Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
798cc6b30f | ||
|
|
6750784d6b | ||
|
|
45ae8cdd89 | ||
|
|
295513e91c | ||
|
|
36699fdc72 | ||
|
|
a269de8e17 | ||
|
|
15cb2cadf2 | ||
|
|
76f88fd593 | ||
|
|
9ff0057014 | ||
|
|
71a1f0a04e | ||
|
|
394bbc82e2 | ||
|
|
7de248e63c | ||
|
|
011a1d7048 | ||
|
|
f3fb9cff75 | ||
|
|
c7bd042239 | ||
|
|
202fa7035e | ||
|
|
602a2a1ac4 | ||
|
|
6a3abf67a2 | ||
|
|
2f88738f78 | ||
|
|
a637d56ea7 | ||
|
|
a841cd082b | ||
|
|
9b18fe7351 | ||
|
|
f3c801e4a4 | ||
|
|
ee13991d87 | ||
|
|
d4846359e4 | ||
|
|
13cf0075f6 | ||
|
|
135e551473 | ||
|
|
689f730a3e | ||
|
|
a30582fa38 | ||
|
|
5b1ce14467 | ||
|
|
264b438cdb | ||
|
|
f699aefa58 | ||
|
|
8d40e76637 | ||
|
|
e2b4becfd6 | ||
|
|
e4ef2d8645 | ||
|
|
bfc28503d5 | ||
|
|
d759f883f4 | ||
|
|
64373fdf3c | ||
|
|
1dd566593e | ||
|
|
560c1f22c4 | ||
|
|
171b85f627 | ||
|
|
734b83b2b8 | ||
|
|
bdeb2c0753 | ||
|
|
97c44fb3bd | ||
|
|
6db18c1495 | ||
|
|
cd985ff5a3 | ||
|
|
2eed857503 | ||
|
|
2b91caece0 |
No files matched your search
+1
-3
@@ -15,6 +15,7 @@ linters:
|
||||
- nolintlint # Goland все равно форматирует с отступом
|
||||
- perfsprint # мнимая производительность в угоду читаемости
|
||||
- tagalign # не всегда имеет смысл
|
||||
- testpackage
|
||||
- varnamelen # очень индивидуально (db)
|
||||
- wsl # расставление пробелов очень индивидуально
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
@@ -75,9 +76,6 @@ linters:
|
||||
- linters:
|
||||
- wrapcheck
|
||||
path: httperrors #отсутствует необходимость оборачивать ошибки
|
||||
- linters:
|
||||
- goconst
|
||||
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
|
||||
+8
-2
@@ -1,5 +1,11 @@
|
||||
### v5.12.0
|
||||
* взаимодействие с `isp-admin-service` переведено с gRPC на HTTP
|
||||
### 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
|
||||
* Обновлены зависимости
|
||||
### v5.11.4
|
||||
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
|
||||
### v5.11.3
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"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/log"
|
||||
)
|
||||
@@ -31,7 +30,7 @@ type Assembly struct {
|
||||
logger *log.Adapter
|
||||
routes *routes.Routes
|
||||
systemCli *client.Client
|
||||
adminCli *httpclix.ClientBalancer
|
||||
adminCli *client.Client
|
||||
lockerCli *client.Client
|
||||
routerLb *lb.RoundRobin
|
||||
|
||||
@@ -73,7 +72,10 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create system cli")
|
||||
}
|
||||
adminCli := httpclix.DefaultWithBalancer(nil)
|
||||
adminCli, err := client.Default()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create admin cli")
|
||||
}
|
||||
lockerCli, err := client.Default()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "create isp-lock-service client")
|
||||
@@ -171,7 +173,7 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
for _, cliCloser := range a.grpcClientByModuleName {
|
||||
closers = append(closers, cliCloser)
|
||||
}
|
||||
closers = append(closers, a.systemCli, a.lockerCli)
|
||||
closers = append(closers, a.systemCli, a.adminCli, a.lockerCli)
|
||||
|
||||
return closers
|
||||
}
|
||||
+10
-4
@@ -5,7 +5,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/metrics"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
|
||||
@@ -30,7 +29,7 @@ type Locator struct {
|
||||
httpHostManagerByModuleName map[string]*lb.RoundRobin
|
||||
routes *routes.Routes
|
||||
systemCli *client.Client
|
||||
adminCli *httpclix.ClientBalancer
|
||||
adminCli *client.Client
|
||||
lockerCli *client.Client
|
||||
routerLb *lb.RoundRobin
|
||||
usersAuthCache *cache.Cache
|
||||
@@ -42,7 +41,7 @@ func NewLocator(
|
||||
httpHostManagerByModuleName map[string]*lb.RoundRobin,
|
||||
routes *routes.Routes,
|
||||
systemCli *client.Client,
|
||||
adminCli *httpclix.ClientBalancer,
|
||||
adminCli *client.Client,
|
||||
lockerCli *client.Client,
|
||||
routerLb *lb.RoundRobin,
|
||||
usersAuthCache *cache.Cache,
|
||||
@@ -97,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
|
||||
@@ -137,7 +138,8 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
middleware.Logger(
|
||||
l.logger, config.Logging.RequestLogEnable,
|
||||
enableBodyLog,
|
||||
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
||||
skipLogging,
|
||||
skipBodyLoggingEndpointPrefixes,
|
||||
config.Logging.EnableForceUnescapingUnicode,
|
||||
),
|
||||
middleware.RequestId(),
|
||||
@@ -161,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,
|
||||
),
|
||||
@@ -178,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,
|
||||
@@ -185,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, config.Logging.RequestLogEnable, skipLogging)
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
"requestLogEnable": true,
|
||||
"bodyLogEnable": false,
|
||||
"skipBodyLoggingEndpointPrefixes": [],
|
||||
"enableForceUnescapingUnicode": false
|
||||
"enableForceUnescapingUnicode": false,
|
||||
"skipLoggingPathPrefixes": []
|
||||
},
|
||||
"caching": {
|
||||
"authenticationDataInSec": 60,
|
||||
|
||||
@@ -49,6 +49,7 @@ type Logging struct {
|
||||
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
|
||||
SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"`
|
||||
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
|
||||
SkipLoggingPathPrefixes []string `schema:"Полностью не логировать запросы к путям с префиксом из списка (сырой path, query не учитывается, '/' в начале игнорируется). Применяется к логу запросов, предупреждению о неизвестном эндпоинте и логу незнакомых locations"`
|
||||
}
|
||||
|
||||
type Caching struct {
|
||||
|
||||
@@ -8,6 +8,9 @@ type AuthenticateAppResponse struct {
|
||||
|
||||
type AppAuthData struct {
|
||||
AppName string
|
||||
SystemId int
|
||||
DomainId int
|
||||
ServiceId int
|
||||
ApplicationId int
|
||||
}
|
||||
|
||||
|
||||
@@ -2,5 +2,8 @@ package entity
|
||||
|
||||
type AppAuthData struct {
|
||||
AppName string
|
||||
SystemId int
|
||||
DomainId int
|
||||
ServiceId int
|
||||
ApplicationId int
|
||||
}
|
||||
@@ -13,6 +13,7 @@ require (
|
||||
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
|
||||
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
|
||||
)
|
||||
@@ -65,7 +66,6 @@ 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
|
||||
|
||||
+13
-10
@@ -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
|
||||
|
||||
@@ -54,6 +54,7 @@ func Logger( // nolint:gocognit,funlen
|
||||
logger log.Logger,
|
||||
enableRequestLogging bool,
|
||||
enableBodyLogging bool,
|
||||
skipLogging SkipLoggingPaths,
|
||||
skipBodyLoggingEndpointPrefixes []string,
|
||||
enableForceUnescapingUnicode bool,
|
||||
) Middleware {
|
||||
@@ -65,6 +66,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 {
|
||||
|
||||
@@ -18,10 +18,10 @@ func (f HandlerFunc) Handle(ctx *request.Context) error {
|
||||
|
||||
type Middleware func(next Handler) Handler
|
||||
|
||||
// nolint:ireturn
|
||||
//nolint:ireturn // Chain по определению возвращает Handler-интерфейс
|
||||
func Chain(root Handler, middlewares ...Middleware) Handler {
|
||||
for _, middleware := range slices.Backward(middlewares) {
|
||||
root = middleware(root)
|
||||
for _, m := range slices.Backward(middlewares) {
|
||||
root = m(root)
|
||||
}
|
||||
return root
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import "strings"
|
||||
|
||||
// SkipLoggingPaths — префиксы сырого request path, для которых
|
||||
// полностью отключено логирование (строка лога, не только тела).
|
||||
type SkipLoggingPaths struct {
|
||||
prefixes []string
|
||||
}
|
||||
|
||||
// NewSkipLoggingPaths нормализует значения конфы: обрезает ведущий '/',
|
||||
// отбрасывает пустые.
|
||||
func NewSkipLoggingPaths(rawPrefixes []string) SkipLoggingPaths {
|
||||
prefixes := make([]string, 0, len(rawPrefixes))
|
||||
for _, p := range rawPrefixes {
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
if p != "" {
|
||||
prefixes = append(prefixes, p)
|
||||
}
|
||||
}
|
||||
return SkipLoggingPaths{prefixes: prefixes}
|
||||
}
|
||||
|
||||
// ShouldSkip — case-sensitive prefix-match. path — сырой r.URL.Path.
|
||||
func (s SkipLoggingPaths) ShouldSkip(path string) bool {
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
for _, p := range s.prefixes {
|
||||
if strings.HasPrefix(path, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"isp-gate-service/middleware"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSkipLoggingPaths_ShouldSkip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
prefixes []string
|
||||
path string
|
||||
wantSkip bool
|
||||
}{
|
||||
{name: "prefix without leading slash", prefixes: []string{"health"}, path: "/health", wantSkip: true},
|
||||
{name: "prefix with leading slash is equivalent", prefixes: []string{"/health"}, path: "/health", wantSkip: true},
|
||||
{name: "no match", prefixes: []string{"health"}, path: "/other", wantSkip: false},
|
||||
{name: "empty value is discarded", prefixes: []string{""}, path: "/health", wantSkip: false},
|
||||
{name: "root slash value is discarded", prefixes: []string{"/"}, path: "/health", wantSkip: false},
|
||||
{name: "case sensitive", prefixes: []string{"Health"}, path: "/health/x", wantSkip: false},
|
||||
{name: "plain prefix matches longer name", prefixes: []string{"health"}, path: "/healthz", wantSkip: true},
|
||||
{name: "plain prefix matches nested path", prefixes: []string{"health"}, path: "/health/x", wantSkip: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
matcher := middleware.NewSkipLoggingPaths(test.prefixes)
|
||||
require.Equal(t, test.wantSkip, matcher.ShouldSkip(test.path))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipLoggingPaths_ShouldSkip_EmptyList(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
matcher := middleware.NewSkipLoggingPaths(nil)
|
||||
for _, path := range []string{"/", "/health", "/health/x", "/unknown"} {
|
||||
require.False(t, matcher.ShouldSkip(path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
@@ -164,6 +164,9 @@ func (p Grpc) writeMetadata(ctx *request.Context) metadata.MD {
|
||||
|
||||
appAuthData, err := ctx.GetAuthData()
|
||||
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)}
|
||||
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
|
||||
md[grpc.ApplicationNameHeader] = []string{encodedAppName}
|
||||
|
||||
@@ -110,6 +110,9 @@ func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
|
||||
|
||||
appAuthData, err := ctx.GetAuthData()
|
||||
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))
|
||||
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
|
||||
header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
|
||||
|
||||
+3
-2
@@ -6,11 +6,12 @@ import (
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/tomakado/websocketproxy"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"isp-gate-service/httperrors"
|
||||
"isp-gate-service/request"
|
||||
)
|
||||
|
||||
type Ws struct {
|
||||
|
||||
+9
-16
@@ -7,8 +7,7 @@ import (
|
||||
"isp-gate-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -17,39 +16,33 @@ const (
|
||||
)
|
||||
|
||||
type Admin struct {
|
||||
cli *httpclix.ClientBalancer
|
||||
cli *client.Client
|
||||
}
|
||||
|
||||
func NewAdmin(cli *httpclix.ClientBalancer) Admin {
|
||||
func NewAdmin(cli *client.Client) Admin {
|
||||
return Admin{cli: cli}
|
||||
}
|
||||
|
||||
func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, adminAuthenticate)
|
||||
|
||||
resp := entity.AdminAuthenticateResponse{}
|
||||
err := r.cli.Post(adminAuthenticate).
|
||||
err := r.cli.Invoke(adminAuthenticate).
|
||||
JsonRequestBody(entity.AuthenticateRequest{Token: token}).
|
||||
JsonResponseBody(&resp).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
Do(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "http client invoke %s", adminAuthenticate)
|
||||
return nil, errors.WithMessagef(err, "grpc client invoke %s", adminAuthenticate)
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, adminAuthorize)
|
||||
|
||||
resp := entity.AdminAuthorizeResponse{}
|
||||
err := r.cli.Post(adminAuthorize).
|
||||
err := r.cli.Invoke(adminAuthorize).
|
||||
JsonRequestBody(entity.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
|
||||
JsonResponseBody(&resp).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
Do(ctx)
|
||||
if err != nil {
|
||||
return false, errors.WithMessagef(err, "http client invoke %s", adminAuthorize)
|
||||
return false, errors.WithMessagef(err, "grpc client invoke: %s", adminAuthorize)
|
||||
}
|
||||
return resp.Authorized, nil
|
||||
}
|
||||
@@ -74,6 +74,9 @@ func (Authentication) convertAuthData(authData *entity.AppAuthData) *domain.AppA
|
||||
|
||||
return &domain.AppAuthData{
|
||||
AppName: authData.AppName,
|
||||
SystemId: authData.SystemId,
|
||||
DomainId: authData.DomainId,
|
||||
ServiceId: authData.ServiceId,
|
||||
ApplicationId: authData.ApplicationId,
|
||||
}
|
||||
}
|
||||
+36
-24
@@ -1,5 +1,5 @@
|
||||
// nolint:canonicalheader
|
||||
package tests_test
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"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/test/fake"
|
||||
|
||||
@@ -60,9 +59,18 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
||||
requestId := requestid.Next()
|
||||
targetService, targetCli := grpct.NewMock(test)
|
||||
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()
|
||||
require.NoError(err)
|
||||
require.EqualValues(requestId, requestid.FromContext(ctx))
|
||||
require.EqualValues(1, systemId)
|
||||
require.EqualValues(2, domainId)
|
||||
require.EqualValues(3, serviceId)
|
||||
require.EqualValues(4, applicationId)
|
||||
|
||||
adminId, err := grpc.StringFromMd("x-admin-id", metadata.MD(authData))
|
||||
@@ -572,7 +580,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
|
||||
}
|
||||
|
||||
// nolint:ireturn
|
||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *httpclix.ClientBalancer) {
|
||||
func (s *HappyPathTestSuite) commonDependencies(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,
|
||||
@@ -589,6 +597,9 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AuthData: &entity.AppAuthData{
|
||||
SystemId: 1,
|
||||
DomainId: 2,
|
||||
ServiceId: 3,
|
||||
ApplicationId: 4,
|
||||
AppName: "test",
|
||||
},
|
||||
@@ -597,27 +608,19 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
|
||||
return entity.AuthorizeResponse{Authorized: true}
|
||||
})
|
||||
|
||||
adminMux := router.New()
|
||||
defaultWrapper := endpoint.DefaultWrapper(test.Logger(), httplog.Noop())
|
||||
adminMux.POST("/admin/secure/authenticate",
|
||||
defaultWrapper.Endpoint(func(req entity.AuthenticateRequest) entity.AdminAuthenticateResponse {
|
||||
return entity.AdminAuthenticateResponse{
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AdminId: 1,
|
||||
}
|
||||
}))
|
||||
adminMux.POST("/admin/secure/authorize",
|
||||
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})
|
||||
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 {
|
||||
if req.Permission == "ok_permission" {
|
||||
return entity.AdminAuthorizeResponse{Authorized: true}
|
||||
}
|
||||
return entity.AdminAuthorizeResponse{Authorized: false}
|
||||
})
|
||||
|
||||
return config, systemCli, adminCli
|
||||
}
|
||||
@@ -628,9 +631,18 @@ 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"))
|
||||
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"))
|
||||
require.NoError(err)
|
||||
require.EqualValues(requestId, requestid.FromContext(ctx))
|
||||
require.EqualValues(1, systemId)
|
||||
require.EqualValues(2, domainId)
|
||||
require.EqualValues(3, serviceId)
|
||||
require.EqualValues(4, applicationId)
|
||||
expectedAppName := base64.StdEncoding.EncodeToString([]byte("test"))
|
||||
require.EqualValues(expectedAppName, headers.Get("x-application-name"))
|
||||
|
||||
+21
-30
@@ -4,11 +4,10 @@ import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/routes"
|
||||
|
||||
@@ -18,10 +17,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -60,12 +55,15 @@ func main() {
|
||||
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}},
|
||||
}
|
||||
|
||||
systemService, systemCli := NewMock(logger)
|
||||
systemService, systemCli, _ := NewMock(logger)
|
||||
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
|
||||
return entity.AuthenticateResponse{
|
||||
Authenticated: true,
|
||||
ErrorReason: "",
|
||||
AuthData: &entity.AppAuthData{
|
||||
SystemId: 1,
|
||||
DomainId: 1,
|
||||
ServiceId: 1,
|
||||
ApplicationId: 1,
|
||||
},
|
||||
}
|
||||
@@ -73,9 +71,16 @@ func main() {
|
||||
return entity.AuthorizeResponse{Authorized: true}
|
||||
})
|
||||
|
||||
adminCli := NewAdminMock(logger)
|
||||
adminService, _, adminCli := NewMock(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 {
|
||||
return response{Id: req.Id}
|
||||
})
|
||||
@@ -97,33 +102,19 @@ func main() {
|
||||
srv.ListenAndServe()
|
||||
}
|
||||
|
||||
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) {
|
||||
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client, *client.Client) {
|
||||
listener, _ := net.Listen("tcp", "127.0.0.1:") // nolint:noctx
|
||||
srv := grpc.NewServer()
|
||||
sysCli, _ := client.Default()
|
||||
adminCli, _ := client.Default()
|
||||
srv.Upgrade(service)
|
||||
go func() {
|
||||
_ = srv.Serve(listener)
|
||||
}()
|
||||
|
||||
sysCli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, sysCli
|
||||
adminCli.Upgrade([]string{listener.Addr().String()})
|
||||
return srv, sysCli, adminCli
|
||||
}
|
||||
|
||||
type MockServer struct {
|
||||
@@ -132,13 +123,13 @@ type MockServer struct {
|
||||
mockEndpoints map[string]any
|
||||
}
|
||||
|
||||
func NewMock(logger log.Logger) (*MockServer, *client.Client) {
|
||||
srv, syscli := TestServer(grpc.NewMux())
|
||||
func NewMock(logger log.Logger) (*MockServer, *client.Client, *client.Client) {
|
||||
srv, syscli, admincli := TestServer(grpc.NewMux())
|
||||
return &MockServer{
|
||||
srv: srv,
|
||||
logger: logger,
|
||||
mockEndpoints: make(map[string]any),
|
||||
}, syscli
|
||||
}, syscli, admincli
|
||||
}
|
||||
|
||||
func (m *MockServer) Mock(endpoint string, handler any) *MockServer {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
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))
|
||||
}
|
||||
Reference in new issue
Block a user