Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
@@ -0,0 +1,60 @@
|
||||
name: Create and publish a Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
IMAGE_NAME: ${{ github.repository }}
|
||||
APP_NAME: ${{ github.event.repository.name }}
|
||||
|
||||
jobs:
|
||||
build-and-push-image:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
attestations: write
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get version from tag
|
||||
id: version_reader
|
||||
run: |
|
||||
VERSION=${GITHUB_REF_NAME#v}
|
||||
echo "version=$VERSION" >> $GITHUB_OUTPUT
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
with:
|
||||
driver: docker-container
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.version_reader.outputs.version }}
|
||||
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
|
||||
labels: |
|
||||
org.opencontainers.image.title=${{ env.IMAGE_NAME }}
|
||||
org.opencontainers.image.version=${{ steps.version_reader.outputs.version }}
|
||||
build-args: |
|
||||
app_name=${{ env.APP_NAME }}
|
||||
version=${{ steps.version_reader.outputs.version }}
|
||||
- name: Generate artifact attestation
|
||||
uses: actions/attest-build-provenance@v2
|
||||
with:
|
||||
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
|
||||
subject-digest: ${{ steps.push.outputs.digest }}
|
||||
push-to-registry: true
|
||||
@@ -1,8 +1,3 @@
|
||||
### v5.12.0
|
||||
* добавлена проверка пользовательских прав на эндпоинте: гейт вызывает `authorizeEndpoint` модуля из `userAuthSettings` и возвращает 403, если пользователь не имеет права, объявленного в дескрипторе эндпоинта; положительные результаты кэшируются на `caching.authorizationDataInSec`
|
||||
* добавлена очистка хедеров, совпадающих с хедерами пришедшими в `UserAuthData.ExtraHeaders`, перед добавлением
|
||||
### v5.11.4
|
||||
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
|
||||
### v5.11.3
|
||||
* добавлена настройка для преопределения content-type в ответе с `application/json` на `application/json; charset=utf-8` для конкретных приложений
|
||||
### v5.11.2
|
||||
|
||||
@@ -20,7 +20,6 @@ import (
|
||||
|
||||
const (
|
||||
routerModuleName = "isp-router-service"
|
||||
defaultAdminServiceName = "msp-admin-service"
|
||||
usersAuthCachePurgeInterval = 5 * time.Second
|
||||
)
|
||||
|
||||
@@ -34,7 +33,7 @@ type Assembly struct {
|
||||
lockerCli *client.Client
|
||||
routerLb *lb.RoundRobin
|
||||
|
||||
localConfig conf.Local
|
||||
locations []conf.Location
|
||||
grpcClientByModuleName map[string]*client.Client
|
||||
httpHostManagerByModuleName map[string]*lb.RoundRobin
|
||||
|
||||
@@ -86,7 +85,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
server: server,
|
||||
logger: boot.App.Logger(),
|
||||
routes: routes.NewRoutes(boot.App.Logger()),
|
||||
localConfig: localConfig,
|
||||
locations: localConfig.Locations,
|
||||
grpcClientByModuleName: grpcClientByModuleName,
|
||||
httpHostManagerByModuleName: httpHostManagerByModuleName,
|
||||
systemCli: systemCli,
|
||||
@@ -119,7 +118,7 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
a.routerLb,
|
||||
a.usersAuthCache,
|
||||
)
|
||||
handler, err := locator.Handler(newCfg, a.localConfig.Locations)
|
||||
handler, err := locator.Handler(newCfg, a.locations)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "locator handler")
|
||||
}
|
||||
@@ -140,12 +139,8 @@ func (a *Assembly) Runners() []app.Runner {
|
||||
for moduleName, upgrader := range a.httpHostManagerByModuleName {
|
||||
eventHandler.RequireModule(moduleName, upgrader)
|
||||
}
|
||||
adminServiceName := a.localConfig.AdminServiceName
|
||||
if adminServiceName == "" {
|
||||
adminServiceName = defaultAdminServiceName
|
||||
}
|
||||
eventHandler.RequireModule("isp-system-service", a.systemCli)
|
||||
eventHandler.RequireModule(adminServiceName, a.adminCli)
|
||||
eventHandler.RequireModule("msp-admin-service", a.adminCli)
|
||||
eventHandler.RequireModule("isp-lock-service", a.lockerCli)
|
||||
eventHandler.RequireModule(routerModuleName, a.routerLb)
|
||||
|
||||
|
||||
@@ -67,12 +67,10 @@ 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 {
|
||||
@@ -144,7 +142,6 @@ 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),
|
||||
|
||||
+1
-2
@@ -17,9 +17,8 @@ logfile:
|
||||
maxBackups: 4
|
||||
compress: true
|
||||
|
||||
adminServiceName: msp-admin-service
|
||||
|
||||
locations:
|
||||
- pathPrefix: /api
|
||||
protocol: grpc
|
||||
targetModule: router
|
||||
targetModule: router
|
||||
+1
-2
@@ -7,8 +7,7 @@ const (
|
||||
)
|
||||
|
||||
type Local struct {
|
||||
Locations []Location
|
||||
AdminServiceName string
|
||||
Locations []Location
|
||||
}
|
||||
|
||||
type Location struct {
|
||||
|
||||
@@ -96,7 +96,6 @@ 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,7 +10,6 @@ type EndpointMeta struct {
|
||||
|
||||
ModuleName string
|
||||
RequiredAdminPermission string
|
||||
RequiredUserPermission string
|
||||
// Объявляемый сервисом метод
|
||||
PathSchema string
|
||||
// Вызываемый метод
|
||||
|
||||
@@ -15,12 +15,3 @@ type UserAuthData struct {
|
||||
IdentityHeader 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()
|
||||
if err == nil {
|
||||
for key, values := range userAuthData.ExtraHeaders {
|
||||
header.Del(key)
|
||||
for _, value := range values {
|
||||
header.Add(key, value)
|
||||
}
|
||||
|
||||
@@ -49,31 +49,3 @@ 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
|
||||
}
|
||||
@@ -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)
|
||||
requiredUserPerm, _ := cluster.GetRequiredUserPermission(descriptor)
|
||||
meta := domain.EndpointMeta{
|
||||
Inner: descriptor.Inner,
|
||||
UserAuthRequired: descriptor.UserAuthRequired,
|
||||
ModuleName: moduleName,
|
||||
RequiredAdminPermission: requiredAdminPerm,
|
||||
RequiredUserPermission: requiredUserPerm,
|
||||
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
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -37,14 +31,12 @@ 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
|
||||
}
|
||||
@@ -52,7 +44,6 @@ type UserAuthentication struct {
|
||||
func NewUserAuthentication(
|
||||
cfg conf.CustomAuth,
|
||||
cache UserAuthenticationCache,
|
||||
authzCache UserAuthorizationCache,
|
||||
repo UserAuthenticationRepo,
|
||||
) (UserAuthentication, error) {
|
||||
tokenProviders := make(map[string]TokenProvider, len(cfg.TokenProviders))
|
||||
@@ -96,7 +87,6 @@ func NewUserAuthentication(
|
||||
settingsByModuleName[moduleName] = userAuthSetting{
|
||||
tokenProviders: settingTokenProviders,
|
||||
authEndpoint: setting.AuthenticateEndpoint,
|
||||
authorizeEndpoint: setting.AuthorizeEndpoint,
|
||||
authCacheDuration: cacheDuration,
|
||||
skipAppAuth: setting.SkipAppAuth,
|
||||
}
|
||||
@@ -105,7 +95,6 @@ func NewUserAuthentication(
|
||||
|
||||
return UserAuthentication{
|
||||
cache: cache,
|
||||
authzCache: authzCache,
|
||||
repo: repo,
|
||||
settingsByModuleName: settingsByModuleName,
|
||||
}, nil
|
||||
@@ -143,58 +132,6 @@ 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,7 +8,6 @@ import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -383,13 +382,11 @@ 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",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -524,14 +521,12 @@ 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",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -584,163 +579,6 @@ 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