Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7bd042239 | ||
|
|
202fa7035e | ||
|
|
602a2a1ac4 | ||
|
|
6a3abf67a2 | ||
|
|
2f88738f78 | ||
|
|
a637d56ea7 | ||
|
|
a841cd082b |
No files matched your search
@@ -74,3 +74,5 @@ package.json
|
|||||||
yarn.lock
|
yarn.lock
|
||||||
|
|
||||||
conf/config_dev.yml
|
conf/config_dev.yml
|
||||||
|
|
||||||
|
.DS_Store
|
||||||
@@ -1,3 +1,19 @@
|
|||||||
|
### v5.9.0
|
||||||
|
* Теперь в зависимоси от `StatusCode` выводится соотвествующий уровень логирования: 400 -> warn, 500 -> error
|
||||||
|
* Исправлен порядок мидлварей, для корректного проброса `requestId`
|
||||||
|
### v5.8.1
|
||||||
|
* Обновлены зависимости
|
||||||
|
### v5.8.0
|
||||||
|
* Изменён resolve для endpoint'ов, теперь используется `lookup` у `github.com/julienschmidt/httprouter`
|
||||||
|
* Добавлен http метод в запрос авторизации (`system/secure/authorize`)
|
||||||
|
### v5.7.0
|
||||||
|
* Добавлено лог поле `applicationName` в логи `log request` и `bypassing unauthorized request because it has admin privilege`
|
||||||
|
### v5.6.2
|
||||||
|
* Обновлено заполнение заголовка `x-application-name` для поддержки кириллических символов
|
||||||
|
### v5.6.1
|
||||||
|
* Добавлен проброс заголовка `x-application-name`
|
||||||
|
### v5.6.0
|
||||||
|
* Добавлена поддержка метрик для http запросов
|
||||||
### v5.5.1
|
### v5.5.1
|
||||||
* повышен приоритет `x-application-token` над basic-auth, при поиске в запросе токена приложения
|
* повышен приоритет `x-application-token` над basic-auth, при поиске в запросе токена приложения
|
||||||
### v5.5.0
|
### v5.5.0
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
+19
-5
@@ -4,6 +4,9 @@ import (
|
|||||||
"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"
|
||||||
@@ -94,6 +97,8 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
forwardReqIdByAppId[setting.ApplicationId] = setting.ForwardRequestId
|
forwardReqIdByAppId[setting.ApplicationId] = setting.ForwardRequestId
|
||||||
}
|
}
|
||||||
|
|
||||||
|
metricsStorage := http_metrics.NewServerStorage(metrics.DefaultRegistry)
|
||||||
|
|
||||||
handler := middleware.Chain(
|
handler := middleware.Chain(
|
||||||
proxyFunc,
|
proxyFunc,
|
||||||
middleware.Logger(
|
middleware.Logger(
|
||||||
@@ -102,16 +107,21 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
||||||
config.Logging.EnableForceUnescapingUnicode,
|
config.Logging.EnableForceUnescapingUnicode,
|
||||||
),
|
),
|
||||||
|
middleware.RequestId(),
|
||||||
middleware.ErrorHandler(l.logger),
|
middleware.ErrorHandler(l.logger),
|
||||||
middleware.Authenticate(authentication),
|
middleware.Authenticate(authentication),
|
||||||
middleware.AdminAuthenticate(adminService),
|
middleware.AdminAuthenticate(adminService),
|
||||||
|
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||||
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.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,
|
||||||
@@ -119,16 +129,20 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
config.Logging.SkipBodyLoggingEndpointPrefixes,
|
||||||
config.Logging.EnableForceUnescapingUnicode,
|
config.Logging.EnableForceUnescapingUnicode,
|
||||||
),
|
),
|
||||||
|
middleware.RequestId(),
|
||||||
middleware.ErrorHandler(l.logger),
|
middleware.ErrorHandler(l.logger),
|
||||||
middleware.RequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||||
|
middleware.Metrics(metricsStorage),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
entrypoint := middleware.Entrypoint(
|
entrypoint := middleware.Entrypoint(
|
||||||
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
|
||||||
|
}
|
||||||
@@ -12,6 +12,7 @@ type AuthenticateResponse struct {
|
|||||||
|
|
||||||
type AuthorizeRequest struct {
|
type AuthorizeRequest struct {
|
||||||
ApplicationId int
|
ApplicationId int
|
||||||
|
HttpMethod string
|
||||||
Endpoint string
|
Endpoint string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ 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.63.3
|
github.com/txix-open/isp-kit v1.64.10
|
||||||
github.com/txix-open/jsonschema v1.3.0
|
github.com/txix-open/jsonschema v1.3.0
|
||||||
golang.org/x/net v0.44.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
|
||||||
google.golang.org/grpc v1.75.1
|
google.golang.org/grpc v1.75.1
|
||||||
)
|
)
|
||||||
@@ -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
|
||||||
@@ -69,9 +69,9 @@ require (
|
|||||||
go.opentelemetry.io/proto/otlp v1.8.0 // indirect
|
go.opentelemetry.io/proto/otlp v1.8.0 // indirect
|
||||||
go.uber.org/multierr v1.11.0 // indirect
|
go.uber.org/multierr v1.11.0 // indirect
|
||||||
go.uber.org/zap v1.27.0 // indirect
|
go.uber.org/zap v1.27.0 // indirect
|
||||||
golang.org/x/crypto v0.42.0 // indirect
|
golang.org/x/crypto v0.45.0 // indirect
|
||||||
golang.org/x/sys v0.36.0 // indirect
|
golang.org/x/sys v0.38.0 // indirect
|
||||||
golang.org/x/text v0.29.0 // indirect
|
golang.org/x/text v0.31.0 // indirect
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 // indirect
|
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 // indirect
|
||||||
google.golang.org/protobuf v1.36.9 // indirect
|
google.golang.org/protobuf v1.36.9 // indirect
|
||||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||||
|
|||||||
@@ -63,8 +63,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
|||||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
|
||||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0=
|
||||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
@@ -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.63.3 h1:UJLgR4z8sYXUX6r1sl6Ww1aijPx6b7ieMeB+elZoViM=
|
github.com/txix-open/isp-kit v1.64.10 h1:lAowLtShBbICZbOWQJ4ptr9LaKKRZ7CE5DBK+7LcLqM=
|
||||||
github.com/txix-open/isp-kit v1.63.3/go.mod h1:rwqKqB3PyZxaoep6iH1PKL89LS9nzRklA6+S4II72M4=
|
github.com/txix-open/isp-kit v1.64.10/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=
|
||||||
@@ -170,16 +170,16 @@ go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
|||||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||||
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
|
||||||
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=
|
||||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||||
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
||||||
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
||||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||||
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 h1:d8Nakh1G+ur7+P3GcMjpRDEkoLUcLW2iU92XVqR+XMQ=
|
google.golang.org/genproto/googleapis/api v0.0.0-20250908214217-97024824d090 h1:d8Nakh1G+ur7+P3GcMjpRDEkoLUcLW2iU92XVqR+XMQ=
|
||||||
|
|||||||
@@ -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(),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
+12
-3
@@ -11,7 +11,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Authorizer interface {
|
type Authorizer interface {
|
||||||
Authorize(ctx context.Context, applicationId int, 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,7 +22,13 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
|||||||
return errors.WithMessage(err, "authorize: get auth data")
|
return errors.WithMessage(err, "authorize: get auth data")
|
||||||
}
|
}
|
||||||
|
|
||||||
ok, err := authorizer.Authorize(ctx.Context(), authData.ApplicationId, ctx.Endpoint())
|
endpointMeta := ctx.EndpointMeta()
|
||||||
|
ok, err := authorizer.Authorize(
|
||||||
|
ctx.Context(),
|
||||||
|
authData.ApplicationId,
|
||||||
|
ctx.Request().Method,
|
||||||
|
endpointMeta.PathSchema,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "authorize: authorize")
|
return errors.WithMessage(err, "authorize: authorize")
|
||||||
}
|
}
|
||||||
@@ -31,6 +37,7 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
|||||||
ctx.Context(),
|
ctx.Context(),
|
||||||
"bypassing unauthorized request because it has admin privilege",
|
"bypassing unauthorized request because it has admin privilege",
|
||||||
log.Int("applicationId", authData.ApplicationId),
|
log.Int("applicationId", authData.ApplicationId),
|
||||||
|
log.String("applicationName", authData.AppName),
|
||||||
log.Int("adminId", ctx.AdminId()),
|
log.Int("adminId", ctx.AdminId()),
|
||||||
)
|
)
|
||||||
return next.Handle(ctx)
|
return next.Handle(ctx)
|
||||||
@@ -39,7 +46,9 @@ func Authorize(authorizer Authorizer, logger log.Logger) Middleware {
|
|||||||
return httperrors.New(
|
return httperrors.New(
|
||||||
http.StatusForbidden,
|
http.StatusForbidden,
|
||||||
"endpoint is not allowed",
|
"endpoint is not allowed",
|
||||||
errors.Errorf("authorize: endpoint '%s' is not allowed for application '%d'", ctx.Endpoint(), authData.ApplicationId),
|
errors.Errorf("authorize: endpoint '%s' with http method '%s' is not allowed for application '%d'",
|
||||||
|
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"))
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-4
@@ -50,7 +50,7 @@ func (w *writerWrapper) WriteHeader(statusCode int) {
|
|||||||
w.ResponseWriter.WriteHeader(statusCode)
|
w.ResponseWriter.WriteHeader(statusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Logger( // nolint:gocognit
|
func Logger( // nolint:gocognit,funlen
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
enableRequestLogging bool,
|
enableRequestLogging bool,
|
||||||
enableBodyLogging bool,
|
enableBodyLogging bool,
|
||||||
@@ -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,8 +110,9 @@ 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.Int("adminId", ctx.AdminId()),
|
log.Int("adminId", ctx.AdminId()),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +125,15 @@ func Logger( // nolint:gocognit
|
|||||||
|
|
||||||
fields = append(fields, log.ByteString("response", buf.ResponseBody()))
|
fields = append(fields, log.ByteString("response", buf.ResponseBody()))
|
||||||
}
|
}
|
||||||
logger.Debug(ctx.Context(), "log request", fields...)
|
|
||||||
|
switch {
|
||||||
|
case scSrc.StatusCode() >= http.StatusInternalServerError:
|
||||||
|
logger.Error(ctx.Context(), "log request", fields...)
|
||||||
|
case scSrc.StatusCode() >= http.StatusBadRequest:
|
||||||
|
logger.Warn(ctx.Context(), "log request", fields...)
|
||||||
|
default:
|
||||||
|
logger.Debug(ctx.Context(), "log request", fields...)
|
||||||
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"isp-gate-service/request"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Metrics(storage *http_metrics.ServerStorage) Middleware {
|
||||||
|
return func(next Handler) Handler {
|
||||||
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
pathSchema := ctx.EndpointMeta().PathSchema
|
||||||
|
if pathSchema == "" {
|
||||||
|
return next.Handle(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
r := ctx.Request()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
err := next.Handle(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
storage.ObserveDuration(r.Method, pathSchema, time.Since(start))
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,10 +13,28 @@ const (
|
|||||||
requestIdHeader = "x-request-id"
|
requestIdHeader = "x-request-id"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RequestId(forwardClientRequestId bool, forwardReqIdByApp map[int]bool) Middleware {
|
func RequestId() 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 {
|
||||||
requestId := requestid.Next()
|
requestId := requestid.Next()
|
||||||
|
|
||||||
|
context := requestid.ToContext(ctx.Context(), requestId)
|
||||||
|
context = log.ToContext(context, log.String("requestId", requestId))
|
||||||
|
|
||||||
|
ctx.SetContext(context)
|
||||||
|
return next.Handle(ctx)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ClientRequestId(forwardClientRequestId bool, forwardReqIdByApp map[int]bool) Middleware {
|
||||||
|
return func(next Handler) Handler {
|
||||||
|
return HandlerFunc(func(ctx *request.Context) error {
|
||||||
|
requestId := requestid.FromContext(ctx.Context())
|
||||||
|
if requestId == "" {
|
||||||
|
requestId = requestid.Next()
|
||||||
|
}
|
||||||
|
|
||||||
clientRequestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader))
|
clientRequestId := strings.TrimSpace(ctx.Request().Header.Get(requestIdHeader))
|
||||||
|
|
||||||
logFields := make([]log.Field, 0)
|
logFields := make([]log.Field, 0)
|
||||||
|
|||||||
+5
-2
@@ -3,6 +3,7 @@ package proxy
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -70,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},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,6 +84,8 @@ func (p Grpc) Handle(ctx *request.Context) error {
|
|||||||
md[grpc.DomainIdHeader] = []string{strconv.Itoa(authData.DomainId)}
|
md[grpc.DomainIdHeader] = []string{strconv.Itoa(authData.DomainId)}
|
||||||
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)}
|
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(authData.ServiceId)}
|
||||||
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)}
|
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(authData.ApplicationId)}
|
||||||
|
encodedAppName := base64.StdEncoding.EncodeToString([]byte(authData.AppName))
|
||||||
|
md[grpc.ApplicationNameHeader] = []string{encodedAppName}
|
||||||
if ctx.IsAdminAuthenticated() {
|
if ctx.IsAdminAuthenticated() {
|
||||||
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
|
md[xAdminIdHeader] = []string{strconv.Itoa(ctx.AdminId())}
|
||||||
}
|
}
|
||||||
@@ -95,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())
|
||||||
|
|||||||
+4
-1
@@ -1,6 +1,7 @@
|
|||||||
package proxy
|
package proxy
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -65,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
|
||||||
@@ -100,6 +101,8 @@ func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) err
|
|||||||
header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId))
|
header.Set(grpc.DomainIdHeader, strconv.Itoa(authData.DomainId))
|
||||||
header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
|
header.Set(grpc.ServiceIdHeader, strconv.Itoa(authData.ServiceId))
|
||||||
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
|
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(authData.ApplicationId))
|
||||||
|
encodedAppName := base64.StdEncoding.EncodeToString([]byte(authData.AppName))
|
||||||
|
header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
|
||||||
if ctx.IsAdminAuthenticated() {
|
if ctx.IsAdminAuthenticated() {
|
||||||
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) //nolint:canonicalheader
|
header.Set(xAdminIdHeader, strconv.Itoa(ctx.AdminId())) //nolint:canonicalheader
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+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)
|
||||||
|
|||||||
@@ -4,9 +4,10 @@ package repository
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
|
"isp-gate-service/domain"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"github.com/txix-open/isp-kit/grpc/client"
|
"github.com/txix-open/isp-kit/grpc/client"
|
||||||
"isp-gate-service/domain"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -36,10 +37,10 @@ func (r System) Authenticate(ctx context.Context, token string) (*domain.Authent
|
|||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r System) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) {
|
func (r System) Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error) {
|
||||||
resp := domain.AuthorizeResponse{}
|
resp := domain.AuthorizeResponse{}
|
||||||
err := r.cli.Invoke(authorize).
|
err := r.cli.Invoke(authorize).
|
||||||
JsonRequestBody(domain.AuthorizeRequest{ApplicationId: applicationId, Endpoint: endpoint}).
|
JsonRequestBody(req).
|
||||||
JsonResponseBody(&resp).
|
JsonResponseBody(&resp).
|
||||||
Do(ctx)
|
Do(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+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) {
|
||||||
|
|||||||
+77
-49
@@ -2,85 +2,113 @@ 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
|
|
||||||
|
handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||||
|
ctx := meta.ToContext(r.Context())
|
||||||
|
// хак для передачи метадаты обратно в код
|
||||||
|
*r = *r.WithContext(ctx)
|
||||||
|
}
|
||||||
|
router.Handle(httpMethod, path, handler)
|
||||||
}
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -2,6 +2,8 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"isp-gate-service/domain"
|
||||||
|
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
@@ -12,7 +14,7 @@ type AuthorizationCache interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type AuthorizationRepo interface {
|
type AuthorizationRepo interface {
|
||||||
Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error)
|
Authorize(ctx context.Context, req domain.AuthorizeRequest) (bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Authorization struct {
|
type Authorization struct {
|
||||||
@@ -27,21 +29,26 @@ func NewAuthorization(cache AuthorizationCache, repo AuthorizationRepo) Authoriz
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Authorization) Authorize(ctx context.Context, applicationId int, endpoint string) (bool, error) {
|
func (s Authorization) Authorize(ctx context.Context, applicationId int, httpMethod string, endpoint string) (bool, error) {
|
||||||
ok, err := s.cache.Get(ctx, applicationId, endpoint)
|
cacheKey := fmt.Sprintf("%s %s", httpMethod, endpoint)
|
||||||
|
ok, err := s.cache.Get(ctx, applicationId, cacheKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, errors.WithMessage(err, "authz cache get")
|
return false, errors.WithMessage(err, "authz cache get")
|
||||||
}
|
}
|
||||||
if ok {
|
if ok {
|
||||||
return ok, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
ok, err = s.repo.Authorize(ctx, applicationId, endpoint)
|
ok, err = s.repo.Authorize(ctx, domain.AuthorizeRequest{
|
||||||
|
ApplicationId: applicationId,
|
||||||
|
HttpMethod: httpMethod,
|
||||||
|
Endpoint: endpoint,
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, errors.WithMessagef(err, "authz repo authorize")
|
return false, errors.WithMessagef(err, "authz repo authorize")
|
||||||
}
|
}
|
||||||
if ok {
|
if ok {
|
||||||
err = s.cache.SetAuthorized(ctx, applicationId, endpoint)
|
err = s.cache.SetAuthorized(ctx, applicationId, cacheKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, errors.WithMessagef(err, "authz cache set")
|
return false, errors.WithMessagef(err, "authz cache set")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package tests
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
"net/url"
|
||||||
@@ -77,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",
|
||||||
@@ -127,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",
|
||||||
@@ -183,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",
|
||||||
@@ -250,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{{
|
||||||
@@ -324,6 +325,7 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
|
|||||||
DomainId: 2,
|
DomainId: 2,
|
||||||
ServiceId: 3,
|
ServiceId: 3,
|
||||||
ApplicationId: 4,
|
ApplicationId: 4,
|
||||||
|
AppName: "test",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
|
}).Mock("system/secure/authorize", func() domain.AuthorizeResponse {
|
||||||
@@ -366,6 +368,8 @@ func assertHeaders(require *require.Assertions, requestId string, ctx context.Co
|
|||||||
require.EqualValues(2, domainId)
|
require.EqualValues(2, domainId)
|
||||||
require.EqualValues(3, serviceId)
|
require.EqualValues(3, serviceId)
|
||||||
require.EqualValues(4, applicationId)
|
require.EqualValues(4, applicationId)
|
||||||
|
expectedAppName := base64.StdEncoding.EncodeToString([]byte("test"))
|
||||||
|
require.EqualValues(expectedAppName, headers.Get("x-application-name"))
|
||||||
|
|
||||||
adminId, err := strconv.Atoi(headers.Get("x-admin-id"))
|
adminId, err := strconv.Atoi(headers.Get("x-admin-id"))
|
||||||
require.NoError(err)
|
require.NoError(err)
|
||||||
|
|||||||
@@ -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