Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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,6 +1,3 @@
|
|||||||
### v5.12.0
|
|
||||||
* добавлена проверка пользовательских прав на эндпоинте: гейт вызывает `authorizeEndpoint` модуля из `userAuthSettings` и возвращает 403, если пользователь не имеет права, объявленного в дескрипторе эндпоинта; положительные результаты кэшируются на `caching.authorizationDataInSec`
|
|
||||||
* добавлена очистка хедеров, совпадающих с хедерами пришедшими в `UserAuthData.ExtraHeaders`, перед добавлением
|
|
||||||
### v5.11.4
|
### v5.11.4
|
||||||
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
|
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
|
||||||
### v5.11.3
|
### v5.11.3
|
||||||
|
|||||||
@@ -67,12 +67,10 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
authentication := service.NewAuthentication(authenticationCache, systemRepo)
|
authentication := service.NewAuthentication(authenticationCache, systemRepo)
|
||||||
|
|
||||||
userAuthenticationCache := repository.NewUserAuthenticationCache(l.usersAuthCache)
|
userAuthenticationCache := repository.NewUserAuthenticationCache(l.usersAuthCache)
|
||||||
userAuthorizationCache := repository.NewUserAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec) * time.Second)
|
|
||||||
userAuthRepo := repository.NewUserAuth(l.routerLb)
|
userAuthRepo := repository.NewUserAuth(l.routerLb)
|
||||||
userAuthentication, err := service.NewUserAuthentication(
|
userAuthentication, err := service.NewUserAuthentication(
|
||||||
config.CustomAuth,
|
config.CustomAuth,
|
||||||
userAuthenticationCache,
|
userAuthenticationCache,
|
||||||
userAuthorizationCache,
|
|
||||||
userAuthRepo,
|
userAuthRepo,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -144,7 +142,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
|||||||
middleware.RequestId(),
|
middleware.RequestId(),
|
||||||
middleware.ErrorHandler(l.logger),
|
middleware.ErrorHandler(l.logger),
|
||||||
middleware.UserAuthenticate(userAuthentication, l.logger),
|
middleware.UserAuthenticate(userAuthentication, l.logger),
|
||||||
middleware.UserAuthorize(userAuthentication),
|
|
||||||
middleware.Authenticate(authentication),
|
middleware.Authenticate(authentication),
|
||||||
middleware.AdminAuthenticate(adminService),
|
middleware.AdminAuthenticate(adminService),
|
||||||
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||||
|
|||||||
@@ -96,7 +96,6 @@ type UserAuthSetting struct {
|
|||||||
ModuleNameList []string `schema:"Название модулей,для которых настраивается аутентификация/авторизация,название модулей должно быть уникальным" validate:"required"`
|
ModuleNameList []string `schema:"Название модулей,для которых настраивается аутентификация/авторизация,название модулей должно быть уникальным" validate:"required"`
|
||||||
TokenProviders []string `schema:"Список названий методов получения токена из запроса,используется первый провайдер, вернувший токен"`
|
TokenProviders []string `schema:"Список названий методов получения токена из запроса,используется первый провайдер, вернувший токен"`
|
||||||
AuthenticateEndpoint string `schema:"Endpoint для аутентификации пользователя,вызывается через isp-router-service" validate:"required"`
|
AuthenticateEndpoint string `schema:"Endpoint для аутентификации пользователя,вызывается через isp-router-service" validate:"required"`
|
||||||
AuthorizeEndpoint string `schema:"Endpoint для проверки прав пользователя,вызывается через isp-router-service" validate:"required"`
|
|
||||||
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
|
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
|
||||||
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
|
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ type EndpointMeta struct {
|
|||||||
|
|
||||||
ModuleName string
|
ModuleName string
|
||||||
RequiredAdminPermission string
|
RequiredAdminPermission string
|
||||||
RequiredUserPermission string
|
|
||||||
// Объявляемый сервисом метод
|
// Объявляемый сервисом метод
|
||||||
PathSchema string
|
PathSchema string
|
||||||
// Вызываемый метод
|
// Вызываемый метод
|
||||||
|
|||||||
@@ -15,12 +15,3 @@ type UserAuthData struct {
|
|||||||
IdentityHeader string
|
IdentityHeader string
|
||||||
ExtraHeaders map[string][]string
|
ExtraHeaders map[string][]string
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserAuthorizeRequest struct {
|
|
||||||
Identity string
|
|
||||||
Permission string
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserAuthorizeResponse struct {
|
|
||||||
Authorized bool
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"isp-gate-service/httperrors"
|
|
||||||
"isp-gate-service/request"
|
|
||||||
|
|
||||||
"github.com/txix-open/isp-kit/errors"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UserAuthorizer interface {
|
|
||||||
UserAuthorize(ctx *request.Context) (bool, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
func UserAuthorize(authorizer UserAuthorizer) Middleware {
|
|
||||||
return func(next Handler) Handler {
|
|
||||||
return HandlerFunc(func(ctx *request.Context) error {
|
|
||||||
endpointMeta := ctx.EndpointMeta()
|
|
||||||
requiredPerm := endpointMeta.RequiredUserPermission
|
|
||||||
if requiredPerm == "" {
|
|
||||||
return next.Handle(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
userAuthData, err := ctx.GetUserAuthData()
|
|
||||||
if err != nil {
|
|
||||||
return httperrors.New(
|
|
||||||
http.StatusUnauthorized,
|
|
||||||
"user authentication required",
|
|
||||||
errors.Errorf("user authorization: user authentication required for '%s'",
|
|
||||||
endpointMeta.Endpoint,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
ok, err := authorizer.UserAuthorize(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return errors.WithMessage(err, "user authorization: authorize")
|
|
||||||
}
|
|
||||||
if !ok {
|
|
||||||
return httperrors.New(
|
|
||||||
http.StatusForbidden,
|
|
||||||
"endpoint is not allowed",
|
|
||||||
errors.Errorf(
|
|
||||||
"user authorization: endpoint '%s' requires '%s' permission, but user '%s' doesn't have it",
|
|
||||||
endpointMeta.Endpoint, requiredPerm, userAuthData.Identity,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
return next.Handle(ctx)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -101,7 +101,6 @@ func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
|
|||||||
userAuthData, err := ctx.GetUserAuthData()
|
userAuthData, err := ctx.GetUserAuthData()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for key, values := range userAuthData.ExtraHeaders {
|
for key, values := range userAuthData.ExtraHeaders {
|
||||||
header.Del(key)
|
|
||||||
for _, value := range values {
|
for _, value := range values {
|
||||||
header.Add(key, value)
|
header.Add(key, value)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,31 +49,3 @@ func (r UserAuth) Authenticate(
|
|||||||
}
|
}
|
||||||
return &resp, nil
|
return &resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r UserAuth) Authorize(
|
|
||||||
ctx context.Context,
|
|
||||||
method string,
|
|
||||||
identity string,
|
|
||||||
permission string,
|
|
||||||
) (bool, error) {
|
|
||||||
ctx = http_metrics.ClientEndpointToContext(ctx, method)
|
|
||||||
|
|
||||||
host, err := r.lb.Next()
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessage(err, "lb next")
|
|
||||||
}
|
|
||||||
|
|
||||||
endpoint := fmt.Sprintf("http://%s/%s", host, method)
|
|
||||||
resp := entity.UserAuthorizeResponse{}
|
|
||||||
err = r.cli.Post(endpoint).
|
|
||||||
JsonRequestBody(entity.UserAuthorizeRequest{
|
|
||||||
Identity: identity,
|
|
||||||
Permission: permission,
|
|
||||||
}).JsonResponseBody(&resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessagef(err, "http client invoke: %s", endpoint)
|
|
||||||
}
|
|
||||||
return resp.Authorized, nil
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"isp-gate-service/cache"
|
|
||||||
)
|
|
||||||
|
|
||||||
type UserAuthorizationCache struct {
|
|
||||||
duration time.Duration
|
|
||||||
cache *cache.Cache
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewUserAuthorizationCache(duration time.Duration) *UserAuthorizationCache {
|
|
||||||
return &UserAuthorizationCache{
|
|
||||||
duration: duration,
|
|
||||||
cache: cache.New(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r UserAuthorizationCache) Get(ctx context.Context, authorizeEndpoint string, identity string, permission string) (bool, error) {
|
|
||||||
key := r.key(authorizeEndpoint, identity, permission)
|
|
||||||
_, ok := r.cache.Get(key)
|
|
||||||
return ok, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r UserAuthorizationCache) SetAuthorized(ctx context.Context, authorizeEndpoint string, identity string, permission string) error {
|
|
||||||
key := r.key(authorizeEndpoint, identity, permission)
|
|
||||||
r.cache.Set(key, nil, r.duration)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r UserAuthorizationCache) key(authorizeEndpoint string, identity string, permission string) string {
|
|
||||||
return fmt.Sprintf("%s:%s:%s", authorizeEndpoint, identity, permission)
|
|
||||||
}
|
|
||||||
@@ -106,13 +106,11 @@ func (s *Routes) registerEndpoint(
|
|||||||
}()
|
}()
|
||||||
|
|
||||||
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
||||||
requiredUserPerm, _ := cluster.GetRequiredUserPermission(descriptor)
|
|
||||||
meta := domain.EndpointMeta{
|
meta := domain.EndpointMeta{
|
||||||
Inner: descriptor.Inner,
|
Inner: descriptor.Inner,
|
||||||
UserAuthRequired: descriptor.UserAuthRequired,
|
UserAuthRequired: descriptor.UserAuthRequired,
|
||||||
ModuleName: moduleName,
|
ModuleName: moduleName,
|
||||||
RequiredAdminPermission: requiredAdminPerm,
|
RequiredAdminPermission: requiredAdminPerm,
|
||||||
RequiredUserPermission: requiredUserPerm,
|
|
||||||
PathSchema: descriptor.Path,
|
PathSchema: descriptor.Path,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,14 +19,8 @@ type UserAuthenticationCache interface {
|
|||||||
Set(ctx context.Context, authEndpoint string, token string, data entity.UserAuthData, duration time.Duration) error
|
Set(ctx context.Context, authEndpoint string, token string, data entity.UserAuthData, duration time.Duration) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserAuthorizationCache interface {
|
|
||||||
Get(ctx context.Context, authorizeEndpoint string, identity string, permission string) (bool, error)
|
|
||||||
SetAuthorized(ctx context.Context, authorizeEndpoint string, identity string, permission string) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserAuthenticationRepo interface {
|
type UserAuthenticationRepo interface {
|
||||||
Authenticate(ctx context.Context, authEndpoint string, token string) (*entity.UserAuthenticateResponse, error)
|
Authenticate(ctx context.Context, authEndpoint string, token string) (*entity.UserAuthenticateResponse, error)
|
||||||
Authorize(ctx context.Context, authorizeEndpoint string, identity string, permission string) (bool, error)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TokenProvider interface {
|
type TokenProvider interface {
|
||||||
@@ -37,14 +31,12 @@ type TokenProvider interface {
|
|||||||
type userAuthSetting struct {
|
type userAuthSetting struct {
|
||||||
tokenProviders []TokenProvider
|
tokenProviders []TokenProvider
|
||||||
authEndpoint string
|
authEndpoint string
|
||||||
authorizeEndpoint string
|
|
||||||
authCacheDuration time.Duration
|
authCacheDuration time.Duration
|
||||||
skipAppAuth bool
|
skipAppAuth bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserAuthentication struct {
|
type UserAuthentication struct {
|
||||||
cache UserAuthenticationCache
|
cache UserAuthenticationCache
|
||||||
authzCache UserAuthorizationCache
|
|
||||||
repo UserAuthenticationRepo
|
repo UserAuthenticationRepo
|
||||||
settingsByModuleName map[string]userAuthSetting
|
settingsByModuleName map[string]userAuthSetting
|
||||||
}
|
}
|
||||||
@@ -52,7 +44,6 @@ type UserAuthentication struct {
|
|||||||
func NewUserAuthentication(
|
func NewUserAuthentication(
|
||||||
cfg conf.CustomAuth,
|
cfg conf.CustomAuth,
|
||||||
cache UserAuthenticationCache,
|
cache UserAuthenticationCache,
|
||||||
authzCache UserAuthorizationCache,
|
|
||||||
repo UserAuthenticationRepo,
|
repo UserAuthenticationRepo,
|
||||||
) (UserAuthentication, error) {
|
) (UserAuthentication, error) {
|
||||||
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
|
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
|
||||||
@@ -96,7 +87,6 @@ func NewUserAuthentication(
|
|||||||
settingsByModuleName[moduleName] = userAuthSetting{
|
settingsByModuleName[moduleName] = userAuthSetting{
|
||||||
tokenProviders: settingTokenProviders,
|
tokenProviders: settingTokenProviders,
|
||||||
authEndpoint: setting.AuthenticateEndpoint,
|
authEndpoint: setting.AuthenticateEndpoint,
|
||||||
authorizeEndpoint: setting.AuthorizeEndpoint,
|
|
||||||
authCacheDuration: cacheDuration,
|
authCacheDuration: cacheDuration,
|
||||||
skipAppAuth: setting.SkipAppAuth,
|
skipAppAuth: setting.SkipAppAuth,
|
||||||
}
|
}
|
||||||
@@ -105,7 +95,6 @@ func NewUserAuthentication(
|
|||||||
|
|
||||||
return UserAuthentication{
|
return UserAuthentication{
|
||||||
cache: cache,
|
cache: cache,
|
||||||
authzCache: authzCache,
|
|
||||||
repo: repo,
|
repo: repo,
|
||||||
settingsByModuleName: settingsByModuleName,
|
settingsByModuleName: settingsByModuleName,
|
||||||
}, nil
|
}, nil
|
||||||
@@ -143,58 +132,6 @@ func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.Authenti
|
|||||||
return resp, nil
|
return resp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s UserAuthentication) UserAuthorize(ctx *request.Context) (bool, error) {
|
|
||||||
meta := ctx.EndpointMeta()
|
|
||||||
|
|
||||||
setting, ok := s.settingsByModuleName[meta.ModuleName]
|
|
||||||
if !ok {
|
|
||||||
return false, errors.WithMessagef(domain.ErrUserAuthSettingNotFound,
|
|
||||||
"setting for module '%s' and endpoint '%s' not found",
|
|
||||||
meta.ModuleName, meta.Endpoint,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
userAuthData, err := ctx.GetUserAuthData()
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessage(err, "get user auth data")
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.authorize(
|
|
||||||
ctx.Context(),
|
|
||||||
setting,
|
|
||||||
userAuthData.Identity,
|
|
||||||
meta.RequiredUserPermission,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s UserAuthentication) authorize(
|
|
||||||
ctx context.Context,
|
|
||||||
setting userAuthSetting,
|
|
||||||
identity string,
|
|
||||||
permission string,
|
|
||||||
) (bool, error) {
|
|
||||||
ok, err := s.authzCache.Get(ctx, setting.authorizeEndpoint, identity, permission)
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessage(err, "user authz cache get")
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
ok, err = s.repo.Authorize(ctx, setting.authorizeEndpoint, identity, permission)
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessagef(err, "user authz repo authorize")
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
err = s.authzCache.SetAuthorized(ctx, setting.authorizeEndpoint, identity, permission)
|
|
||||||
if err != nil {
|
|
||||||
return false, errors.WithMessagef(err, "user authz cache set")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ok, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s UserAuthentication) extractToken(ctx *request.Context, providers []TokenProvider) (string, error) {
|
func (s UserAuthentication) extractToken(ctx *request.Context, providers []TokenProvider) (string, error) {
|
||||||
for _, provider := range providers {
|
for _, provider := range providers {
|
||||||
token, err := provider.ExtractToken(ctx)
|
token, err := provider.ExtractToken(ctx)
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ import (
|
|||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"net/url"
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync/atomic"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -383,13 +382,11 @@ func (s *HappyPathTestSuite) TestUserAuthorization() { // nolint:funlen
|
|||||||
ModuleNameList: []string{"target"},
|
ModuleNameList: []string{"target"},
|
||||||
TokenProviders: []string{"test_provider"},
|
TokenProviders: []string{"test_provider"},
|
||||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ModuleNameList: []string{"target2"},
|
ModuleNameList: []string{"target2"},
|
||||||
TokenProviders: []string{"test_provider"},
|
TokenProviders: []string{"test_provider"},
|
||||||
AuthenticateEndpoint: "failed-user-auth/authenticate",
|
AuthenticateEndpoint: "failed-user-auth/authenticate",
|
||||||
AuthorizeEndpoint: "failed-user-auth/authorize",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -524,14 +521,12 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
|
|||||||
ModuleNameList: []string{"target"},
|
ModuleNameList: []string{"target"},
|
||||||
TokenProviders: []string{"test_provider"},
|
TokenProviders: []string{"test_provider"},
|
||||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
|
||||||
SkipAppAuth: true,
|
SkipAppAuth: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
ModuleNameList: []string{"target2"},
|
ModuleNameList: []string{"target2"},
|
||||||
TokenProviders: []string{"test_provider"},
|
TokenProviders: []string{"test_provider"},
|
||||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -584,163 +579,6 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
|
|||||||
require.EqualValues(http.StatusUnauthorized, errResp.StatusCode)
|
require.EqualValues(http.StatusUnauthorized, errResp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *HappyPathTestSuite) TestUserAuthorization_PermissionCheck() { // nolint:funlen
|
|
||||||
test, require := test.New(s.T())
|
|
||||||
config, systemCli, adminCli := s.commonDependencies(test)
|
|
||||||
|
|
||||||
userAuthData := entity.UserAuthData{
|
|
||||||
Identity: "42",
|
|
||||||
IdentityHeader: "x-user-identity",
|
|
||||||
ExtraHeaders: map[string][]string{"x-user-session-token": {"test-session-token"}},
|
|
||||||
}
|
|
||||||
|
|
||||||
targetService, targetCli := grpct.NewMock(test)
|
|
||||||
for _, endpointName := range []string{"perm_ok_endpoint", "no_perm_endpoint"} {
|
|
||||||
targetService.Mock(endpointName, func(ctx context.Context, authData grpc.AuthData, req request) response {
|
|
||||||
md, ok := metadata.FromIncomingContext(ctx)
|
|
||||||
require.True(ok)
|
|
||||||
require.ElementsMatch([]string{userAuthData.Identity}, md.Get(userAuthData.IdentityHeader))
|
|
||||||
|
|
||||||
return response{Id: req.Id}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
var authorizeCalls atomic.Int64
|
|
||||||
routerMux := router.New()
|
|
||||||
defaultWrapper := endpoint.DefaultWrapper(
|
|
||||||
test.Logger(),
|
|
||||||
httplog.Noop(),
|
|
||||||
)
|
|
||||||
|
|
||||||
userAuthToken := fake.It[string]()
|
|
||||||
|
|
||||||
routerMux.POST("/test-user-auth/authenticate",
|
|
||||||
defaultWrapper.Endpoint(func(req entity.UserAuthenticateRequest) entity.UserAuthenticateResponse {
|
|
||||||
require.Equal(userAuthToken, req.Token)
|
|
||||||
return entity.UserAuthenticateResponse{
|
|
||||||
Authenticated: true,
|
|
||||||
AuthData: &userAuthData,
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
routerMux.POST("/test-user-auth/authorize",
|
|
||||||
defaultWrapper.Endpoint(func(req entity.UserAuthorizeRequest) entity.UserAuthorizeResponse {
|
|
||||||
authorizeCalls.Add(1)
|
|
||||||
require.Equal(userAuthData.Identity, req.Identity)
|
|
||||||
if req.Permission == "ok_permission" {
|
|
||||||
return entity.UserAuthorizeResponse{Authorized: true}
|
|
||||||
}
|
|
||||||
return entity.UserAuthorizeResponse{}
|
|
||||||
}))
|
|
||||||
routerMock := httptest.NewServer(routerMux)
|
|
||||||
targetUrl, err := url.Parse(routerMock.URL)
|
|
||||||
require.NoError(err)
|
|
||||||
rr := lb.NewRoundRobin([]string{targetUrl.Host})
|
|
||||||
|
|
||||||
targetClients := map[string]*client.Client{"target": targetCli}
|
|
||||||
logger, err := log.New(log.WithLevel(log.DebugLevel))
|
|
||||||
require.NoError(err)
|
|
||||||
routes := routes.NewRoutes(logger)
|
|
||||||
locator := assembly.NewLocator(logger, targetClients, nil, routes, systemCli, adminCli, nil, rr, cache.New())
|
|
||||||
|
|
||||||
locations := []conf.Location{{
|
|
||||||
SkipAuth: false,
|
|
||||||
PathPrefix: "/api",
|
|
||||||
Protocol: "grpc",
|
|
||||||
TargetModule: "target",
|
|
||||||
}}
|
|
||||||
config.CustomAuth = conf.CustomAuth{
|
|
||||||
TokenProviders: []conf.TokenProvider{
|
|
||||||
{
|
|
||||||
Name: "test_provider",
|
|
||||||
Type: conf.HeaderTokenProviderType,
|
|
||||||
HeaderProvider: &conf.HeaderTokenProvider{
|
|
||||||
HeaderName: "test-token-header",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
UserAuthSettings: []conf.UserAuthSetting{
|
|
||||||
{
|
|
||||||
ModuleNameList: []string{"target"},
|
|
||||||
TokenProviders: []string{"test_provider"},
|
|
||||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
|
||||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
|
||||||
SkipAppAuth: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
handler, err := locator.Handler(config, locations)
|
|
||||||
require.NoError(err)
|
|
||||||
|
|
||||||
err = routes.ReceiveRoutes(context.Background(), cluster.RoutingConfig{{
|
|
||||||
ModuleName: "target",
|
|
||||||
Endpoints: []cluster.EndpointDescriptor{
|
|
||||||
{
|
|
||||||
Path: "perm_ok_endpoint",
|
|
||||||
Inner: false,
|
|
||||||
UserAuthRequired: true,
|
|
||||||
Extra: cluster.RequireUserPermission("ok_permission"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "perm_bad_endpoint",
|
|
||||||
Inner: false,
|
|
||||||
UserAuthRequired: true,
|
|
||||||
Extra: cluster.RequireUserPermission("bad_permission"),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Path: "no_perm_endpoint",
|
|
||||||
Inner: false,
|
|
||||||
UserAuthRequired: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}})
|
|
||||||
require.NoError(err)
|
|
||||||
|
|
||||||
srv := httptest.NewServer(handler)
|
|
||||||
cli := httpcli.New()
|
|
||||||
req := request{Id: uuid.New().String()}
|
|
||||||
resp := response{}
|
|
||||||
|
|
||||||
err = cli.Post(srv.URL+"/api/perm_ok_endpoint").
|
|
||||||
Header("test-token-header", userAuthToken).
|
|
||||||
JsonRequestBody(req).
|
|
||||||
JsonResponseBody(&resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
require.NoError(err)
|
|
||||||
require.EqualValues(req.Id, resp.Id)
|
|
||||||
require.EqualValues(int64(1), authorizeCalls.Load())
|
|
||||||
|
|
||||||
err = cli.Post(srv.URL+"/api/perm_bad_endpoint").
|
|
||||||
Header("test-token-header", userAuthToken).
|
|
||||||
JsonRequestBody(req).
|
|
||||||
JsonResponseBody(&resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
errResp := httpcli.ErrorResponse{}
|
|
||||||
require.ErrorAs(err, &errResp)
|
|
||||||
require.EqualValues(http.StatusForbidden, errResp.StatusCode)
|
|
||||||
require.EqualValues(int64(2), authorizeCalls.Load())
|
|
||||||
|
|
||||||
err = cli.Post(srv.URL+"/api/no_perm_endpoint").
|
|
||||||
Header("test-token-header", userAuthToken).
|
|
||||||
JsonRequestBody(req).
|
|
||||||
JsonResponseBody(&resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
require.NoError(err)
|
|
||||||
require.EqualValues(req.Id, resp.Id)
|
|
||||||
require.EqualValues(int64(2), authorizeCalls.Load())
|
|
||||||
|
|
||||||
err = cli.Post(srv.URL + "/api/perm_ok_endpoint").
|
|
||||||
JsonRequestBody(req).
|
|
||||||
JsonResponseBody(&resp).
|
|
||||||
StatusCodeToError().
|
|
||||||
DoWithoutResponse(s.T().Context())
|
|
||||||
errResp = httpcli.ErrorResponse{}
|
|
||||||
require.ErrorAs(err, &errResp)
|
|
||||||
require.EqualValues(http.StatusUnauthorized, errResp.StatusCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
// nolint:ireturn
|
// nolint:ireturn
|
||||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
|
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
|
||||||
config := conf.Remote{
|
config := conf.Remote{
|
||||||
|
|||||||
Reference in new issue
Block a user