From 0c2bcc6cfe2ef7d621e6ff07ec16bff5cf8b6f09 Mon Sep 17 00:00:00 2001 From: yankomissarov Date: Mon, 30 Jun 2025 19:14:05 +0300 Subject: [PATCH] MSP-5358 reimplement --- assembly/locator.go | 5 +++-- middleware/admin_authorize.go | 4 ++-- middleware/entrypoint.go | 23 ++++++++++++--------- proxy/http.go | 1 - proxy/ws.go | 1 - repository/daily_limit.go | 2 +- routes/routes.go | 39 ++++++++++++++++++++++++++++------- tests/acceptance_test.go | 39 +++++++++++++++++++++++++++++------ 8 files changed, 84 insertions(+), 30 deletions(-) diff --git a/assembly/locator.go b/assembly/locator.go index 15f154d..ad12836 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -120,13 +120,14 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location, redisCli ) } entrypoint := middleware.Entrypoint( - config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:mnd,gomnd + config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:mnd handler, - l.logger, middleware.EntryPointConfig{ WithPrefix: location.WithPrefix, PathPrefix: location.PathPrefix, }, + l.routes, + l.logger, ) mux.PathPrefix(location.PathPrefix).Handler(entrypoint) } diff --git a/middleware/admin_authorize.go b/middleware/admin_authorize.go index 4579ca8..5bad0d7 100644 --- a/middleware/admin_authorize.go +++ b/middleware/admin_authorize.go @@ -10,8 +10,8 @@ import ( ) type AdminMethodStore interface { - IsInnerEndpoint(path string) bool - RequiredAdminPermission(path string) (string, bool) + IsInnerEndpoint(endpoint string) bool + RequiredAdminPermission(endpoint string) (string, bool) } type AdminAuthorizer interface { diff --git a/middleware/entrypoint.go b/middleware/entrypoint.go index cdf5eb5..bc1725c 100644 --- a/middleware/entrypoint.go +++ b/middleware/entrypoint.go @@ -1,13 +1,10 @@ package middleware import ( - "fmt" - "net/http" - "strings" - "github.com/pkg/errors" "github.com/txix-open/isp-kit/log" "isp-gate-service/request" + "net/http" ) type EntryPointConfig struct { @@ -15,15 +12,21 @@ type EntryPointConfig struct { WithPrefix bool } -func Entrypoint(maxReqBodySize int64, next Handler, logger log.Logger, cfg EntryPointConfig) http.Handler { +type EndpointResolver interface { + ResolveEndpoint(path string, cfg EntryPointConfig) string +} + +func Entrypoint( + maxReqBodySize int64, + next Handler, + cfg EntryPointConfig, + entryPointResolver EndpointResolver, + logger log.Logger, +) http.Handler { return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) { req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize) - endpoint := req.URL.Path - if !cfg.WithPrefix { - prefix := fmt.Sprintf("%s/", cfg.PathPrefix) - endpoint = strings.TrimPrefix(req.URL.Path, prefix) - } + endpoint := entryPointResolver.ResolveEndpoint(req.URL.Path, cfg) ctx := request.NewContext(req, writer, endpoint) err := next.Handle(ctx) diff --git a/proxy/http.go b/proxy/http.go index 8ce42ca..4581202 100644 --- a/proxy/http.go +++ b/proxy/http.go @@ -18,7 +18,6 @@ import ( "golang.org/x/net/context" ) -// nolint:gomnd var ( httpTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, diff --git a/proxy/ws.go b/proxy/ws.go index c822a01..a41af0b 100644 --- a/proxy/ws.go +++ b/proxy/ws.go @@ -25,7 +25,6 @@ func NewWs(hostManager HttpHostManager, skipAuth bool) Ws { } } -//nolint:gomnd func (ws Ws) Handle(ctx *request.Context) error { host, err := ws.hostManager.Next() if err != nil { diff --git a/repository/daily_limit.go b/repository/daily_limit.go index 653a47a..ef47059 100644 --- a/repository/daily_limit.go +++ b/repository/daily_limit.go @@ -27,7 +27,7 @@ func (r DailyLimit) Increment(ctx context.Context, applicationId int, today time } if value == 1 { - err := r.cli.ExpireNX(ctx, key, 24*time.Hour).Err() //nolint:mnd,gomnd + err := r.cli.ExpireNX(ctx, key, 24*time.Hour).Err() //nolint:mnd if err != nil { return 0, errors.WithMessage(err, "expire nx") } diff --git a/routes/routes.go b/routes/routes.go index bb60c1f..841e59d 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -2,28 +2,34 @@ package routes import ( "context" + "fmt" + "isp-gate-service/middleware" "strings" "github.com/txix-open/isp-kit/cluster" ) type Routes struct { + allEndpoints map[string]bool innerEndpoints map[string]bool requiredPermissions map[string]string } func NewRoutes() *Routes { return &Routes{ + allEndpoints: make(map[string]bool), innerEndpoints: make(map[string]bool), requiredPermissions: make(map[string]string), } } func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error { + newAllEndpoints := make(map[string]bool) newInnerMethods := make(map[string]bool) newRequiredPermissions := make(map[string]string) for _, backend := range routes { for _, v := range backend.Endpoints { + newAllEndpoints[v.Path] = true if v.Inner { newInnerMethods[v.Path] = true } @@ -34,21 +40,40 @@ func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig } } + s.allEndpoints = newAllEndpoints s.innerEndpoints = newInnerMethods s.requiredPermissions = newRequiredPermissions return nil } -func (s *Routes) IsInnerEndpoint(path string) bool { - return s.innerEndpoints[path] || s.innerEndpoints[invertLeadingSlash(path)] +func (s *Routes) ResolveEndpoint(path string, cfg middleware.EntryPointConfig) string { + if cfg.WithPrefix { + return path + } + + prefix := fmt.Sprintf("%s/", cfg.PathPrefix) + noPrefixPath := strings.TrimPrefix(path, prefix) + ok := s.allEndpoints[noPrefixPath] + if ok { + return noPrefixPath + } + + invertedLeadingSlash := invertLeadingSlash(noPrefixPath) + ok = s.allEndpoints[invertedLeadingSlash] + if ok { + return invertedLeadingSlash + } + + return "unknown_endpoint" } -func (s *Routes) RequiredAdminPermission(path string) (string, bool) { - perm, ok := s.requiredPermissions[path] - if !ok { - perm, ok = s.requiredPermissions[invertLeadingSlash(path)] - } +func (s *Routes) IsInnerEndpoint(endpoint string) bool { + return s.innerEndpoints[endpoint] +} + +func (s *Routes) RequiredAdminPermission(endpoint string) (string, bool) { + perm, ok := s.requiredPermissions[endpoint] return perm, ok } diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go index f0705c8..b23ff47 100644 --- a/tests/acceptance_test.go +++ b/tests/acceptance_test.go @@ -72,12 +72,21 @@ func (s *HappyPathTestSuite) TestGrpcProxy() { require.NoError(err) require.EqualValues("1", adminId) - return response{Id: req.Id} //nolint:gosimple + return response{Id: req.Id} }) targetClients := map[string]*client.Client{"target": targetCli} logger, err := log.New(log.WithLevel(log.DebugLevel)) require.NoError(err) - locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli) + + routes := routes.NewRoutes() + err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{ + Path: "endpoint", + }}, + }}) + require.NoError(err) + + locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli) locations := []conf.Location{{ SkipAuth: false, @@ -112,13 +121,22 @@ func (s *HappyPathTestSuite) TestHttpProxy() { targetService := httpt.NewMock(test) targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response { assertHeaders(require, requestId, ctx, httpReq.Header) - return response{Id: req.Id} //nolint:gosimple + return response{Id: req.Id} }) targetUrl, err := url.Parse(targetService.BaseURL()) require.NoError(err) rr := lb.NewRoundRobin([]string{targetUrl.Host}) targetClients := map[string]*lb.RoundRobin{"target": rr} - locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli, adminCli) + + routes := routes.NewRoutes() + err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{ + Path: "/endpoint", + }}, + }}) + require.NoError(err) + + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli) locations := []conf.Location{{ SkipAuth: false, PathPrefix: "/api", @@ -165,7 +183,16 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen require.NoError(err) rr := lb.NewRoundRobin([]string{targetUrl.Host}) targetClients := map[string]*lb.RoundRobin{"target": rr} - locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes.NewRoutes(), systemCli, adminCli) + + routes := routes.NewRoutes() + err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{ + Endpoints: []cluster.EndpointDescriptor{{ + Path: "/service", + }}, + }}) + require.NoError(err) + + locator := assembly.NewLocator(test.Logger(), nil, targetClients, routes, systemCli, adminCli) locations := []conf.Location{{ SkipAuth: false, PathPrefix: "/ws", @@ -219,7 +246,7 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() { targetService, targetCli := grpct.NewMock(test) targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response { - return response{Id: req.Id} //nolint:gosimple + return response{Id: req.Id} }) targetClients := map[string]*client.Client{"target": targetCli} logger, err := log.New(log.WithLevel(log.DebugLevel))