MSP-8999 add userAuthorization
This commit is contained in:
1 parent
4e924575ce
commit
f06db36390
10 files changed
+360
No files matched your search
@@ -67,10 +67,12 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
authentication := service.NewAuthentication(authenticationCache, systemRepo)
|
||||
|
||||
userAuthenticationCache := repository.NewUserAuthenticationCache(l.usersAuthCache)
|
||||
userAuthorizationCache := repository.NewUserAuthorizationCache(time.Duration(config.Caching.AuthorizationDataInSec) * time.Second)
|
||||
userAuthRepo := repository.NewUserAuth(l.routerLb)
|
||||
userAuthentication, err := service.NewUserAuthentication(
|
||||
config.CustomAuth,
|
||||
userAuthenticationCache,
|
||||
userAuthorizationCache,
|
||||
userAuthRepo,
|
||||
)
|
||||
if err != nil {
|
||||
@@ -142,6 +144,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
middleware.RequestId(),
|
||||
middleware.ErrorHandler(l.logger),
|
||||
middleware.UserAuthenticate(userAuthentication, l.logger),
|
||||
middleware.UserAuthorize(userAuthentication),
|
||||
middleware.Authenticate(authentication),
|
||||
middleware.AdminAuthenticate(adminService),
|
||||
middleware.ClientRequestId(config.EnableClientRequestIdForwarding, forwardReqIdByAppId),
|
||||
|
||||
@@ -96,6 +96,7 @@ type UserAuthSetting struct {
|
||||
ModuleNameList []string `schema:"Название модулей,для которых настраивается аутентификация/авторизация,название модулей должно быть уникальным" validate:"required"`
|
||||
TokenProviders []string `schema:"Список названий методов получения токена из запроса,используется первый провайдер, вернувший токен"`
|
||||
AuthenticateEndpoint string `schema:"Endpoint для аутентификации пользователя,вызывается через isp-router-service" validate:"required"`
|
||||
AuthorizeEndpoint string `schema:"Endpoint для проверки прав пользователя,вызывается через isp-router-service" validate:"required"`
|
||||
CacheDataInSec int `schema:"Время кеширования данных аутентификации/авторизации пользователя,отключен при значениях <=0,в секундах"`
|
||||
SkipAppAuth bool `schema:"Пропустить аутентификацию и авторизацию приложения"`
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ type EndpointMeta struct {
|
||||
|
||||
ModuleName string
|
||||
RequiredAdminPermission string
|
||||
RequiredUserPermission string
|
||||
// Объявляемый сервисом метод
|
||||
PathSchema string
|
||||
// Вызываемый метод
|
||||
|
||||
@@ -15,3 +15,12 @@ type UserAuthData struct {
|
||||
IdentityHeader string
|
||||
ExtraHeaders map[string][]string
|
||||
}
|
||||
|
||||
type UserAuthorizeRequest struct {
|
||||
Identity string
|
||||
Permission string
|
||||
}
|
||||
|
||||
type UserAuthorizeResponse struct {
|
||||
Authorized bool
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -49,3 +49,31 @@ func (r UserAuth) Authenticate(
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
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,11 +106,13 @@ func (s *Routes) registerEndpoint(
|
||||
}()
|
||||
|
||||
requiredAdminPerm, _ := cluster.GetRequiredAdminPermission(descriptor)
|
||||
requiredUserPerm, _ := cluster.GetRequiredUserPermission(descriptor)
|
||||
meta := domain.EndpointMeta{
|
||||
Inner: descriptor.Inner,
|
||||
UserAuthRequired: descriptor.UserAuthRequired,
|
||||
ModuleName: moduleName,
|
||||
RequiredAdminPermission: requiredAdminPerm,
|
||||
RequiredUserPermission: requiredUserPerm,
|
||||
PathSchema: descriptor.Path,
|
||||
}
|
||||
|
||||
|
||||
@@ -19,8 +19,14 @@ type UserAuthenticationCache interface {
|
||||
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 {
|
||||
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 {
|
||||
@@ -31,12 +37,14 @@ type TokenProvider interface {
|
||||
type userAuthSetting struct {
|
||||
tokenProviders []TokenProvider
|
||||
authEndpoint string
|
||||
authorizeEndpoint string
|
||||
authCacheDuration time.Duration
|
||||
skipAppAuth bool
|
||||
}
|
||||
|
||||
type UserAuthentication struct {
|
||||
cache UserAuthenticationCache
|
||||
authzCache UserAuthorizationCache
|
||||
repo UserAuthenticationRepo
|
||||
settingsByModuleName map[string]userAuthSetting
|
||||
}
|
||||
@@ -44,6 +52,7 @@ type UserAuthentication struct {
|
||||
func NewUserAuthentication(
|
||||
cfg conf.CustomAuth,
|
||||
cache UserAuthenticationCache,
|
||||
authzCache UserAuthorizationCache,
|
||||
repo UserAuthenticationRepo,
|
||||
) (UserAuthentication, error) {
|
||||
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
|
||||
@@ -87,6 +96,7 @@ func NewUserAuthentication(
|
||||
settingsByModuleName[moduleName] = userAuthSetting{
|
||||
tokenProviders: settingTokenProviders,
|
||||
authEndpoint: setting.AuthenticateEndpoint,
|
||||
authorizeEndpoint: setting.AuthorizeEndpoint,
|
||||
authCacheDuration: cacheDuration,
|
||||
skipAppAuth: setting.SkipAppAuth,
|
||||
}
|
||||
@@ -95,6 +105,7 @@ func NewUserAuthentication(
|
||||
|
||||
return UserAuthentication{
|
||||
cache: cache,
|
||||
authzCache: authzCache,
|
||||
repo: repo,
|
||||
settingsByModuleName: settingsByModuleName,
|
||||
}, nil
|
||||
@@ -132,6 +143,58 @@ func (s UserAuthentication) Authenticate(ctx *request.Context) (*domain.Authenti
|
||||
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) {
|
||||
for _, provider := range providers {
|
||||
token, err := provider.ExtractToken(ctx)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -382,11 +383,13 @@ func (s *HappyPathTestSuite) TestUserAuthorization() { // nolint:funlen
|
||||
ModuleNameList: []string{"target"},
|
||||
TokenProviders: []string{"test_provider"},
|
||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
||||
},
|
||||
{
|
||||
ModuleNameList: []string{"target2"},
|
||||
TokenProviders: []string{"test_provider"},
|
||||
AuthenticateEndpoint: "failed-user-auth/authenticate",
|
||||
AuthorizeEndpoint: "failed-user-auth/authorize",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -521,12 +524,14 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
|
||||
ModuleNameList: []string{"target"},
|
||||
TokenProviders: []string{"test_provider"},
|
||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
||||
SkipAppAuth: true,
|
||||
},
|
||||
{
|
||||
ModuleNameList: []string{"target2"},
|
||||
TokenProviders: []string{"test_provider"},
|
||||
AuthenticateEndpoint: "test-user-auth/authenticate",
|
||||
AuthorizeEndpoint: "test-user-auth/authorize",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -579,6 +584,163 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
|
||||
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
|
||||
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) {
|
||||
config := conf.Remote{
|
||||
|
||||
Reference in new issue
Block a user