Compare commits

..
44 Commits
Author SHA1 Message Date
txix 36699fdc72 2026-08-28 15:17:49: merge [main:657d4302881986193395aa831b36df6fd0798d4d];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-08-28 15:17:49 +03:00
txix a269de8e17 2026-07-27 16:33:30: merge [main:227a2a069d1922a94e2a88af2863dac3035f705d];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-27 16:33:30 +03:00
txix 15cb2cadf2 2026-07-07 10:21:49: merge [main:7d936adaf0486f3328902461e9a32ae3539e9e64];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-07 10:21:49 +03:00
txix 76f88fd593 2026-05-12 13:56:16: merge [main:81e9195d79a530c26a2640652f946389f536842f];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-05-12 13:56:16 +03:00
txix 9ff0057014 2026-04-20 12:28:32: merge [main:ac8a556442b323a61053fc1f978ce68455350ad0];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-04-20 12:28:32 +03:00
txix 71a1f0a04e 2026-04-08 18:36:43: merge [main:cca6ce0ad1fef44571b4a61f1aca34f2e41ce5cd];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-04-08 18:36:43 +03:00
txix 394bbc82e2 2026-04-06 15:36:37: merge [main:48e53159863d08bc31c4e926d73c0bb4341128ae];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-04-06 15:36:37 +03:00
txix 7de248e63c 2026-03-31 16:58:42: merge [main:8b672bdd308ebb53d48d75a6a5bfbdb7ea8d7ddd];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-31 16:58:43 +03:00
txix 011a1d7048 2026-03-24 17:42:31: merge [main:c523d2347d1bdc87bceae397a11ecfc8776ff8aa];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-24 17:42:31 +03:00
txix f3fb9cff75 2026-03-18 17:07:55: merge [main:1bd032e5aa9a3d83735ea3fb30aeab719d917b82];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-18 17:07:55 +03:00
txix c7bd042239 2026-03-10 10:38:58: merge [main:aae3c282252c73901b8e48b1412f48217b1a6195];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-03-10 10:38:58 +03:00
txix 202fa7035e 2026-01-27 15:11:45: merge [main:30d731ebfa46bcfb3fa1c39f4580293dc546acc0];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-27 15:11:45 +03:00
txix 602a2a1ac4 2026-01-27 13:25:45: merge [main:e5e723811e7a9dc57a6ff5d1c067c07c23a97210];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-27 13:25:45 +03:00
txix 6a3abf67a2 2026-01-23 13:09:31: merge [main:63c694e2a33c8c0b025f62619d2814f536915e49];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-23 13:09:31 +03:00
txix 2f88738f78 2026-01-23 12:57:58: merge [main:4f90477e73bbbbbfe9cdb168b87e0ea201679912];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-23 12:57:58 +03:00
txix a637d56ea7 2026-01-14 11:52:30: merge [main:1a274e79e588612933ce36c33b236a91fc74db9a];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-01-14 11:52:30 +03:00
txix a841cd082b 2025-12-26 09:37:14: merge [main:2b5ee66527f48ea4e6111148c0ba3c23611d6772];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-12-26 09:37:14 +03:00
txix 9b18fe7351 2025-11-26 13:43:01: merge [main:e9c5c9b80517122ca122933c111070bf470e31c1];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-11-26 13:43:01 +03:00
txix f3c801e4a4 2025-11-26 10:05:59: merge [main:96f8e79d3384c01bf52552f94afdf4ed662997e5];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-11-26 10:05:59 +03:00
txix ee13991d87 2025-10-03 15:15:07: merge [main:c3e3ed9636c6987e89feaf39503dda74462fcfde];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-03 15:15:07 +03:00
txix d4846359e4 2025-10-02 16:02:08: merge [main:13db082fcac220b28433a207845ceb3bef8bd07d];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-02 16:02:08 +03:00
txix 13cf0075f6 2025-09-17 18:07:26: merge [main:f5bfe7d2ba0d7a2f391f4ffaff6fffc1686ba3c7];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-17 18:07:26 +03:00
txix 135e551473 2025-08-21 15:04:13: merge [main:a4b6e5fd1d9685c751c5988518e9f8dd62a8e519]; 2025-08-21 15:04:13 +03:00
txix 689f730a3e 2025-07-09 12:35:19: merge [main:9f485b5e57937029be52e58137ef79ad5c3ca524];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-09 12:35:19 +03:00
txix a30582fa38 2025-07-03 12:26:31: merge [main:66e6c4b9c432b19b644d033703545d38aba3b847];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-03 12:26:31 +03:00
txix 5b1ce14467 2025-07-01 16:40:11: merge [main:61f11c0bda72fe35f473f8302edfaf86f151c0ad];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-01 16:40:11 +03:00
txix 264b438cdb 2025-07-01 13:32:55: merge [main:6491e79afd06cd665731c89f8ab2cd373351c1b4]; 2025-07-01 13:32:55 +03:00
txix f699aefa58 2025-05-27 14:32:05: merge [master:01f8dcdc36fb3f9867a65ffb7379ad25c85cd988];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-05-27 14:32:05 +03:00
txix 8d40e76637 2025-05-13 13:05:46: merge [master:49d1bfaa3f027c5465de7a0c0d46a9bab0588e19]; 2025-05-13 13:05:46 +03:00
txix e2b4becfd6 2025-04-29 14:57:30: merge [master:357ce03935a551e8be5766b349a621104998de83]; 2025-04-29 14:57:30 +03:00
txix e4ef2d8645 2025-04-23 12:39:56: merge [master:82ac257e917aa3f9ab915b911afbd28c0f52f88e]; 2025-04-23 12:39:56 +03:00
txix bfc28503d5 2025-04-18 12:46:39: merge [master:7b5fc0b41640a6b6648e6391777fa08099997af1]; 2025-04-18 12:46:39 +03:00
txix d759f883f4 2025-04-18 12:26:12: merge [master:576ef18526fa6f0685f8ab997cae0d31a4ebce90]; 2025-04-18 12:26:13 +03:00
txix 64373fdf3c 2025-04-03 17:31:43: merge [master:03df79d7b37febb99439347c2da79707bf437498]; 2025-04-03 17:31:43 +03:00
txix 1dd566593e 2024-12-27 17:46:16: merge [master:4898a95fc423e3ae55135d3023a1b78fb18edebc]; 2024-12-27 17:46:16 +03:00
txix 560c1f22c4 2024-12-27 12:28:18: merge [master:9ec52bd8525d6120bfebe62b6da4eb172a000ee8]; 2024-12-27 12:28:18 +03:00
txix 171b85f627 2024-12-27 12:14:12: merge [master:bf6ba426f66d82ef1e76da30674890898919501b]; 2024-12-27 12:14:12 +03:00
txix 734b83b2b8 2024-12-11 12:34:04: merge [master:744eaa2605c9d3eb73b2db76661b2d0a6949d4d9]; 2024-12-11 12:34:04 +03:00
txix bdeb2c0753 2024-12-03 13:02:16: merge [master:b21f96b8a5ec988002a89bd9d1f51e90c01a2d21]; 2024-12-03 13:02:16 +03:00
txix 97c44fb3bd 2024-10-11 14:58:36: merge [master:7f99b95ceaaed865d2833070a0397cf191949b8e]; 2024-10-11 14:58:36 +03:00
txix 6db18c1495 2024-07-01 10:56:14: merge [master:f9b2632335c35844013af97443dacebb9fc385c5]; 2024-07-01 10:56:14 +03:00
txix cd985ff5a3 2024-03-26 12:20:05: merge [master:27c825f7051ccbb42344a2d66c50192e2b3b5889]; 2024-03-26 12:20:05 +03:00
txix 2eed857503 2024-03-22 15:21:57: merge [master:d3624ee87e4530490024ae4023a1c69643689e95]; 2024-03-22 15:21:57 +03:00
txix 2b91caece0 2024-01-22 17:22:41: merge [master:56d3e06e49d7a75f142424293788a4f3b6245430]; 2024-01-22 17:22:41 +03:00
17 changed files with 67 additions and 380 deletions

No files matched your search

+60
View File
@@ -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 -1
View File
@@ -1 +1 @@
5.12.0
5.11.3
-5
View File
@@ -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
+4 -9
View File
@@ -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)
-3
View File
@@ -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
View File
@@ -17,9 +17,8 @@ logfile:
maxBackups: 4
compress: true
adminServiceName: msp-admin-service
locations:
- pathPrefix: /api
protocol: grpc
targetModule: router
targetModule: router
+1 -2
View File
@@ -7,8 +7,7 @@ const (
)
type Local struct {
Locations []Location
AdminServiceName string
Locations []Location
}
type Location struct {
-1
View File
@@ -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:"Пропустить аутентификацию и авторизацию приложения"`
}
-1
View File
@@ -10,7 +10,6 @@ type EndpointMeta struct {
ModuleName string
RequiredAdminPermission string
RequiredUserPermission string
// Объявляемый сервисом метод
PathSchema string
// Вызываемый метод
-9
View File
@@ -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
}
-54
View File
@@ -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)
})
}
}
-1
View File
@@ -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)
}
-28
View File
@@ -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
}
-37
View File
@@ -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)
}
-2
View File
@@ -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,
}
-63
View File
@@ -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)
-162
View File
@@ -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{