MSP-7042 Ref routes.Routes
This commit is contained in:
1 parent
29cdf42808
commit
2ddb3a3d1f
19 files changed
+193
-102
No files matched your search
@@ -74,7 +74,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
|||||||
boot: boot,
|
boot: boot,
|
||||||
server: server,
|
server: server,
|
||||||
logger: boot.App.Logger(),
|
logger: boot.App.Logger(),
|
||||||
routes: routes.NewRoutes(),
|
routes: routes.NewRoutes(boot.App.Logger()),
|
||||||
locations: localConfig.Locations,
|
locations: localConfig.Locations,
|
||||||
grpcClientByModuleName: grpcClientByModuleName,
|
grpcClientByModuleName: grpcClientByModuleName,
|
||||||
httpHostManagerByModuleName: httpHostManagerByModuleName,
|
httpHostManagerByModuleName: httpHostManagerByModuleName,
|
||||||
|
|||||||
+11
-5
@@ -1,11 +1,12 @@
|
|||||||
package assembly
|
package assembly
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/txix-open/isp-kit/metrics"
|
|
||||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/metrics"
|
||||||
|
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||||
|
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
"isp-gate-service/middleware"
|
"isp-gate-service/middleware"
|
||||||
"isp-gate-service/proxy"
|
"isp-gate-service/proxy"
|
||||||
@@ -110,13 +111,16 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
middleware.Authenticate(authentication),
|
middleware.Authenticate(authentication),
|
||||||
middleware.AdminAuthenticate(adminService),
|
middleware.AdminAuthenticate(adminService),
|
||||||
middleware.Authorize(authorization, l.logger),
|
middleware.Authorize(authorization, l.logger),
|
||||||
middleware.AdminAuthorize(l.routes, adminService),
|
middleware.AdminAuthorize(adminService),
|
||||||
middleware.Throttling(throttlingService),
|
middleware.Throttling(throttlingService),
|
||||||
middleware.DailyLimit(dailyLimitService),
|
middleware.DailyLimit(dailyLimitService),
|
||||||
middleware.RequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
middleware.RequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||||
middleware.Metrics(metricsStorage),
|
middleware.Metrics(metricsStorage),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
errorOnUnknownEndpoint := true
|
||||||
if location.SkipAuth {
|
if location.SkipAuth {
|
||||||
|
errorOnUnknownEndpoint = false
|
||||||
handler = middleware.Chain(
|
handler = middleware.Chain(
|
||||||
proxyFunc,
|
proxyFunc,
|
||||||
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
|
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
|
||||||
@@ -133,8 +137,10 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:mnd
|
config.Http.MaxRequestBodySizeInMb*1024*1024, //nolint:mnd
|
||||||
handler,
|
handler,
|
||||||
middleware.EntryPointConfig{
|
middleware.EntryPointConfig{
|
||||||
WithPrefix: location.WithPrefix,
|
WithPrefix: location.WithPrefix,
|
||||||
PathPrefix: location.PathPrefix,
|
PathPrefix: location.PathPrefix,
|
||||||
|
ErrorOnUnknownEndpoint: errorOnUnknownEndpoint,
|
||||||
|
WithLendingSlash: location.Protocol != conf.GrpcProtocol,
|
||||||
},
|
},
|
||||||
l.routes,
|
l.routes,
|
||||||
l.logger,
|
l.logger,
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "context"
|
||||||
|
|
||||||
|
type EndpointMeta struct {
|
||||||
|
Inner bool
|
||||||
|
RequiredAdminPermission string
|
||||||
|
// Объявляемый сервисом метод
|
||||||
|
PathSchema string
|
||||||
|
// Вызываемый метод
|
||||||
|
Endpoint string
|
||||||
|
}
|
||||||
|
|
||||||
|
type endpointMetaKey struct{}
|
||||||
|
|
||||||
|
func (m EndpointMeta) ToContext(ctx context.Context) context.Context {
|
||||||
|
return context.WithValue(ctx, endpointMetaKey{}, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
func EndpointMetaFromContext(ctx context.Context) EndpointMeta {
|
||||||
|
meta, _ := ctx.Value(endpointMetaKey{}).(EndpointMeta)
|
||||||
|
return meta
|
||||||
|
}
|
||||||
@@ -10,7 +10,7 @@ require (
|
|||||||
github.com/redis/go-redis/v9 v9.11.0
|
github.com/redis/go-redis/v9 v9.11.0
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
github.com/tomakado/websocketproxy v0.1.0
|
github.com/tomakado/websocketproxy v0.1.0
|
||||||
github.com/txix-open/isp-kit v1.64.6
|
github.com/txix-open/isp-kit v1.31.5-0.20260122130000-6a7f11644724
|
||||||
github.com/txix-open/jsonschema v1.3.0
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
golang.org/x/net v0.47.0
|
golang.org/x/net v0.47.0
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20250908214217-97024824d090
|
||||||
@@ -40,7 +40,7 @@ require (
|
|||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect
|
||||||
github.com/json-iterator/go v1.1.12 // indirect
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
github.com/julienschmidt/httprouter v1.3.0
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mailru/easyjson v0.9.0 // indirect
|
github.com/mailru/easyjson v0.9.0 // indirect
|
||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
|
|||||||
@@ -125,8 +125,8 @@ github.com/txix-open/etp/v4 v4.0.1 h1:5VSYgGsvnMz0tvUHsjVWFETI0qWBTCF1O3ARCHaCIg
|
|||||||
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
github.com/txix-open/etp/v4 v4.0.1/go.mod h1:FIu7TUDdwcgmtmF6tFTV1bGA2fRY/iVaPQdsGzvqYc8=
|
||||||
github.com/txix-open/grmq v1.9.0 h1:ArDbJJcFX9zXKEcPf49rp9nYiRyGMJxGKJAxdbSsfaM=
|
github.com/txix-open/grmq v1.9.0 h1:ArDbJJcFX9zXKEcPf49rp9nYiRyGMJxGKJAxdbSsfaM=
|
||||||
github.com/txix-open/grmq v1.9.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
github.com/txix-open/grmq v1.9.0/go.mod h1:EyFOP17KrwEFOUjR+PH8iH3LCtiN9TSQ8t0ysyk62po=
|
||||||
github.com/txix-open/isp-kit v1.64.6 h1:AXQ8/HQGG1VoJyiFvPqgPimPp5WJ4MrlWzPBxuxqhRs=
|
github.com/txix-open/isp-kit v1.31.5-0.20260122130000-6a7f11644724 h1:Fo/MFRZo2UVrE8q9aLWE+1076cQlK+xveWNIWW/gC7M=
|
||||||
github.com/txix-open/isp-kit v1.64.6/go.mod h1:GvBsX5p2U3/ugK6PuWANYzSy/4YgawROm3eAKb35G6o=
|
github.com/txix-open/isp-kit v1.31.5-0.20260122130000-6a7f11644724/go.mod h1:GvBsX5p2U3/ugK6PuWANYzSy/4YgawROm3eAKb35G6o=
|
||||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/txix-open/isp-kit/bootstrap"
|
|
||||||
"github.com/txix-open/isp-kit/shutdown"
|
|
||||||
"isp-gate-service/assembly"
|
"isp-gate-service/assembly"
|
||||||
"isp-gate-service/conf"
|
"isp-gate-service/conf"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/bootstrap"
|
||||||
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
|
"github.com/txix-open/isp-kit/shutdown"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -12,7 +14,7 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
boot := bootstrap.New(version, conf.Remote{}, nil)
|
boot := bootstrap.New(version, conf.Remote{}, nil, cluster.HttpTransport)
|
||||||
app := boot.App
|
app := boot.App
|
||||||
logger := app.Logger()
|
logger := app.Logger()
|
||||||
|
|
||||||
|
|||||||
@@ -9,19 +9,16 @@ import (
|
|||||||
"isp-gate-service/request"
|
"isp-gate-service/request"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AdminMethodStore interface {
|
|
||||||
IsInnerEndpoint(endpoint string) bool
|
|
||||||
RequiredAdminPermission(endpoint string) (string, bool)
|
|
||||||
}
|
|
||||||
|
|
||||||
type AdminAuthorizer interface {
|
type AdminAuthorizer interface {
|
||||||
AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error)
|
AdminAuthorize(ctx context.Context, adminId int, permission string) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middleware {
|
func AdminAuthorize(authorizer AdminAuthorizer) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
isInner := store.IsInnerEndpoint(ctx.Endpoint())
|
endpointMeta := ctx.EndpointMeta()
|
||||||
|
|
||||||
|
isInner := endpointMeta.Inner
|
||||||
if !isInner {
|
if !isInner {
|
||||||
return next.Handle(ctx)
|
return next.Handle(ctx)
|
||||||
}
|
}
|
||||||
@@ -30,12 +27,13 @@ func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middlewa
|
|||||||
return httperrors.New(
|
return httperrors.New(
|
||||||
http.StatusForbidden,
|
http.StatusForbidden,
|
||||||
"admin authentication required",
|
"admin authentication required",
|
||||||
errors.Errorf("admin authorization: admin authentication required for '%s'", ctx.Endpoint()),
|
errors.Errorf("admin authorization: admin authentication required for '%s'",
|
||||||
|
endpointMeta.Endpoint),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
requiredPerm, ok := store.RequiredAdminPermission(ctx.Endpoint())
|
requiredPerm := endpointMeta.RequiredAdminPermission
|
||||||
if !ok {
|
if requiredPerm == "" {
|
||||||
return next.Handle(ctx)
|
return next.Handle(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,7 +47,7 @@ func AdminAuthorize(store AdminMethodStore, authorizer AdminAuthorizer) Middlewa
|
|||||||
"endpoint is not allowed",
|
"endpoint is not allowed",
|
||||||
errors.Errorf(
|
errors.Errorf(
|
||||||
"admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it",
|
"admin authorization: endpoint '%s' requires '%s' permission, but admin '%d' doesn't have it",
|
||||||
ctx.Endpoint(), requiredPerm, ctx.AdminId(),
|
endpointMeta.Endpoint, requiredPerm, ctx.AdminId(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Authorizer interface {
|
type Authorizer interface {
|
||||||
Authorize(ctx context.Context, applicationId int, httpMethod string, endpoint string) (bool, error)
|
Authorize(ctx context.Context, applicationId int, httpMethod string, pathSchema string) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
||||||
@@ -22,11 +22,12 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
|||||||
return errors.WithMessage(err, "authorize: get auth data")
|
return errors.WithMessage(err, "authorize: get auth data")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
endpointMeta := ctx.EndpointMeta()
|
||||||
ok, err := authorizer.Authorize(
|
ok, err := authorizer.Authorize(
|
||||||
ctx.Context(),
|
ctx.Context(),
|
||||||
authData.ApplicationId,
|
authData.ApplicationId,
|
||||||
ctx.Request().Method,
|
ctx.Request().Method,
|
||||||
ctx.Endpoint(),
|
endpointMeta.PathSchema,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "authorize: authorize")
|
return errors.WithMessage(err, "authorize: authorize")
|
||||||
@@ -46,7 +47,7 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
|||||||
http.StatusForbidden,
|
http.StatusForbidden,
|
||||||
"endpoint is not allowed",
|
"endpoint is not allowed",
|
||||||
errors.Errorf("authorize: endpoint '%s' with http method '%s' is not allowed for application '%d'",
|
errors.Errorf("authorize: endpoint '%s' with http method '%s' is not allowed for application '%d'",
|
||||||
ctx.Endpoint(), ctx.Request().Method, authData.ApplicationId,
|
endpointMeta.PathSchema, ctx.Request().Method, authData.ApplicationId,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,23 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"isp-gate-service/domain"
|
||||||
"github.com/txix-open/isp-kit/log"
|
|
||||||
"isp-gate-service/request"
|
"isp-gate-service/request"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type EntryPointConfig struct {
|
type EntryPointConfig struct {
|
||||||
PathPrefix string
|
PathPrefix string
|
||||||
WithPrefix bool
|
WithPrefix bool
|
||||||
|
ErrorOnUnknownEndpoint bool
|
||||||
|
WithLendingSlash bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type EndpointResolver interface {
|
type EndpointResolver interface {
|
||||||
ResolveEndpoint(path string, cfg EntryPointConfig) string
|
ResolveEndpoint(method string, path string, cfg EntryPointConfig) (*domain.EndpointMeta, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Entrypoint(
|
func Entrypoint(
|
||||||
@@ -26,10 +30,15 @@ func Entrypoint(
|
|||||||
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
|
return http.HandlerFunc(func(writer http.ResponseWriter, req *http.Request) {
|
||||||
req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize)
|
req.Body = http.MaxBytesReader(writer, req.Body, maxReqBodySize)
|
||||||
|
|
||||||
endpoint := entryPointResolver.ResolveEndpoint(req.URL.Path, cfg)
|
endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(writer, err.Error(), http.StatusNotImplemented)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
ctx := request.NewContext(req, writer, endpoint)
|
ctx := request.NewContext(req, writer, endpoint)
|
||||||
|
|
||||||
err := next.Handle(ctx)
|
err = next.Handle(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Error(req.Context(), errors.WithMessage(err, "uncaught error"))
|
logger.Error(req.Context(), errors.WithMessage(err, "uncaught error"))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ func Logger( // nolint:gocognit
|
|||||||
logBodyFromCurrenRequest := enableBodyLogging
|
logBodyFromCurrenRequest := enableBodyLogging
|
||||||
if logBodyFromCurrenRequest {
|
if logBodyFromCurrenRequest {
|
||||||
for _, prefix := range skipBodyLoggingEndpointPrefixes {
|
for _, prefix := range skipBodyLoggingEndpointPrefixes {
|
||||||
if strings.HasPrefix(ctx.Endpoint(), prefix) {
|
if strings.HasPrefix(ctx.EndpointMeta().Endpoint, prefix) {
|
||||||
logBodyFromCurrenRequest = false
|
logBodyFromCurrenRequest = false
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -110,7 +110,7 @@ func Logger( // nolint:gocognit
|
|||||||
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
|
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
|
||||||
log.Int("statusCode", scSrc.StatusCode()),
|
log.Int("statusCode", scSrc.StatusCode()),
|
||||||
log.String("path", originalPath),
|
log.String("path", originalPath),
|
||||||
log.String("endpoint", ctx.Endpoint()),
|
log.String("endpoint", ctx.EndpointMeta().Endpoint),
|
||||||
log.Int("applicationId", authData.ApplicationId),
|
log.Int("applicationId", authData.ApplicationId),
|
||||||
log.String("applicationName", authData.AppName),
|
log.String("applicationName", authData.AppName),
|
||||||
log.Int("adminId", ctx.AdminId()),
|
log.Int("adminId", ctx.AdminId()),
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ import (
|
|||||||
func Metrics(storage *http_metrics.ServerStorage) Middleware {
|
func Metrics(storage *http_metrics.ServerStorage) Middleware {
|
||||||
return func(next Handler) Handler {
|
return func(next Handler) Handler {
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
endpoint := ctx.Endpoint()
|
pathSchema := ctx.EndpointMeta().PathSchema
|
||||||
if endpoint == "" {
|
if pathSchema == "" {
|
||||||
return next.Handle(ctx)
|
return next.Handle(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ func Metrics(storage *http_metrics.ServerStorage) Middleware {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
storage.ObserveDuration(r.Method, endpoint, time.Since(start))
|
storage.ObserveDuration(r.Method, pathSchema, time.Since(start))
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|||||||
+2
-2
@@ -71,7 +71,7 @@ func (p Grpc) Handle(ctx *request.Context) error {
|
|||||||
|
|
||||||
requestId := requestid.FromContext(ctx.Context())
|
requestId := requestid.FromContext(ctx.Context())
|
||||||
md := metadata.MD{
|
md := metadata.MD{
|
||||||
grpc.ProxyMethodNameHeader: {ctx.Endpoint()},
|
grpc.ProxyMethodNameHeader: {ctx.EndpointMeta().Endpoint},
|
||||||
requestid.Header: {requestId},
|
requestid.Header: {requestId},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ func (p Grpc) Handle(ctx *request.Context) error {
|
|||||||
Body: &isp.Message_BytesBody{BytesBody: body},
|
Body: &isp.Message_BytesBody{BytesBody: body},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return p.handleError(err, ctx.ResponseWriter(), ctx.Endpoint())
|
return p.handleError(err, ctx.ResponseWriter(), ctx.EndpointMeta().Endpoint)
|
||||||
}
|
}
|
||||||
|
|
||||||
return p.writeResponse(http.StatusOK, result.GetBytesBody(), requestId, ctx.ResponseWriter())
|
return p.writeResponse(http.StatusOK, result.GetBytesBody(), requestId, ctx.ResponseWriter())
|
||||||
|
|||||||
+1
-1
@@ -66,7 +66,7 @@ func (p Http) Handle(ctx *request.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
request := ctx.Request()
|
request := ctx.Request()
|
||||||
request.URL.Path = ctx.Endpoint()
|
request.URL.Path = ctx.EndpointMeta().Endpoint
|
||||||
err = setHttpHeaders(ctx, request.Header, p.skipAuth)
|
err = setHttpHeaders(ctx, request.Header, p.skipAuth)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
+1
-1
@@ -38,7 +38,7 @@ func (ws Ws) Handle(ctx *request.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
request := ctx.Request()
|
request := ctx.Request()
|
||||||
request.URL.Path = ctx.Endpoint()
|
request.URL.Path = ctx.EndpointMeta().Endpoint
|
||||||
|
|
||||||
var resultError error
|
var resultError error
|
||||||
proxy := websocketproxy.NewProxy(target)
|
proxy := websocketproxy.NewProxy(target)
|
||||||
|
|||||||
+10
-5
@@ -2,6 +2,7 @@ package request
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"isp-gate-service/domain"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ type Context struct {
|
|||||||
request *http.Request
|
request *http.Request
|
||||||
responseWriter http.ResponseWriter
|
responseWriter http.ResponseWriter
|
||||||
|
|
||||||
endpoint string
|
endpointMeta *domain.EndpointMeta
|
||||||
|
|
||||||
authenticated bool
|
authenticated bool
|
||||||
authData *AuthData
|
authData *AuthData
|
||||||
@@ -36,11 +37,15 @@ type Context struct {
|
|||||||
queryParams map[string]string
|
queryParams map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewContext(request *http.Request, response http.ResponseWriter, endpoint string) *Context {
|
func NewContext(
|
||||||
|
request *http.Request,
|
||||||
|
response http.ResponseWriter,
|
||||||
|
endpointMeta *domain.EndpointMeta,
|
||||||
|
) *Context {
|
||||||
return &Context{
|
return &Context{
|
||||||
request: request,
|
request: request,
|
||||||
responseWriter: response,
|
responseWriter: response,
|
||||||
endpoint: endpoint,
|
endpointMeta: endpointMeta,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,8 +61,8 @@ func (c *Context) SetResponseWriter(writer http.ResponseWriter) {
|
|||||||
c.responseWriter = writer
|
c.responseWriter = writer
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) Endpoint() string {
|
func (c *Context) EndpointMeta() *domain.EndpointMeta {
|
||||||
return c.endpoint
|
return c.endpointMeta
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Context) Authenticate(authData AuthData) {
|
func (c *Context) Authenticate(authData AuthData) {
|
||||||
|
|||||||
+80
-49
@@ -2,85 +2,116 @@ package routes
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"isp-gate-service/domain"
|
||||||
"isp-gate-service/middleware"
|
"isp-gate-service/middleware"
|
||||||
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
|
"github.com/julienschmidt/httprouter"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/cluster"
|
"github.com/txix-open/isp-kit/cluster"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Routes struct {
|
type Routes struct {
|
||||||
allEndpoints map[string]bool
|
logger log.Logger
|
||||||
innerEndpoints map[string]bool
|
allHttpMethods []string
|
||||||
requiredPermissions map[string]string
|
router *httprouter.Router
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRoutes() *Routes {
|
func NewRoutes(logger log.Logger) *Routes {
|
||||||
return &Routes{
|
return &Routes{
|
||||||
allEndpoints: make(map[string]bool),
|
logger: logger,
|
||||||
innerEndpoints: make(map[string]bool),
|
allHttpMethods: []string{
|
||||||
requiredPermissions: make(map[string]string),
|
http.MethodGet,
|
||||||
|
http.MethodHead,
|
||||||
|
http.MethodPost,
|
||||||
|
http.MethodPut,
|
||||||
|
http.MethodPatch,
|
||||||
|
http.MethodDelete,
|
||||||
|
http.MethodConnect,
|
||||||
|
http.MethodOptions,
|
||||||
|
http.MethodTrace,
|
||||||
|
},
|
||||||
|
router: httprouter.New(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error {
|
func (s *Routes) ReceiveRoutes(ctx context.Context, routes cluster.RoutingConfig) error {
|
||||||
newAllEndpoints := make(map[string]bool)
|
router := httprouter.New()
|
||||||
newInnerMethods := make(map[string]bool)
|
|
||||||
newRequiredPermissions := make(map[string]string)
|
|
||||||
for _, backend := range routes {
|
for _, backend := range routes {
|
||||||
for _, v := range backend.Endpoints {
|
for _, descriptor := range backend.Endpoints {
|
||||||
newAllEndpoints[v.Path] = true
|
path := normalizeDescriptorPath(descriptor.Path)
|
||||||
if v.Inner {
|
if descriptor.HttpMethod != "" {
|
||||||
newInnerMethods[v.Path] = true
|
s.registerEndpoint(router, descriptor.HttpMethod, path, descriptor)
|
||||||
}
|
} else {
|
||||||
perm, ok := cluster.GetRequiredAdminPermission(v)
|
for _, httpMethod := range s.allHttpMethods {
|
||||||
if ok {
|
s.registerEndpoint(router, httpMethod, path, descriptor)
|
||||||
newRequiredPermissions[v.Path] = perm
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
s.allEndpoints = newAllEndpoints
|
s.router = router
|
||||||
s.innerEndpoints = newInnerMethods
|
|
||||||
s.requiredPermissions = newRequiredPermissions
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Routes) ResolveEndpoint(path string, cfg middleware.EntryPointConfig) string {
|
func (s *Routes) ResolveEndpoint(method string, path string, cfg middleware.EntryPointConfig) (*domain.EndpointMeta, error) {
|
||||||
if cfg.WithPrefix {
|
lookupPath := path
|
||||||
return path
|
if !cfg.WithPrefix {
|
||||||
|
lookupPath = strings.TrimPrefix(lookupPath, cfg.PathPrefix)
|
||||||
}
|
}
|
||||||
|
|
||||||
prefix := fmt.Sprintf("%s/", cfg.PathPrefix)
|
handler, params, _ := s.router.Lookup(method, lookupPath)
|
||||||
noPrefixPath := strings.TrimPrefix(path, prefix)
|
|
||||||
ok := s.allEndpoints[noPrefixPath]
|
metaEndpoint := lookupPath
|
||||||
if ok {
|
if !cfg.WithLendingSlash {
|
||||||
return noPrefixPath
|
metaEndpoint = strings.TrimLeft(metaEndpoint, "/")
|
||||||
}
|
}
|
||||||
|
|
||||||
invertedLeadingSlash := invertLeadingSlash(noPrefixPath)
|
if handler == nil {
|
||||||
ok = s.allEndpoints[invertedLeadingSlash]
|
if cfg.ErrorOnUnknownEndpoint {
|
||||||
if ok {
|
return nil, errors.Errorf("unknown endpoint '%s'", lookupPath)
|
||||||
return invertedLeadingSlash
|
}
|
||||||
|
return &domain.EndpointMeta{
|
||||||
|
Endpoint: metaEndpoint,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return noPrefixPath // pdp-webapi-service(анонсирует вот такой ендпоинт GET /api/:token/profile/me/:blocks) hack =(
|
req, _ := http.NewRequestWithContext(context.Background(), method, lookupPath, nil)
|
||||||
|
handler(nil, req, params)
|
||||||
|
|
||||||
|
meta := domain.EndpointMetaFromContext(req.Context())
|
||||||
|
meta.Endpoint = metaEndpoint
|
||||||
|
return &meta, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Routes) IsInnerEndpoint(endpoint string) bool {
|
func (s *Routes) registerEndpoint(
|
||||||
return s.innerEndpoints[endpoint]
|
router *httprouter.Router,
|
||||||
}
|
httpMethod string,
|
||||||
|
path string,
|
||||||
|
descriptor cluster.EndpointDescriptor,
|
||||||
|
) {
|
||||||
|
defer func() {
|
||||||
|
_ = recover()
|
||||||
|
}()
|
||||||
|
|
||||||
func (s *Routes) RequiredAdminPermission(endpoint string) (string, bool) {
|
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
||||||
perm, ok := s.requiredPermissions[endpoint]
|
meta := domain.EndpointMeta{
|
||||||
return perm, ok
|
Inner: descriptor.Inner,
|
||||||
}
|
RequiredAdminPermission: requiredAdminPerm,
|
||||||
|
PathSchema: descriptor.Path,
|
||||||
func invertLeadingSlash(path string) string {
|
|
||||||
path, withoutSlash := strings.CutPrefix(path, "/")
|
|
||||||
if withoutSlash {
|
|
||||||
return path
|
|
||||||
}
|
}
|
||||||
return "/" + path
|
|
||||||
|
router.HandlerFunc(
|
||||||
|
httpMethod,
|
||||||
|
path,
|
||||||
|
func(_ http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx := meta.ToContext(r.Context())
|
||||||
|
// хак для передачи метадаты обратно в код
|
||||||
|
*r = *r.WithContext(ctx)
|
||||||
|
},
|
||||||
|
)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// nolint:mnd
|
||||||
|
func normalizeDescriptorPath(path string) string {
|
||||||
|
pathParts := strings.Split(path, " ")
|
||||||
|
// хак для endpoint'ов с GET /path
|
||||||
|
if len(pathParts) == 2 {
|
||||||
|
path = pathParts[1]
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(path, "/") {
|
||||||
|
path = "/" + path
|
||||||
|
}
|
||||||
|
return path
|
||||||
|
}
|
||||||
@@ -78,7 +78,7 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
|
|||||||
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
|
|
||||||
routes := routes.NewRoutes()
|
routes := routes.NewRoutes(logger)
|
||||||
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||||
Endpoints: []cluster.EndpointDescriptor{{
|
Endpoints: []cluster.EndpointDescriptor{{
|
||||||
Path: "endpoint",
|
Path: "endpoint",
|
||||||
@@ -128,7 +128,7 @@ func (s *HappyPathTestSuite) TestHttpProxy() {
|
|||||||
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
||||||
targetClients := map[string]*lb.RoundRobin{"target": rr}
|
targetClients := map[string]*lb.RoundRobin{"target": rr}
|
||||||
|
|
||||||
routes := routes.NewRoutes()
|
routes := routes.NewRoutes(test.Logger())
|
||||||
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||||
Endpoints: []cluster.EndpointDescriptor{{
|
Endpoints: []cluster.EndpointDescriptor{{
|
||||||
Path: "/endpoint",
|
Path: "/endpoint",
|
||||||
@@ -184,7 +184,7 @@ func (s *HappyPathTestSuite) TestWsProxy() { // nolint: funlen
|
|||||||
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
||||||
targetClients := map[string]*lb.RoundRobin{"target": rr}
|
targetClients := map[string]*lb.RoundRobin{"target": rr}
|
||||||
|
|
||||||
routes := routes.NewRoutes()
|
routes := routes.NewRoutes(test.Logger())
|
||||||
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||||
Endpoints: []cluster.EndpointDescriptor{{
|
Endpoints: []cluster.EndpointDescriptor{{
|
||||||
Path: "/service",
|
Path: "/service",
|
||||||
@@ -251,7 +251,7 @@ func (s *HappyPathTestSuite) TestAdminAuthorization() {
|
|||||||
targetClients := map[string]*client.Client{"target": targetCli}
|
targetClients := map[string]*client.Client{"target": targetCli}
|
||||||
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
routes := routes.NewRoutes()
|
routes := routes.NewRoutes(logger)
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
|
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil)
|
||||||
|
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func main() {
|
|||||||
})
|
})
|
||||||
targetClients := map[string]*client.Client{"target": targetCli}
|
targetClients := map[string]*client.Client{"target": targetCli}
|
||||||
logger, _ = log.New(log.WithLevel(log.DebugLevel))
|
logger, _ = log.New(log.WithLevel(log.DebugLevel))
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(), systemCli, adminCli, nil)
|
locator := assembly.NewLocator(logger, targetClients, nil, routes.NewRoutes(logger), systemCli, adminCli, nil)
|
||||||
locations := []conf.Location{{
|
locations := []conf.Location{{
|
||||||
SkipAuth: false,
|
SkipAuth: false,
|
||||||
PathPrefix: "/api",
|
PathPrefix: "/api",
|
||||||
|
|||||||
Reference in new issue
Block a user