Compare commits
28
Commits
dev
..
txix-release
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2563cb294 | ||
|
|
5cb3885330 | ||
|
|
554123722d | ||
|
|
a791e0f678 | ||
|
|
c1bb2cf4ed | ||
|
|
0ad3e3dead | ||
|
|
aebc53174b | ||
|
|
88e5ffedad | ||
|
|
71a841fee0 | ||
|
|
3029e084ce | ||
|
|
14bd29e48f | ||
|
|
32466576b0 | ||
|
|
121f63f57a | ||
|
|
7c9e12685d | ||
|
|
2b167919b1 | ||
|
|
f10153a53b | ||
|
|
83b10f368c | ||
|
|
8789f8a5ec | ||
|
|
3bbe1c3952 | ||
|
|
e1de1c31d8 | ||
|
|
0166d4a050 | ||
|
|
5d7c8f48c3 | ||
|
|
8ec71761d3 | ||
|
|
f8074400a1 | ||
|
|
daf35df301 | ||
|
|
1efb8fa354 | ||
|
|
17747f5b74 | ||
|
|
ed8a4eef5d |
No files matched your search
@@ -20,12 +20,7 @@ linters:
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
- godoclint # ругается на // nolint, не удобно
|
||||
- prealloc # слишком аггресивный, в большинстве случаев не требуется
|
||||
- gomodguard # deprecated
|
||||
- goconst # слишком агрессивный
|
||||
settings:
|
||||
exhaustruct_v5:
|
||||
allow-empty: true
|
||||
explicit-mode: true
|
||||
cyclop:
|
||||
max-complexity: 15 # по умолчанию 10 мало
|
||||
funlen:
|
||||
@@ -65,9 +60,6 @@ linters:
|
||||
- unqueryvet
|
||||
- prealloc
|
||||
path: ".*_test\\.go$"
|
||||
- linters:
|
||||
- goconst
|
||||
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
@@ -81,4 +73,3 @@ formatters:
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
@@ -1,8 +1,3 @@
|
||||
### v7.2.0
|
||||
* Добавлено поле `application_group` в таблицу `roles`
|
||||
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
|
||||
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
|
||||
* Добавлена возможность скачивания и формирования CSV
|
||||
### v7.1.0
|
||||
* переименование авторизации через SUDIR в OAuth:
|
||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.27-alpine as builder
|
||||
FROM golang:1.26-alpine as builder
|
||||
WORKDIR /build
|
||||
ARG version
|
||||
ENV version_env=$version
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
|
||||
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.27 git
|
||||
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.24 git
|
||||
WORKDIR /build
|
||||
ARG version
|
||||
ENV version_env=$version
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
@@ -26,7 +26,7 @@ import (
|
||||
type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
db *dbrx.Client
|
||||
server *http.Server
|
||||
server *grpc.Server
|
||||
oauthCli *httpcli.Client
|
||||
logger *log.Adapter
|
||||
bgjobCli *bgjobx.Client
|
||||
@@ -43,7 +43,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
return &Assembly{
|
||||
boot: boot,
|
||||
db: db,
|
||||
server: http.NewServer(logger),
|
||||
server: grpc.NewServer(),
|
||||
logger: logger,
|
||||
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||
bgjobCli: bgjobCli,
|
||||
@@ -109,7 +109,7 @@ func (a *Assembly) Runners() []app.Runner {
|
||||
app.RunnerFunc(func(ctx context.Context) error {
|
||||
err := a.server.ListenAndServe(a.boot.BindingAddress)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "listen and serve http server")
|
||||
return errors.WithMessage(err, "listen ans serve grpc server")
|
||||
}
|
||||
return nil
|
||||
}),
|
||||
@@ -127,7 +127,7 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
return []app.Closer{
|
||||
a.boot.ClusterCli,
|
||||
app.CloserFunc(func() error {
|
||||
_ = a.server.Shutdown(context.Background())
|
||||
a.server.Shutdown()
|
||||
return nil
|
||||
}),
|
||||
app.CloserFunc(func() error {
|
||||
|
||||
+4
-17
@@ -18,10 +18,9 @@ import (
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/endpoint/httplog"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
@@ -45,7 +44,7 @@ func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Handler *router.Router
|
||||
Handler isp.BackendServiceServer
|
||||
BgJobCfg []bgjobx.WorkerConfig
|
||||
}
|
||||
|
||||
@@ -98,14 +97,6 @@ func (l Locator) Config(
|
||||
|
||||
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
||||
|
||||
downloadService := service.NewDownload(
|
||||
auditService,
|
||||
userService,
|
||||
tokenService,
|
||||
roleService,
|
||||
permissionsService,
|
||||
)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
authController := controller.NewAuth(authService, l.logger)
|
||||
@@ -115,11 +106,8 @@ func (l Locator) Config(
|
||||
roleController := controller.NewRole(roleService)
|
||||
permissionController := controller.NewPermissions(permissionsService)
|
||||
uiSettingsController := controller.NewUiSettings(uiSettingsService)
|
||||
downloadController := controller.NewDownload(downloadService)
|
||||
|
||||
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
|
||||
handler := routes.Handler(
|
||||
wrapper,
|
||||
endpoint.DefaultWrapper(l.logger),
|
||||
routes.Controllers{
|
||||
User: userController,
|
||||
Customization: customizationController,
|
||||
@@ -130,7 +118,6 @@ func (l Locator) Config(
|
||||
Role: roleController,
|
||||
Permissions: permissionController,
|
||||
UiSettings: uiSettingsController,
|
||||
Download: downloadController,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
// StringFromHeader extracts a string value from header by key.
|
||||
// Returns an error if header is nil or the key is not found.
|
||||
func StringFromHeader(key string, h http.Header) (string, error) {
|
||||
if h == nil {
|
||||
return "", errors.New("header is nil")
|
||||
}
|
||||
values := h.Values(key)
|
||||
if len(values) == 0 {
|
||||
return "", errors.Errorf("'%s' is expected in header", key)
|
||||
}
|
||||
return values[0], nil
|
||||
}
|
||||
|
||||
// IntFromHeader extracts an integer value from header by key.
|
||||
// Returns an error if the key is not found or the value cannot be parsed as an integer.
|
||||
func IntFromHeader(key string, h http.Header) (int, error) {
|
||||
value, err := StringFromHeader(key, h)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
intValue, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return 0, errors.WithMessagef(err, "parse '%s' to int", key)
|
||||
}
|
||||
return intValue, nil
|
||||
}
|
||||
+35
-36
@@ -2,12 +2,12 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type AuditService interface {
|
||||
@@ -27,17 +27,16 @@ func NewAudit(service AuditService) Audit {
|
||||
}
|
||||
|
||||
// All
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/all [POST]
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.AuditResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/all [POST]
|
||||
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -50,38 +49,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
|
||||
}
|
||||
|
||||
// Events
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Получение списка событий аудита
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/events [POST]
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.AuditResponse true "Тело запроса"
|
||||
// @Success 200 {array} domain.AuditEvent
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/events [POST]
|
||||
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
|
||||
return c.service.Events(ctx)
|
||||
}
|
||||
|
||||
// SetEvents
|
||||
//
|
||||
// @Tags log
|
||||
// @Summary Установить события аудита
|
||||
// @Description Устанавливает (обновляет) набор активных событий аудита.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
|
||||
// @Success 200 {object} map[string]interface{} "События успешно установлены"
|
||||
// @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /log/set_events [POST]
|
||||
// @Tags log
|
||||
// @Summary Получение списка логов
|
||||
// @Description Всегда возвращает полный список доступных событий аудита
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SetAuditEvent true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /log/set_events [POST]
|
||||
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
|
||||
err := c.service.SetEvents(ctx, req)
|
||||
switch {
|
||||
case errors.As(err, &domain.UnknownAuditEventError{}):
|
||||
return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
|
||||
return status.Error(codes.InvalidArgument, err.Error())
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
+60
-64
@@ -2,15 +2,16 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"isp-admin-service/auth"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type authService interface {
|
||||
@@ -32,19 +33,18 @@ func NewAuth(authService authService, logger log.Logger) Auth {
|
||||
}
|
||||
|
||||
// Logout
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags auth
|
||||
// @Summary Выход из авторизованной сессии
|
||||
// @Description Выход из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout [POST]
|
||||
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,20 +58,19 @@ func (a Auth) Logout(ctx context.Context, r *http.Request) error {
|
||||
}
|
||||
|
||||
// LogoutWithReason
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Success 200 {object} map[string]interface{} "Успешный выход"
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -85,30 +84,28 @@ func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutR
|
||||
}
|
||||
|
||||
// Login
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
|
||||
// @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login [POST]
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по логину и паролю
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login [POST]
|
||||
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
|
||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid credential")
|
||||
case errors.Is(err, domain.ErrTooManyLoginRequests):
|
||||
return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
|
||||
return nil, status.Error(codes.ResourceExhausted, "too many requests")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login")
|
||||
default:
|
||||
@@ -117,26 +114,25 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
||||
}
|
||||
|
||||
// LoginWithOauth
|
||||
//
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора.
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithOauth(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
|
||||
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with oauth")
|
||||
default:
|
||||
@@ -144,15 +140,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
|
||||
}
|
||||
}
|
||||
|
||||
func getAdminId(r *http.Request) (int64, error) {
|
||||
token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
|
||||
func getAdminId(authData grpc.AuthData) (int64, error) {
|
||||
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData))
|
||||
if err != nil {
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
return 0, status.Error(codes.InvalidArgument, err.Error())
|
||||
}
|
||||
|
||||
adminId, err := strconv.Atoi(token)
|
||||
if err != nil {
|
||||
return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
|
||||
return 0, status.Error(codes.InvalidArgument, "admin id is not a number")
|
||||
}
|
||||
|
||||
return int64(adminId), nil
|
||||
|
||||
+10
-11
@@ -19,17 +19,16 @@ func NewCustomization(uiCfg conf.UIDesign) Customization {
|
||||
}
|
||||
|
||||
// GetUIDesign
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UIDesign
|
||||
// @Failure 400 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_design [POST]
|
||||
// @Tags user
|
||||
// @Summary Получение внешнего вида
|
||||
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UIDesign
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_design [POST]
|
||||
func (c Customization) GetUIDesign() (domain.UIDesign, error) {
|
||||
return c.uiCfg, nil
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type DownloadService interface {
|
||||
DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error
|
||||
DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error
|
||||
DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error
|
||||
DownloadRoles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error
|
||||
}
|
||||
|
||||
type Download struct {
|
||||
service DownloadService
|
||||
}
|
||||
|
||||
func NewDownload(service DownloadService) Download {
|
||||
return Download{
|
||||
service: service,
|
||||
}
|
||||
}
|
||||
|
||||
// Users
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список пользователей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /user/download [POST]
|
||||
func (c Download) Users(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadUsers(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download users")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Sessions
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать список сессий в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /session/download [POST]
|
||||
func (c Download) Sessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadSessions(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download sessions")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Audit
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать журнал аудита в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Param body body domain.AuditPageRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /log/download [POST]
|
||||
func (c Download) Audit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadAudit(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download audit")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Roles
|
||||
//
|
||||
// @Tags Download
|
||||
// @Summary Скачать матрицу ролей в csv
|
||||
// @Accept json
|
||||
// @Produce text/csv
|
||||
// @Success 200
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка сервиса ```{errorCode: -1}```"
|
||||
// @Router /role/download [POST]
|
||||
func (c Download) Roles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error {
|
||||
err := c.service.DownloadRoles(ctx, req, w)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "download roles")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -21,15 +21,13 @@ func NewPermissions(permissionsService permissionsService) Permissions {
|
||||
}
|
||||
|
||||
// GetPermissions
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить все разрешения
|
||||
// @Description Получить все разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_permissions [POST]
|
||||
// @Tags user
|
||||
// @Summary Получить все разрашения
|
||||
// @Description Получить все разрашения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Permission
|
||||
// @Router /user/get_permissions [POST]
|
||||
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
|
||||
return u.permissionsService.All(ctx)
|
||||
}
|
||||
+60
-63
@@ -2,16 +2,17 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
|
||||
All(ctx context.Context) ([]domain.Role, error)
|
||||
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
||||
@@ -28,19 +29,18 @@ func NewRole(roleService roleService) Role {
|
||||
}
|
||||
|
||||
// All
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx, req)
|
||||
// @Tags role
|
||||
// @Summary Список ролей
|
||||
// @Description Получить список ролей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles")
|
||||
}
|
||||
@@ -49,21 +49,20 @@ func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role
|
||||
}
|
||||
|
||||
// CreateRole
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Создать роль
|
||||
// @Description Создать роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/create [POST]
|
||||
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -71,7 +70,7 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
|
||||
role, err := u.roleService.Create(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create role")
|
||||
default:
|
||||
@@ -80,21 +79,20 @@ func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *h
|
||||
}
|
||||
|
||||
// UpdateRole
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags role
|
||||
// @Summary Обновить роль
|
||||
// @Description Обновить данные существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateRoleRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.Role
|
||||
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/update [POST]
|
||||
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -102,9 +100,9 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
|
||||
result, err := u.roleService.Update(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
return nil, status.Error(codes.NotFound, "role not found")
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
return nil, status.Error(codes.AlreadyExists, "role with current name already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update role")
|
||||
default:
|
||||
@@ -113,20 +111,19 @@ func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *h
|
||||
}
|
||||
|
||||
// DeleteRole
|
||||
//
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags role
|
||||
// @Summary Удалить роль
|
||||
// @Description Удалить существующую роль
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.DeleteRoleRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/delete [POST]
|
||||
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+19
-21
@@ -6,7 +6,7 @@ import (
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
@@ -25,16 +25,15 @@ func NewSecure(service SecureService) Secure {
|
||||
}
|
||||
|
||||
// Authenticate
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authenticate [POST]
|
||||
// @Tags secure
|
||||
// @Summary Метод аутентификации токена
|
||||
// @Description Проверяет токен и возвращает идентификатор администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authenticate [POST]
|
||||
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
|
||||
adminId, err := s.service.Authenticate(ctx, req.Token)
|
||||
switch {
|
||||
@@ -62,16 +61,15 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
|
||||
}
|
||||
|
||||
// Authorize
|
||||
//
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /secure/authorize [POST]
|
||||
// @Tags secure
|
||||
// @Summary Метод авторизации для администратора
|
||||
// @Description Проверяет наличие у администратора необходимого разрешения
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.SecureAuthzRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SecureAuthzResponse
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /secure/authorize [POST]
|
||||
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
|
||||
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
|
||||
if err != nil {
|
||||
|
||||
+20
-22
@@ -22,17 +22,16 @@ func NewSession(service SessionService) Session {
|
||||
}
|
||||
|
||||
// All
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/all [POST]
|
||||
// @Tags session
|
||||
// @Summary Получение списка сессий
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.SessionPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.SessionResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/all [POST]
|
||||
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -45,17 +44,16 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
|
||||
}
|
||||
|
||||
// Revoke
|
||||
//
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /session/revoke [POST]
|
||||
// @Tags session
|
||||
// @Summary Отзыв сессии
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RevokeRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /session/revoke [POST]
|
||||
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
|
||||
return c.service.Revoke(ctx, req.Id)
|
||||
}
|
||||
+14
-15
@@ -3,10 +3,10 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type UiSettingsService interface {
|
||||
@@ -24,23 +24,22 @@ func NewUiSettings(service UiSettingsService) UiSettings {
|
||||
}
|
||||
|
||||
// UiOauthSettings
|
||||
//
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
resp, err := c.service.OauthSettings(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnknownClient):
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
|
||||
+120
-127
@@ -2,13 +2,15 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/http/apierrors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type userService interface {
|
||||
@@ -34,20 +36,19 @@ func NewUser(userService userService) User {
|
||||
}
|
||||
|
||||
// GetProfile
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 401 {object} apierrors.Error "Невалидный токен"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователя не существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Получить профиль
|
||||
// @Description Получить данные профиля
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.AdminUserShort
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователя не существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_profile [POST]
|
||||
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -55,9 +56,9 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
|
||||
profile, err := u.userService.GetProfileById(ctx, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
|
||||
return nil, status.Error(codes.Unauthenticated, "user is blocked")
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get profile")
|
||||
default:
|
||||
@@ -66,18 +67,17 @@ func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUse
|
||||
}
|
||||
|
||||
// GetUsers
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_users [POST]
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UsersPageRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_users [POST]
|
||||
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
|
||||
if req.Order == nil {
|
||||
req.Order = &domain.OrderParams{
|
||||
@@ -95,17 +95,16 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
|
||||
}
|
||||
|
||||
// GetAllUsers
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} apierrors.Error
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_all_users [POST]
|
||||
// @Tags user
|
||||
// @Summary Список пользователей
|
||||
// @Description Получить список пользователей
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200 {object} domain.UsersResponse
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_all_users [POST]
|
||||
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
users, err := u.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
@@ -116,21 +115,20 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
|
||||
}
|
||||
|
||||
// CreateUser
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Создать пользователя
|
||||
// @Description Создать пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.CreateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/create_user [POST]
|
||||
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -138,7 +136,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
|
||||
user, err := u.userService.CreateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "create user")
|
||||
default:
|
||||
@@ -147,22 +145,21 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *h
|
||||
}
|
||||
|
||||
// UpdateUser
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Обновить пользователя
|
||||
// @Description Обновить данные существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.UpdateUserRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует"
|
||||
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/update_user [POST]
|
||||
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -170,11 +167,11 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
|
||||
result, err := u.userService.UpdateUser(ctx, req, adminId)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
|
||||
return nil, status.Error(codes.NotFound, "user not found")
|
||||
case errors.Is(err, domain.ErrInvalid):
|
||||
return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
|
||||
return nil, status.Error(codes.InvalidArgument, "user modification is not available")
|
||||
case errors.Is(err, domain.ErrAlreadyExists):
|
||||
return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
|
||||
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "update user")
|
||||
default:
|
||||
@@ -183,20 +180,19 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *h
|
||||
}
|
||||
|
||||
// DeleteUser
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Удалить пользователя
|
||||
// @Description Удалить существующего пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdentitiesRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.DeleteResponse
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/delete_user [POST]
|
||||
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -210,19 +206,18 @@ func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesReques
|
||||
}
|
||||
|
||||
// Block
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Метод блокировки/разблокировки пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/block_user [POST]
|
||||
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -235,34 +230,32 @@ func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Re
|
||||
}
|
||||
|
||||
// GetById
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error
|
||||
// @Router /user/get_by_id [POST]
|
||||
// @Tags user
|
||||
// @Summary Метод получения данных по пользователю
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.IdRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.User
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /user/get_by_id [POST]
|
||||
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
|
||||
return u.userService.GetById(ctx, identities.UserId)
|
||||
}
|
||||
|
||||
// ChangePassword
|
||||
//
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
|
||||
// @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
|
||||
adminId, err := getAdminId(r)
|
||||
// @Tags user
|
||||
// @Summary Метод изменения пароля пользователя
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.ChangePasswordRequest true "Тело запроса"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
|
||||
// @Failure 500 {object} apierrors.Error "внутренняя ошибка"
|
||||
// @Router /user/change_password [POST]
|
||||
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -270,7 +263,7 @@ func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordReque
|
||||
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrInvalidPassword):
|
||||
return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
|
||||
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err)
|
||||
case err != nil:
|
||||
return apierrors.NewInternalServiceError(err)
|
||||
default:
|
||||
|
||||
+116
-263
@@ -46,25 +46,19 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Данные для авторизации не верны",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"429": {
|
||||
"description": "Слишком много запросов на авторизацию",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,7 +66,7 @@
|
||||
},
|
||||
"/auth/login_with_oauth": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора.",
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -101,22 +95,22 @@
|
||||
"$ref": "#/definitions/domain.LoginResponse"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Авторизация OAuth не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Некорректный код для авторизации или неизвестное название клиента",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация OAuth не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,22 +140,18 @@
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Успешный выход",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,13 +171,6 @@
|
||||
],
|
||||
"summary": "Выход по бездействию из авторизованной сессии",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
@@ -196,26 +179,29 @@
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LogoutRequest"
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"description": "Токен администратора",
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Успешный выход",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,7 +228,7 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса (пагинация, сортировка, фильтры)",
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
@@ -261,49 +247,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/log/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать журнал аудита в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.AuditPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -321,7 +271,7 @@
|
||||
"tags": [
|
||||
"log"
|
||||
],
|
||||
"summary": "Получение списка событий аудита",
|
||||
"summary": "Получение списка логов",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
@@ -329,6 +279,15 @@
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.AuditResponse"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -341,10 +300,16 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -352,7 +317,7 @@
|
||||
},
|
||||
"/log/set_events": {
|
||||
"post": {
|
||||
"description": "Устанавливает (обновляет) набор активных событий аудита.",
|
||||
"description": "Всегда возвращает полный список доступных событий аудита",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -362,7 +327,7 @@
|
||||
"tags": [
|
||||
"log"
|
||||
],
|
||||
"summary": "Установить события аудита",
|
||||
"summary": "Получение списка логов",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "string",
|
||||
@@ -372,36 +337,29 @@
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Список событий аудита для установки",
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/domain.SetAuditEvent"
|
||||
}
|
||||
"$ref": "#/definitions/domain.SetAuditEvent"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "События успешно установлены",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": true
|
||||
}
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"description": "Неизвестное событие аудита",
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -442,13 +400,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -464,7 +422,7 @@
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"role"
|
||||
"user"
|
||||
],
|
||||
"summary": "Создать роль",
|
||||
"parameters": [
|
||||
@@ -489,25 +447,25 @@
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.Role"
|
||||
"$ref": "#/definitions/domain.User"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Роль с указанным именем уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -551,38 +509,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/role/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать матрицу ролей в csv",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -629,19 +562,19 @@
|
||||
"404": {
|
||||
"description": "Роль с указанным id не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Роль с указанным именем уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,7 +614,7 @@
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -721,7 +654,7 @@
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -767,49 +700,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/session/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать список сессий в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.SessionPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -852,13 +749,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -898,19 +795,19 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Неизвестное название клиента",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -953,13 +850,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1000,13 +897,13 @@
|
||||
"description": "OK"
|
||||
},
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса или неверный старый пароль",
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка",
|
||||
"description": "внутренняя ошибка",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
@@ -1055,19 +952,19 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1114,49 +1011,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/user/download": {
|
||||
"post": {
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"text/csv"
|
||||
],
|
||||
"tags": [
|
||||
"Download"
|
||||
],
|
||||
"summary": "Скачать список пользователей в csv",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UsersPageRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK"
|
||||
},
|
||||
"500": {
|
||||
"description": "Внутренняя ошибка сервиса ```{errorCode: -1}```",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1194,13 +1055,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1239,13 +1100,13 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1283,13 +1144,13 @@
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1297,7 +1158,7 @@
|
||||
},
|
||||
"/user/get_permissions": {
|
||||
"post": {
|
||||
"description": "Получить все разрешения",
|
||||
"description": "Получить все разрашения",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -1307,7 +1168,7 @@
|
||||
"tags": [
|
||||
"user"
|
||||
],
|
||||
"summary": "Получить все разрешения",
|
||||
"summary": "Получить все разрашения",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
@@ -1317,12 +1178,6 @@
|
||||
"$ref": "#/definitions/domain.Permission"
|
||||
}
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1356,22 +1211,22 @@
|
||||
"$ref": "#/definitions/domain.AdminUserShort"
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"400": {
|
||||
"description": "Невалидный токен",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователя не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1418,13 +1273,13 @@
|
||||
"400": {
|
||||
"description": "Bad Request",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1471,25 +1326,25 @@
|
||||
"400": {
|
||||
"description": "Невалидное тело запроса",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"404": {
|
||||
"description": "Пользователь с указанным id не существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "Пользователь с указанным email уже существует",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
},
|
||||
"500": {
|
||||
"description": "Internal Server Error",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/apierrors.Error"
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1709,10 +1564,6 @@
|
||||
"domain.CreateRoleRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
@@ -1805,6 +1656,21 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.GrpcError": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"details": {
|
||||
"type": "array",
|
||||
"items": {}
|
||||
},
|
||||
"errorCode": {
|
||||
"type": "string"
|
||||
},
|
||||
"errorMessage": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.IdRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -1939,10 +1805,6 @@
|
||||
"domain.Role": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
@@ -2187,10 +2049,6 @@
|
||||
"domain.UpdateRoleRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
@@ -2353,11 +2211,6 @@
|
||||
"limit"
|
||||
],
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Фильтр по группе приложений",
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"limit": {
|
||||
"description": "Максимальное количество записей",
|
||||
"type": "integer"
|
||||
|
||||
+1
-1
@@ -17,7 +17,7 @@ type AuditResponse struct {
|
||||
}
|
||||
|
||||
type AuditPageRequest struct {
|
||||
LimitOffsetParams
|
||||
LimitOffestParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *AuditQuery // Параметры выборки
|
||||
|
||||
@@ -26,19 +26,6 @@ var (
|
||||
ErrUnknownClient = errors.New("unknown client")
|
||||
)
|
||||
|
||||
const (
|
||||
UnknownAuditEventErrorCode = 601
|
||||
ErrOauthAuthorizationCode = 602
|
||||
ErrUnauthenticatedCode = 603
|
||||
ErrTooManyLoginRequestsCode = 604
|
||||
ErrOauthIsMissedCode = 605
|
||||
ErrAlreadyExistsCode = 606
|
||||
ErrNotFoundCode = 607
|
||||
ErrUnknownClientCode = 608
|
||||
ErrInvalidCode = 609
|
||||
ErrInvalidPasswordCode = 610
|
||||
)
|
||||
|
||||
type UnknownAuditEventError struct {
|
||||
Event string
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package domain
|
||||
|
||||
type GrpcError struct {
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
ErrorCode string `json:"errorCode"`
|
||||
Details []any `json:"details"`
|
||||
}
|
||||
+1
-1
@@ -7,7 +7,7 @@ const (
|
||||
DefaultOrderType = "desc"
|
||||
)
|
||||
|
||||
type LimitOffsetParams struct {
|
||||
type LimitOffestParams struct {
|
||||
Limit uint64 `validate:"required"` // Максимальное количество записей
|
||||
Offset uint64 // Отступ для выборки
|
||||
}
|
||||
|
||||
+18
-25
@@ -5,39 +5,32 @@ import (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time // Дата создания
|
||||
UpdatedAt time.Time // Дата обновления
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time // Дата создания
|
||||
UpdatedAt time.Time // Дата обновления
|
||||
}
|
||||
|
||||
type CreateRoleRequest struct {
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type UpdateRoleRequest struct {
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type DeleteRoleRequest struct {
|
||||
Id int // Идентификатор роли
|
||||
}
|
||||
|
||||
type RoleAllRequest struct {
|
||||
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
|
||||
}
|
||||
+1
-24
@@ -4,17 +4,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Id int // Идентификатор сессии
|
||||
UserId int // Идентификатор пользоватеккля
|
||||
@@ -24,7 +13,7 @@ type Session struct {
|
||||
}
|
||||
|
||||
type SessionPageRequest struct {
|
||||
LimitOffsetParams
|
||||
LimitOffestParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *SessionQuery // Параметры выборки
|
||||
@@ -46,15 +35,3 @@ type SessionResponse struct {
|
||||
type RevokeRequest struct {
|
||||
Id int `validate:"required"` // Идентификатор сессии
|
||||
}
|
||||
|
||||
func (s Session) StatusRus() string {
|
||||
switch s.Status {
|
||||
case SessionStatusAllowed:
|
||||
return SessionStatusAllowedRus
|
||||
case SessionStatusExpired:
|
||||
return SessionStatusExpiredRus
|
||||
case SessionStatusRevoked:
|
||||
return SessionStatusRevokedRus
|
||||
}
|
||||
return ""
|
||||
}
|
||||
+1
-2
@@ -32,8 +32,7 @@ type UserQuery struct {
|
||||
}
|
||||
|
||||
type UsersPageRequest struct {
|
||||
LimitOffsetParams
|
||||
RoleAllRequest
|
||||
LimitOffestParams
|
||||
|
||||
Order *OrderParams // Параметры сортировки
|
||||
Query *UserQuery // Параметры выборки
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package entity
|
||||
|
||||
const (
|
||||
SessionStatusAllowed = "ALLOWED"
|
||||
SessionStatusAllowedRus = "Активная"
|
||||
|
||||
SessionStatusExpired = "EXPIRED"
|
||||
SessionStatusExpiredRus = "Истекшая"
|
||||
|
||||
SessionStatusRevoked = "REVOKED"
|
||||
SessionStatusRevokedRus = "Отмененная"
|
||||
)
|
||||
|
||||
func AuditColumnNames() []string {
|
||||
return []string{"Пользователь", "Время события", "Действие"}
|
||||
}
|
||||
|
||||
func SessionColumnNames() []string {
|
||||
return []string{"Пользователь", "Идентификатор", "Дата начала сессии", "Дата окончания сессии", "Статус"}
|
||||
}
|
||||
|
||||
func UserColumnNames() []string {
|
||||
return []string{"id", "Пользователь", "Описание", "Email", "Роль", "Последняя сессия"}
|
||||
}
|
||||
|
||||
func RoleColumnNames() []string {
|
||||
return []string{"Действие", "Ключ в системе"}
|
||||
}
|
||||
+8
-9
@@ -13,15 +13,14 @@ const (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ApplicationGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type PermList []string
|
||||
|
||||
@@ -5,7 +5,6 @@ import "time"
|
||||
type User struct {
|
||||
OauthUserId *string
|
||||
Id int64
|
||||
Roles []int
|
||||
FirstName string
|
||||
LastName string
|
||||
FullName string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module isp-admin-service
|
||||
|
||||
go 1.27
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
@@ -8,10 +8,11 @@ require (
|
||||
github.com/iancoleman/strcase v0.3.0
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/txix-open/bgjob v1.6.0
|
||||
github.com/txix-open/isp-kit v1.76.0
|
||||
github.com/txix-open/isp-kit v1.74.1
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/sync v0.25.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/sync v0.22.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -21,65 +22,61 @@ require (
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
|
||||
github.com/getsentry/sentry-go v0.50.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.12.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/getsentry/sentry-go v0.49.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.11.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.2 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.13.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
||||
github.com/jackc/pgx/v5 v5.10.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/julienschmidt/httprouter v1.3.0 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
github.com/mailru/easyjson v0.9.2 // indirect
|
||||
github.com/mfridman/interpolate v0.2.0 // indirect
|
||||
github.com/mfridman/interpolate v0.0.2 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pandatix/go-abnf v0.5.5 // indirect
|
||||
github.com/pressly/goose/v3 v3.30.1 // indirect
|
||||
github.com/prometheus/client_golang v1.25.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.74.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/pressly/goose/v3 v3.27.3 // indirect
|
||||
github.com/prometheus/client_golang v1.24.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // indirect
|
||||
github.com/txix-open/etp/v4 v4.1.3 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect
|
||||
go.opentelemetry.io/otel v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.46.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/net v0.63.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/grpc v1.85.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -19,18 +19,18 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
||||
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
||||
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
|
||||
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
|
||||
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
|
||||
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
@@ -38,13 +38,15 @@ github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
|
||||
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
|
||||
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
|
||||
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -52,26 +54,26 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -88,12 +90,12 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
|
||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
|
||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -103,35 +105,33 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
|
||||
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
|
||||
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
|
||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
|
||||
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
|
||||
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
@@ -153,12 +153,12 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
|
||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
||||
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
|
||||
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
@@ -170,56 +170,54 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
|
||||
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
@@ -230,11 +228,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
|
||||
modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
|
||||
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
|
||||
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
||||
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
@@ -12,18 +12,18 @@ import (
|
||||
|
||||
var version = "1.0.0"
|
||||
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
|
||||
// @license.name GNU GPL v3.0
|
||||
// @license.name GNU GPL v3.0
|
||||
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
// @host localhost:9000
|
||||
// @BasePath /api/admin
|
||||
|
||||
//go:generate swag init -pd -ot json -eot json
|
||||
func main() {
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
|
||||
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport)
|
||||
app := boot.App
|
||||
logger := app.Logger()
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE roles DROP COLUMN application_group;
|
||||
+4
-20
@@ -25,7 +25,6 @@ const (
|
||||
updatedAtRolesColumn = "updated_at"
|
||||
permissionsRolesColumn = "permissions"
|
||||
externalGroupRolesColumn = "external_group"
|
||||
applicationGroupColumn = "application_group"
|
||||
immutableRolesColumn = "immutable"
|
||||
exclusiveRolesColumn = "exclusive"
|
||||
)
|
||||
@@ -38,7 +37,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("id, name, external_group, application_group, permissions, created_at, updated_at").
|
||||
Select("id, name, external_group, permissions, created_at, updated_at").
|
||||
From("roles").
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
ToSql()
|
||||
@@ -68,7 +67,6 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -103,7 +101,6 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -125,7 +122,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
|
||||
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
||||
q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, q)
|
||||
if err != nil {
|
||||
@@ -134,24 +131,12 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter")
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, `
|
||||
select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at
|
||||
from roles where application_group=$1 order by created_at`, applicationGroup)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "select all roles")
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
|
||||
|
||||
q, args, err := query.New().Insert("roles").
|
||||
Columns("name", "permissions", "external_group", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
|
||||
Columns("name", "permissions", "external_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
@@ -173,7 +158,6 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
|
||||
Set("name", role.Name).
|
||||
Set("permissions", role.Permissions).
|
||||
Set("external_group", role.ExternalGroup).
|
||||
Set("application_group", role.ApplicationGroup).
|
||||
Where(squirrel.Eq{"id": role.Id}).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
|
||||
+102
-159
@@ -3,12 +3,12 @@ package routes
|
||||
import (
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/docs"
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/common_endpoints"
|
||||
httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
|
||||
"github.com/txix-open/isp-kit/http/router"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/grpc/endpoint"
|
||||
"github.com/txix-open/isp-kit/grpc/isp"
|
||||
)
|
||||
|
||||
type Controllers struct {
|
||||
@@ -21,7 +21,6 @@ type Controllers struct {
|
||||
Role controller.Role
|
||||
Permissions controller.Permissions
|
||||
UiSettings controller.UiSettings
|
||||
Download controller.Download
|
||||
}
|
||||
|
||||
func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
@@ -31,13 +30,13 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
|
||||
)
|
||||
}
|
||||
|
||||
func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
|
||||
muxer := router.New()
|
||||
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn
|
||||
muxer := grpc.NewMux()
|
||||
for _, descriptor := range endpointDescriptors(c) {
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
for _, descriptor := range commonEndpoints() {
|
||||
muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
|
||||
}
|
||||
return muxer
|
||||
}
|
||||
@@ -46,209 +45,153 @@ func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // no
|
||||
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
return []cluster.EndpointDescriptor{
|
||||
{
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/auth/login",
|
||||
Inner: false,
|
||||
Handler: c.Auth.Login,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/auth/logout",
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
Handler: c.User.GetProfile,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_design",
|
||||
Inner: true,
|
||||
Handler: c.Customization.GetUIDesign,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetUsers,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_all_users",
|
||||
Inner: true,
|
||||
Handler: c.User.GetAllUsers,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/create_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_create"),
|
||||
Handler: c.User.CreateUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/update_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_update"),
|
||||
Handler: c.User.UpdateUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/delete_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_delete"),
|
||||
Handler: c.User.DeleteUser,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/block_user",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("user_block"),
|
||||
Handler: c.User.Block,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_by_id",
|
||||
Inner: true,
|
||||
Handler: c.User.GetById,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/change_password",
|
||||
Inner: true,
|
||||
Handler: c.User.ChangePassword,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/role/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Role.All,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/user/get_permissions",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_view"),
|
||||
Handler: c.Permissions.GetPermissions,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/role/create",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_add"),
|
||||
Handler: c.Role.CreateRole,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/role/update",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_update"),
|
||||
Handler: c.Role.UpdateRole,
|
||||
},
|
||||
{
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/role/delete",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("role_delete"),
|
||||
Handler: c.Role.DeleteRole,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/session/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_view"),
|
||||
Handler: c.Session.All,
|
||||
},
|
||||
{
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/session/revoke",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("session_revoke"),
|
||||
Handler: c.Session.Revoke,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/log/all",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("security_log_view"),
|
||||
Handler: c.Audit.All,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/log/events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.Events,
|
||||
},
|
||||
{
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/log/set_events",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("audit_management_view"),
|
||||
Handler: c.Audit.SetEvents,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/secure/authenticate",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authenticate,
|
||||
},
|
||||
{
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/secure/authorize",
|
||||
Inner: true,
|
||||
Handler: c.Secure.Authorize,
|
||||
},
|
||||
{
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
// download
|
||||
{
|
||||
Path: "user/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Users,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "session/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Sessions,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "log/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Audit,
|
||||
HttpMethod: http.MethodPost,
|
||||
},
|
||||
{
|
||||
Path: "role/download",
|
||||
Inner: true,
|
||||
Extra: cluster.RequireAdminPermission("data_download"),
|
||||
Handler: c.Download.Roles,
|
||||
HttpMethod: http.MethodPost,
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,325 +0,0 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
requestLimit = 1000
|
||||
foundSymbol = "+"
|
||||
notFoundSymbol = "-"
|
||||
)
|
||||
|
||||
type Download struct {
|
||||
auditService Audit
|
||||
userService User
|
||||
tokenService Token
|
||||
roleService Role
|
||||
permissionService Permission
|
||||
loc *time.Location
|
||||
}
|
||||
|
||||
func NewDownload(
|
||||
auditService Audit,
|
||||
userService User,
|
||||
tokenService Token,
|
||||
roleService Role,
|
||||
permissionService Permission,
|
||||
) Download {
|
||||
loc, _ := time.LoadLocation("Europe/Moscow")
|
||||
return Download{
|
||||
auditService: auditService,
|
||||
userService: userService,
|
||||
tokenService: tokenService,
|
||||
roleService: roleService,
|
||||
permissionService: permissionService,
|
||||
loc: loc,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Download) DownloadAudit(ctx context.Context, req domain.AuditPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Audit")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.AuditColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write auditColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, audit := range response.Items {
|
||||
username := getUsername(userById, audit.UserId)
|
||||
|
||||
row := []string{username, s.formatTime(&audit.CreatedAt, false), audit.Message}
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write audit row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.auditService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get audit")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadSessions(ctx context.Context, req domain.SessionPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
response, err := s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
if response.TotalCount == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Sessions")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.SessionColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write sessionColumns to csv")
|
||||
}
|
||||
|
||||
userById, err := s.getUsersList(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users list")
|
||||
}
|
||||
|
||||
itemsCount := len(response.Items)
|
||||
for {
|
||||
for _, session := range response.Items {
|
||||
row := []string{
|
||||
getUsername(userById, session.UserId),
|
||||
strconv.Itoa(session.Id),
|
||||
s.formatTime(&session.CreatedAt, false),
|
||||
s.formatTime(&session.ExpiredAt, false),
|
||||
session.StatusRus()}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write session row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
if itemsCount >= response.TotalCount {
|
||||
break
|
||||
}
|
||||
|
||||
req.Offset += requestLimit
|
||||
response, err = s.tokenService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get sessions")
|
||||
}
|
||||
|
||||
itemsCount += len(response.Items)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadUsers(ctx context.Context, req domain.UsersPageRequest, w http.ResponseWriter) error {
|
||||
req.Limit = requestLimit
|
||||
req.Offset = 0
|
||||
|
||||
users, err := s.userService.GetUsers(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
roles, err := s.roleService.All(ctx, req.RoleAllRequest)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
if len(users.Items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Users")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, entity.UserColumnNames())
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write userColumns to csv")
|
||||
}
|
||||
|
||||
for _, user := range users.Items {
|
||||
row := []string{strconv.Itoa(int(user.Id)),
|
||||
user.FullName,
|
||||
user.Description,
|
||||
user.Email,
|
||||
getRoleNamesByIds(roles, user.Roles),
|
||||
s.formatTime(user.LastSessionCreatedAt, true)}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write user row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) DownloadRoles(ctx context.Context, req domain.RoleAllRequest, w http.ResponseWriter) error {
|
||||
roles, err := s.roleService.All(ctx, req)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
perms := s.permissionService.All(ctx)
|
||||
|
||||
if len(perms) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
columns := entity.RoleColumnNames()
|
||||
for _, role := range roles {
|
||||
columns = append(columns, role.Name)
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", getCsvFileName("Roles")))
|
||||
w.Header().Set("content-type", "application/octet-stream; charset=utf-8")
|
||||
w.Header().Set("transfer-encoding", "chunked")
|
||||
|
||||
csvWriter := csv.NewWriter(w)
|
||||
defer csvWriter.Flush()
|
||||
|
||||
err = writeCsvLine(csvWriter, columns)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role columns to csv")
|
||||
}
|
||||
|
||||
for _, perm := range perms {
|
||||
row := []string{perm.Name, perm.Key}
|
||||
|
||||
for _, role := range roles {
|
||||
if slices.Contains(role.Permissions, perm.Key) {
|
||||
row = append(row, foundSymbol)
|
||||
} else {
|
||||
row = append(row, notFoundSymbol)
|
||||
}
|
||||
}
|
||||
|
||||
err = writeCsvLine(csvWriter, row)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write role row to csv")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Download) getUsersList(ctx context.Context) (map[int]domain.User, error) {
|
||||
users, err := s.userService.GetAllUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get users")
|
||||
}
|
||||
|
||||
userById := make(map[int]domain.User)
|
||||
for _, user := range users.Items {
|
||||
userById[int(user.Id)] = user
|
||||
}
|
||||
|
||||
return userById, nil
|
||||
}
|
||||
|
||||
func getUsername(userById map[int]domain.User, userId int) string {
|
||||
user, ok := userById[userId]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
return user.FullName
|
||||
}
|
||||
|
||||
func getRoleNamesByIds(roles []domain.Role, roleIds []int) string {
|
||||
names := make([]string, 0)
|
||||
for _, role := range roles {
|
||||
if slices.Contains(roleIds, role.Id) {
|
||||
names = append(names, role.Name)
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(names, ", ")
|
||||
}
|
||||
|
||||
func writeCsvLine(csvWriter *csv.Writer, line []string) error {
|
||||
err := csvWriter.Write(line)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "write line to csv")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getCsvFileName(pageName string) string {
|
||||
return fmt.Sprintf("%s_%s.%s", pageName, time.Now().Format("02-01-2006_15:04:05"), "csv")
|
||||
}
|
||||
|
||||
func (s Download) formatTime(t *time.Time, onlyDate bool) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
if onlyDate {
|
||||
return t.In(s.loc).Format("02-01-2006")
|
||||
}
|
||||
|
||||
return t.In(s.loc).Format("02-01-2006 15:04:05")
|
||||
}
|
||||
@@ -11,12 +11,12 @@ type Permission struct {
|
||||
permissions []domain.Permission
|
||||
}
|
||||
|
||||
func NewPermission(permissions []conf.Permission) Permission {
|
||||
return Permission{
|
||||
func NewPermission(permissions []conf.Permission) *Permission {
|
||||
return &Permission{
|
||||
permissions: toDomain(permissions),
|
||||
}
|
||||
}
|
||||
func (s Permission) All(_ context.Context) []domain.Permission {
|
||||
func (s *Permission) All(_ context.Context) []domain.Permission {
|
||||
return s.permissions
|
||||
}
|
||||
|
||||
|
||||
+29
-46
@@ -13,7 +13,6 @@ import (
|
||||
|
||||
type roleRoleRepo interface {
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Delete(ctx context.Context, id int) error
|
||||
@@ -33,17 +32,8 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
|
||||
}
|
||||
}
|
||||
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
var (
|
||||
roles []entity.Role
|
||||
err error
|
||||
)
|
||||
switch {
|
||||
case req.ApplicationGroup != nil:
|
||||
roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup)
|
||||
default:
|
||||
roles, err = u.roleRepo.All(ctx)
|
||||
}
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
roles, err := u.roleRepo.All(ctx)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
@@ -68,10 +58,9 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
}
|
||||
|
||||
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -80,15 +69,13 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Группа приложений": "",
|
||||
"Разрешения": []int{},
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Разрешения": []int{},
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -119,11 +106,10 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
oldRole := roles[0]
|
||||
|
||||
role, err := u.roleRepo.Update(ctx, entity.Role{
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -133,15 +119,13 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
slices.Sort(oldRole.Permissions)
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Группа приложений": oldRole.ApplicationGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -164,14 +148,13 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
|
||||
|
||||
func (u Role) toDomain(role entity.Role) domain.Role {
|
||||
return domain.Role{
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
ApplicationGroup: role.ApplicationGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
}
|
||||
}
|
||||
+32
-30
@@ -1,7 +1,6 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -13,10 +12,13 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestAuditSuite(t *testing.T) {
|
||||
@@ -29,7 +31,7 @@ type AuditSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
}
|
||||
|
||||
func (s *AuditSuite) SetupTest() {
|
||||
@@ -73,20 +75,20 @@ func (s *AuditSuite) SetupTest() {
|
||||
s.Require().NoError(err)
|
||||
s.insertAuditLogs()
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_Events_DefaultEvents() {
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err := s.httpCli.
|
||||
Post("admin/log/events").
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]string{
|
||||
@@ -121,10 +123,10 @@ func (s *AuditSuite) Test_Events_SortEvents() {
|
||||
s.Require().NoError(err)
|
||||
|
||||
response := make([]domain.AuditEvent, 0)
|
||||
err = s.httpCli.
|
||||
Post("admin/log/events").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/log/events").
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedSort := []bool{
|
||||
@@ -137,13 +139,13 @@ func (s *AuditSuite) Test_Events_SortEvents() {
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
err := s.httpCli.
|
||||
Post("admin/log/set_events").
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: entity.EventRoleChanged, Enabled: false},
|
||||
}).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
expectedEventList := map[string]bool{
|
||||
@@ -167,24 +169,24 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||
err := s.httpCli.Post("admin/log/set_events").
|
||||
err := s.grpcCli.Invoke("admin/log/set_events").
|
||||
JsonRequestBody([]domain.SetAuditEvent{
|
||||
{Event: entity.EventUserChanged, Enabled: true},
|
||||
{Event: "новый#2", Enabled: false},
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
status, isStatus := status.FromError(err)
|
||||
s.Require().True(isStatus)
|
||||
s.Require().Equal(codes.InvalidArgument, status.Code())
|
||||
}
|
||||
|
||||
func (s *AuditSuite) Test_All_Logs() {
|
||||
request := domain.AuditPageRequest{
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
@@ -192,11 +194,11 @@ func (s *AuditSuite) Test_All_Logs() {
|
||||
}
|
||||
|
||||
var response *domain.AuditResponse
|
||||
err := s.httpCli.
|
||||
Post("admin/log/all").
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 3)
|
||||
@@ -210,11 +212,11 @@ func (s *AuditSuite) Test_All_Logs() {
|
||||
request.Limit = 10
|
||||
request.Offset = 0
|
||||
|
||||
err = s.httpCli.
|
||||
Post("admin/log/all").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/log/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 6)
|
||||
|
||||
+50
-57
@@ -18,15 +18,18 @@ import (
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/json"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestAuthTestSuite(t *testing.T) {
|
||||
@@ -39,7 +42,7 @@ type AuthTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
oauthCli *httpcli.Client
|
||||
oauthClientName string
|
||||
}
|
||||
@@ -78,11 +81,11 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
mocksrv.Close()
|
||||
})
|
||||
}
|
||||
@@ -96,13 +99,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.LoginResponse{}
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -112,18 +115,16 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a1@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -137,18 +138,16 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
||||
Blocked: true,
|
||||
})
|
||||
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -161,18 +160,16 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: "WrongPassword",
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
@@ -180,13 +177,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
user := entity.User{}
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
||||
@@ -202,19 +199,17 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.httpCli.Post("admin/auth/login_with_oauth").
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.oauthClientName + fake.It[string](),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
@@ -226,9 +221,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||
@@ -238,16 +233,18 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, "0143218411981").
|
||||
DoWithoutResponse(s.T().Context())
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981").
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
time.Sleep(time.Second)
|
||||
audit := repository.NewAudit(s.db)
|
||||
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
@@ -269,9 +266,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
CreatedAt: time.Time{},
|
||||
ExpiredAt: time.Time{},
|
||||
})
|
||||
err := s.httpCli.Post("admin/auth/logout").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
err := s.grpcCli.Invoke("admin/auth/logout").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||
@@ -295,24 +292,20 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
group.Go(func() error {
|
||||
start := time.Now()
|
||||
response := domain.LoginResponse{}
|
||||
err := s.httpCli.Post("admin/auth/login").
|
||||
err := s.grpcCli.Invoke("admin/auth/login").
|
||||
JsonRequestBody(domain.LoginRequest{
|
||||
Email: "a@a.ru",
|
||||
Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(ctx)
|
||||
Do(ctx)
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
|
||||
switch httpErr.StatusCode { // nolint:exhaustive
|
||||
case http.StatusTooManyRequests:
|
||||
switch status.Code(err) { // nolint:exhaustive
|
||||
case codes.ResourceExhausted:
|
||||
tooManyRequestsErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) < time.Second)
|
||||
case http.StatusUnauthorized:
|
||||
case codes.Unauthenticated:
|
||||
unauthorizedErrorCount.Add(1)
|
||||
s.Require().True(time.Since(start) > time.Second)
|
||||
default:
|
||||
|
||||
@@ -9,10 +9,10 @@ import (
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
)
|
||||
|
||||
func TestCustomizationTestSuite(t *testing.T) {
|
||||
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) SetupTest() {
|
||||
@@ -44,21 +44,21 @@ func (s *CustomizationTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *CustomizationTestSuite) TestGetDesign() {
|
||||
response := conf.UIDesign{}
|
||||
err := s.httpCli.
|
||||
Post("admin/user/get_design").
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_design").
|
||||
JsonRequestBody(struct{}{}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := conf.UIDesign{
|
||||
Name: "test",
|
||||
|
||||
@@ -42,13 +42,9 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
|
||||
}
|
||||
q, args, err := query.New().
|
||||
Insert("roles").
|
||||
Columns("name", "permissions", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ApplicationGroup).
|
||||
Suffix(`ON CONFLICT (name) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
permissions = EXCLUDED.permissions,
|
||||
application_group = EXCLUDED.application_group
|
||||
RETURNING id`).
|
||||
Columns("name", "permissions").
|
||||
Values(role.Name, role.Permissions).
|
||||
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
panic(errors.WithMessagef(err, "insert role"))
|
||||
|
||||
@@ -1,277 +0,0 @@
|
||||
// nolint: funlen
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestDownloadSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &DownloadSuite{})
|
||||
}
|
||||
|
||||
type DownloadSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
permissions entity.PermList
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
Permissions: []conf.Permission{
|
||||
{
|
||||
Key: "data_download",
|
||||
Name: "123",
|
||||
},
|
||||
},
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, cli := httpt.TestServer(s.test, cfg.Handler)
|
||||
s.httpCli = cli
|
||||
|
||||
s.permissions = entity.PermList{
|
||||
"data_download",
|
||||
}
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestUsersHappyPath() {
|
||||
id1 := InsertUser(s.db, entity.User{
|
||||
FirstName: "Alice",
|
||||
LastName: "Bob",
|
||||
FullName: "Bob Alice",
|
||||
Email: "alice@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(id1)})
|
||||
|
||||
resp, err := s.httpCli.Post("user/download").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["id"]
|
||||
s.Require().True(ok)
|
||||
emailIdx, ok := col["Email"]
|
||||
s.Require().True(ok)
|
||||
fullNameIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
|
||||
row := records[1]
|
||||
s.Require().EqualValues("3", row[idIdx])
|
||||
s.Require().EqualValues("alice@a.ru", row[emailIdx])
|
||||
s.Require().EqualValues("Bob Alice", row[fullNameIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestSessionsHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "sess1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_1",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-1 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_2",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
ExpiredAt: timeNow.Add(1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-2 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "test_token_3",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusExpired,
|
||||
ExpiredAt: timeNow.Add(-1 * time.Hour),
|
||||
CreatedAt: timeNow.Add(-3 * time.Hour),
|
||||
UpdatedAt: timeNow,
|
||||
})
|
||||
|
||||
resp, err := s.httpCli.Post("/session/download").
|
||||
JsonRequestBody(domain.SessionPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
defer resp.Raw.Body.Close()
|
||||
s.Require().Equal(http.StatusOK, resp.StatusCode())
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
userIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
idIdx, ok := col["Идентификатор"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 4)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[userIdx])
|
||||
s.Require().EqualValues("1", row[idIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestAuditHappyPath() {
|
||||
timeNow := time.Now().UTC()
|
||||
userId := InsertUser(s.db, entity.User{Email: "audit1@a.ru", FullName: "Bob Alice"})
|
||||
roleId := InsertRole(s.db, entity.Role{Name: "admin", Permissions: s.permissions})
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId), UserId: int(userId)})
|
||||
|
||||
auditRepo := repository.NewAudit(s.db)
|
||||
_, err := auditRepo.Insert(s.T().Context(), entity.Audit{
|
||||
Id: 1,
|
||||
UserId: int(userId),
|
||||
Message: "audit1@a.ru",
|
||||
Event: "123456",
|
||||
CreatedAt: timeNow,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
resp, err := s.httpCli.Post("log/download").
|
||||
JsonRequestBody(domain.AuditPageRequest{
|
||||
Limit: 1000,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
},
|
||||
}).
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
idIdx, ok := col["Пользователь"]
|
||||
s.Require().True(ok)
|
||||
moveIdx, ok := col["Действие"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 2)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("Bob Alice", row[idIdx])
|
||||
s.Require().EqualValues("audit1@a.ru", row[moveIdx])
|
||||
}
|
||||
|
||||
func (s *DownloadSuite) TestRolesHappyPath() {
|
||||
InsertRole(s.db, entity.Role{
|
||||
Name: "admin_1",
|
||||
ApplicationGroup: "123",
|
||||
Permissions: s.permissions,
|
||||
})
|
||||
InsertRole(s.db, entity.Role{
|
||||
Name: "admin_2",
|
||||
ApplicationGroup: "456",
|
||||
Permissions: s.permissions,
|
||||
})
|
||||
|
||||
applicationGroup := "123"
|
||||
resp, err := s.httpCli.Post("role/download").
|
||||
JsonRequestBody(domain.RoleAllRequest{
|
||||
ApplicationGroup: &applicationGroup,
|
||||
}).
|
||||
StatusCodeToError().
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
records, err := csv.NewReader(resp.Raw.Body).ReadAll()
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(records)
|
||||
|
||||
header := records[0]
|
||||
col := make(map[string]int, len(header))
|
||||
for i, name := range header {
|
||||
col[name] = i
|
||||
}
|
||||
|
||||
moveIdx, ok := col["Действие"]
|
||||
s.Require().True(ok)
|
||||
keyIdx, ok := col["Ключ в системе"]
|
||||
s.Require().True(ok)
|
||||
nameIdx, ok := col["admin_1"]
|
||||
s.Require().True(ok)
|
||||
|
||||
s.Require().Len(records, 2)
|
||||
row := records[1]
|
||||
s.Require().EqualValues("123", row[moveIdx])
|
||||
s.Require().EqualValues("data_download", row[keyIdx])
|
||||
s.Require().EqualValues("+", row[nameIdx])
|
||||
}
|
||||
@@ -49,8 +49,10 @@ func TestInactiveWorker(t *testing.T) {
|
||||
require.True(user.Blocked)
|
||||
|
||||
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
)
|
||||
|
||||
func TestRoleTestSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &RoleTestSuite{})
|
||||
}
|
||||
|
||||
type RoleTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
adminId int64
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.httpCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
})
|
||||
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "admin_test",
|
||||
Permissions: []string{
|
||||
"role_view",
|
||||
"role_add",
|
||||
"role_update",
|
||||
},
|
||||
})
|
||||
s.adminId = InsertUser(s.db, entity.User{
|
||||
Email: "admin@test.ru",
|
||||
})
|
||||
InsertUserRole(s.db, entity.UserRole{
|
||||
UserId: int(s.adminId),
|
||||
RoleId: int(roleId),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
||||
InsertRole(s.db, entity.Role{Name: "empty"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
groups := make(map[string]string, len(roles))
|
||||
for _, role := range roles {
|
||||
groups[role.Name] = role.ApplicationGroup
|
||||
}
|
||||
|
||||
s.Require().Empty(groups["empty"])
|
||||
s.Require().Equal("groupA", groups["groupA_1"])
|
||||
s.Require().Equal("groupA", groups["groupA_2"])
|
||||
s.Require().Equal("groupB", groups["groupB"])
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
|
||||
roles := []domain.Role{}
|
||||
statusCode, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
||||
|
||||
s.Require().Error(err)
|
||||
s.Require().Equal(http.StatusBadRequest, statusCode)
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
|
||||
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
_, err := s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(roles, 1)
|
||||
s.Require().Equal("groupA", roles[0].ApplicationGroup)
|
||||
|
||||
roles = []domain.Role{}
|
||||
_, err = s.request("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
|
||||
role := domain.Role{}
|
||||
_, err := s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group",
|
||||
Permissions: []string{},
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
|
||||
roleEmpty := domain.Role{}
|
||||
_, err = s.request("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_empty",
|
||||
Permissions: []string{},
|
||||
}, &roleEmpty)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group", role.ApplicationGroup)
|
||||
s.Require().Equal("role_empty", roleEmpty.Name)
|
||||
s.Require().Empty(roleEmpty.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "role_old",
|
||||
ApplicationGroup: "group_old",
|
||||
})
|
||||
|
||||
role := domain.Role{}
|
||||
_, err := s.request("admin/role/update", domain.UpdateRoleRequest{
|
||||
Id: int(roleId),
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group_new",
|
||||
Permissions: []string{},
|
||||
}, &role)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group_new", role.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) request(path string, req, resp any) (int, error) {
|
||||
err := s.httpCli.Post(path).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(resp).
|
||||
StatusCodeToError().
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
if err != nil {
|
||||
return http.StatusBadRequest, errors.WithMessagef(err, "request %s", path)
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
+20
-19
@@ -12,10 +12,11 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
)
|
||||
|
||||
func TestSecureSuite(t *testing.T) {
|
||||
@@ -29,7 +30,7 @@ type SecureSuite struct {
|
||||
test *test.Test
|
||||
require *require.Assertions
|
||||
db *dbt.TestDb
|
||||
httpCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
}
|
||||
|
||||
func (s *SecureSuite) SetupTest() {
|
||||
@@ -43,11 +44,11 @@ func (s *SecureSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := httpt.TestServer(s.test, cfg.Handler)
|
||||
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
|
||||
s.test.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
})
|
||||
s.httpCli = apiCli
|
||||
s.grpcCli = apiCli
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
@@ -60,12 +61,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "happy_path",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: true,
|
||||
@@ -84,12 +85,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "revoked",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -108,12 +109,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "expired",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -124,12 +125,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_NotFound() {
|
||||
result := domain.SecureAuthResponse{}
|
||||
err := s.httpCli.Post("admin/secure/authenticate").
|
||||
err := s.grpcCli.Invoke("admin/secure/authenticate").
|
||||
JsonRequestBody(domain.SecureAuthRequest{
|
||||
Token: "not_found",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.Equal(domain.SecureAuthResponse{
|
||||
Authenticated: false,
|
||||
@@ -164,35 +165,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
|
||||
})
|
||||
|
||||
result := domain.SecureAuthzResponse{}
|
||||
err := s.httpCli.Post("admin/secure/authorize").
|
||||
err := s.grpcCli.Invoke("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm1",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm2",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.True(result.Authorized)
|
||||
|
||||
result = domain.SecureAuthzResponse{}
|
||||
err = s.httpCli.Post("admin/secure/authorize").
|
||||
err = s.grpcCli.Invoke("admin/secure/authorize").
|
||||
JsonRequestBody(domain.SecureAuthzRequest{
|
||||
AdminId: int(userId),
|
||||
Permission: "perm3",
|
||||
}).
|
||||
JsonResponseBody(&result).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.require.NoError(err)
|
||||
s.require.False(result.Authorized)
|
||||
}
|
||||
+29
-24
@@ -14,10 +14,11 @@ import (
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
)
|
||||
|
||||
func TestSessionSuite(t *testing.T) {
|
||||
@@ -31,7 +32,7 @@ type SessionSuite struct {
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
config assembly.Config
|
||||
httpCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
}
|
||||
|
||||
func (s *SessionSuite) SetupTest() {
|
||||
@@ -76,11 +77,11 @@ func (s *SessionSuite) SetupTest() {
|
||||
|
||||
s.config = config
|
||||
|
||||
server, cli := httpt.TestServer(s.test, config.Handler)
|
||||
s.httpCli = cli
|
||||
server, apiCli := grpct.TestServer(testInstance, s.config.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -116,16 +117,18 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
|
||||
// Дефолт сортировка, лимит и оффсет
|
||||
request := domain.SessionPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
}
|
||||
|
||||
var response *domain.SessionResponse
|
||||
err := s.httpCli.
|
||||
Post("admin/session/all").
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -141,11 +144,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
To: timeNow.Add(24 * time.Hour),
|
||||
},
|
||||
}
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -160,11 +163,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Type: "asc",
|
||||
}
|
||||
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 3)
|
||||
@@ -180,11 +183,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Status: []string{entity.TokenStatusExpired},
|
||||
}
|
||||
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 1)
|
||||
@@ -205,8 +208,10 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
}
|
||||
|
||||
request = domain.SessionPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
@@ -215,11 +220,11 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
Id: new(2),
|
||||
},
|
||||
}
|
||||
err = s.httpCli.
|
||||
Post("admin/session/all").
|
||||
err = s.grpcCli.
|
||||
Invoke("admin/session/all").
|
||||
JsonRequestBody(request).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 5)
|
||||
|
||||
+13
-14
@@ -4,22 +4,23 @@ import (
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type UiSettingsSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
apiCli *httpcli.Client
|
||||
apiCli *client.Client
|
||||
oauthClientSetting conf.OauthClientConfig
|
||||
baseOauthUrl string
|
||||
}
|
||||
@@ -53,18 +54,18 @@ func (s *UiSettingsSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, 0)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
|
||||
_, s.apiCli = grpct.TestServer(s.test, cfg.Handler)
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
var resp domain.UiOauthSetting
|
||||
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName,
|
||||
}).
|
||||
JsonResponseBody(&resp).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
loginURL, err := url.Parse(resp.LoginUrl)
|
||||
@@ -92,15 +93,13 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
||||
err := s.apiCli.Post("admin/ui_settings/oauth").
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.Unauthenticated, st.Code())
|
||||
}
|
||||
+99
-107
@@ -2,12 +2,11 @@ package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
@@ -20,10 +19,13 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
@@ -40,7 +42,7 @@ type UserTestSuite struct {
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
apiCli *httpcli.Client
|
||||
grpcCli *client.Client
|
||||
httpCli *httpcli.Client
|
||||
tokenService tokenService
|
||||
}
|
||||
@@ -58,11 +60,11 @@ func (s *UserTestSuite) SetupTest() {
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
|
||||
s.apiCli = apiCli
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Close()
|
||||
server.Shutdown()
|
||||
})
|
||||
|
||||
tokenRep := repository.NewToken(s.db)
|
||||
@@ -88,10 +90,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
JsonResponseBody(&response).
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -115,14 +117,13 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
err := s.apiCli.Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
err := s.grpcCli.Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.NotFound, st.Code())
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
@@ -144,11 +145,11 @@ func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
})
|
||||
|
||||
response := domain.AdminUserShort{}
|
||||
err := s.apiCli.
|
||||
Post("admin/user/get_profile").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/get_profile").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.AdminUserShort{
|
||||
FirstName: "name",
|
||||
@@ -183,10 +184,12 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
email := "a1@"
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "email",
|
||||
Type: "asc",
|
||||
@@ -197,7 +200,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
roles := []int{int(roleId1), int(roleId2)}
|
||||
@@ -209,10 +212,12 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
s.Require().EqualValues(roles, response.Items[1].Roles)
|
||||
|
||||
email = "test@mail.ru"
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "asc",
|
||||
@@ -223,7 +228,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
s.Require().Empty(response.Items)
|
||||
}
|
||||
@@ -246,10 +251,7 @@ func (s *UserTestSuite) TestAllGetUsers() {
|
||||
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.apiCli.Post("admin/user/get_all_users").
|
||||
JsonResponseBody(&response).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 7)
|
||||
@@ -294,10 +296,12 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err = s.apiCli.Post("admin/user/get_users").
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "lastSessionCreatedAt",
|
||||
Type: "desc",
|
||||
@@ -310,7 +314,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 2)
|
||||
@@ -328,10 +332,12 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.apiCli.Post("admin/user/get_users").
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Order: &domain.OrderParams{
|
||||
Field: "userId",
|
||||
Type: "asc",
|
||||
@@ -341,7 +347,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
},
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Len(response.Items, 4)
|
||||
@@ -358,9 +364,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -368,7 +374,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -386,9 +392,9 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -396,7 +402,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
@@ -409,22 +415,20 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
|
||||
err := s.apiCli.
|
||||
Post("admin/user/create_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "exists@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
@@ -436,11 +440,12 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
Email: "update@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -462,11 +467,12 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
||||
Email: "oauth@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
expected := domain.UpdateUserRequest{
|
||||
Id: response.Id,
|
||||
@@ -489,16 +495,15 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
@@ -513,16 +518,15 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.httpCli.Post("admin/user/update_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
@@ -532,12 +536,12 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.apiCli.
|
||||
Post("admin/user/delete_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/delete_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
|
||||
JsonResponseBody(&response).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(2, response.Deleted)
|
||||
@@ -563,11 +567,10 @@ func (s *UserTestSuite) TestBlockUser() {
|
||||
UpdatedAt: time.Now(),
|
||||
})
|
||||
|
||||
err := s.apiCli.Post("admin/user/block_user").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
StatusCodeToError().
|
||||
err := s.grpcCli.Invoke("admin/user/block_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
|
||||
JsonRequestBody(domain.IdRequest{UserId: int(id)}).
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
|
||||
@@ -595,31 +598,20 @@ func (s *UserTestSuite) TestChangePasswordUser() {
|
||||
|
||||
// check for err when invalid data
|
||||
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
|
||||
err := s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err := s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(invalidReq).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
var httpErr httpcli.ErrorResponse
|
||||
s.Require().ErrorAs(err, &httpErr)
|
||||
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
|
||||
|
||||
var body struct {
|
||||
ErrorCode int `json:"errorCode"`
|
||||
ErrorMessage string `json:"errorMessage"`
|
||||
}
|
||||
s.Require().NoError(json.Unmarshal(httpErr.Body, &body))
|
||||
s.Require().Equal(domain.ErrCodeInvalidPassword, body.ErrorCode)
|
||||
err = apierrors.FromError(err)
|
||||
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword))
|
||||
|
||||
// change password
|
||||
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
|
||||
err = s.apiCli.Post("admin/user/change_password").
|
||||
Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
err = s.grpcCli.Invoke("admin/user/change_password").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
|
||||
JsonRequestBody(changePswReq).
|
||||
StatusCodeToError().
|
||||
DoWithoutResponse(s.T().Context())
|
||||
Do(s.T().Context())
|
||||
|
||||
s.Require().NoError(err)
|
||||
|
||||
|
||||
-3
@@ -13,9 +13,6 @@
|
||||
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype">
|
||||
<img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
|
||||
</a>
|
||||
<a href="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml">
|
||||
<img alt="Tests" src="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml/badge.svg">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/gabriel-vasile/mimetype">
|
||||
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
|
||||
</a>
|
||||
|
||||
+29
-142
@@ -46,14 +46,12 @@ type cdf struct {
|
||||
satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input
|
||||
satEntries int // number of valid SAT entries reachable through satSecs
|
||||
firstSSAT int32
|
||||
ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain
|
||||
dirRaw []byte // directory stream bytes (entries are decoded on demand)
|
||||
sst []byte // short-stream pool (root storage's stream)
|
||||
sstBuilt bool // whether sst was already loaded (it is loaded lazily)
|
||||
rootStreamFirst int32 // first sector of the root storage short-stream pool
|
||||
rootStreamSize uint32 // size of the root storage short-stream pool
|
||||
rootChild int32 // directory id of the root storage's child tree
|
||||
rootStorageUUID [16]byte
|
||||
rootStorageUUID []byte
|
||||
}
|
||||
|
||||
// parse reads the entire on-disk structure required for type detection. It
|
||||
@@ -83,108 +81,35 @@ func parse(raw []byte, c *cdf) bool {
|
||||
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
|
||||
|
||||
c.buildSAT(masterSAT, firstMSAT, nMSAT)
|
||||
c.buildSSAT()
|
||||
c.dirRaw = c.readLong(firstDirSec, 0)
|
||||
|
||||
c.rootStreamFirst = -1
|
||||
c.rootChild = -1
|
||||
var d dirEntry
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
c.dirAt(i, &d)
|
||||
if d.typ != dirTypeRootStorage {
|
||||
if d.typ != dirTypeRootStorage || d.streamFirst < 0 {
|
||||
continue
|
||||
}
|
||||
copy(c.rootStorageUUID[:], d.storageUUID[:])
|
||||
c.rootChild = d.child
|
||||
c.rootStorageUUID = d.storageUUID[:]
|
||||
// Record where the short-stream pool lives; it is loaded lazily by
|
||||
// shortStream the first time a short stream is actually read.
|
||||
if d.streamFirst >= 0 {
|
||||
c.rootStreamFirst = d.streamFirst
|
||||
c.rootStreamSize = d.size
|
||||
}
|
||||
c.rootStreamFirst = d.streamFirst
|
||||
c.rootStreamSize = d.size
|
||||
break
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// rootChildIter iterates over the directory entries that are direct children
|
||||
// of the root storage, walking the red-black sibling tree hanging off the root
|
||||
// entry's child pointer. Restricting detection to root-level entries matters:
|
||||
// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry
|
||||
// their own SummaryInformation streams deeper in the hierarchy, and a flat
|
||||
// directory scan can pick those up instead of the document's own.
|
||||
// If the tree is unusable (no valid root child) iteration degrades to a flat
|
||||
// scan of all entries so truncated or malformed files still get best-effort
|
||||
// detection. The iterator lives entirely on the caller's stack: it allocates
|
||||
// nothing and decodes each visited entry into its inline d field.
|
||||
type rootChildIter struct {
|
||||
c *cdf
|
||||
d dirEntry // entry decoded by the latest successful next call
|
||||
n int // total directory entries
|
||||
i int // next index for the flat fallback scan
|
||||
flat bool // no usable tree; scan all entries instead
|
||||
visited int // entries visited so far; guards against cyclic trees
|
||||
sp int // number of ids on stack
|
||||
stack [64]int32
|
||||
}
|
||||
|
||||
// rootChildren returns an iterator over the root storage's direct children.
|
||||
// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... }
|
||||
func (c *cdf) rootChildren() rootChildIter {
|
||||
it := rootChildIter{c: c, n: c.dirLen()}
|
||||
if c.rootChild >= 0 && int(c.rootChild) < it.n {
|
||||
it.stack[0] = c.rootChild
|
||||
it.sp = 1
|
||||
} else {
|
||||
it.flat = true
|
||||
}
|
||||
return it
|
||||
}
|
||||
|
||||
// next advances to the next entry, decoding it into it.d. It reports false
|
||||
// when iteration is done.
|
||||
func (it *rootChildIter) next() bool {
|
||||
if it.flat {
|
||||
if it.i >= it.n {
|
||||
return false
|
||||
}
|
||||
it.c.dirAt(it.i, &it.d)
|
||||
it.i++
|
||||
return true
|
||||
}
|
||||
for it.sp > 0 {
|
||||
it.sp--
|
||||
id := it.stack[it.sp]
|
||||
if id < 0 || int(id) >= it.n {
|
||||
continue
|
||||
}
|
||||
if it.visited++; it.visited > it.n {
|
||||
return false // cyclic sibling pointers in a malformed directory
|
||||
}
|
||||
it.c.dirAt(int(id), &it.d)
|
||||
// Push the siblings. A valid red-black tree of n entries is at most
|
||||
// 2*log2(n) deep, so the fixed-size stack cannot overflow for any
|
||||
// real directory; if a malformed tree overflows it, the excess
|
||||
// branches are dropped and detection degrades gracefully.
|
||||
for _, sib := range [2]int32{it.d.left, it.d.right} {
|
||||
if sib >= 0 && it.sp < len(it.stack) {
|
||||
it.stack[it.sp] = sib
|
||||
it.sp++
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *cdf) detect() CDFType {
|
||||
for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} {
|
||||
if t, ok := c.detectFromSummary(name); ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok {
|
||||
var d dirEntry
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
c.dirAt(i, &d)
|
||||
if t, ok := lookupSection(d.nameBytes(), d.typ); ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
@@ -195,7 +120,7 @@ func (c *cdf) detect() CDFType {
|
||||
// derive a CDFType from the root-storage CLSID, the property NameOfApplication,
|
||||
// and finally the names of sibling user streams.
|
||||
func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
|
||||
if bytes.Equal(c.rootStorageUUID[:], msiCLSID) {
|
||||
if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) {
|
||||
return CDFTypeInstaller, true
|
||||
}
|
||||
raw, ok := c.userStream(streamName)
|
||||
@@ -207,11 +132,13 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if it.d.nameLen == 0 {
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
var d dirEntry
|
||||
c.dirAt(i, &d)
|
||||
if d.nameLen == 0 {
|
||||
continue
|
||||
}
|
||||
if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok {
|
||||
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
@@ -237,9 +164,6 @@ type dirEntry struct {
|
||||
name [32]byte
|
||||
nameLen uint8
|
||||
typ uint8
|
||||
left int32 // left sibling directory id
|
||||
right int32 // right sibling directory id
|
||||
child int32 // first child directory id (for storages)
|
||||
streamFirst int32
|
||||
size uint32
|
||||
storageUUID [16]byte
|
||||
@@ -248,56 +172,23 @@ type dirEntry struct {
|
||||
// nameBytes returns the decoded ASCII name without copying.
|
||||
func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] }
|
||||
|
||||
// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain
|
||||
// through the SAT once. The SSAT contents are not materialized; ssatAt computes
|
||||
// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt.
|
||||
// The walk is bounded by the number of sectors in the file so a cyclic SAT
|
||||
// (a self-looping sector) cannot spin forever.
|
||||
func (c *cdf) buildSSAT() {
|
||||
maxIDs := len(c.data)/c.secSize + 1
|
||||
buf := make([]byte, 0, 4*8)
|
||||
var tmp [4]byte
|
||||
func (c *cdf) ssatAt(i int32) int32 {
|
||||
for sid := c.firstSSAT; sid >= 0; {
|
||||
if int(sid) >= c.satLen() {
|
||||
break // SAT is truncated; stop collecting
|
||||
}
|
||||
if _, ok := c.sector(sid); !ok {
|
||||
buf, ok := c.sector(sid)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id
|
||||
buf = append(buf, tmp[:]...)
|
||||
if len(buf)/4 > maxIDs {
|
||||
break // cyclic SAT chain; stop allocating
|
||||
lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32
|
||||
if i < lbuf {
|
||||
return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id
|
||||
}
|
||||
i -= lbuf
|
||||
sid = c.satAt(sid)
|
||||
}
|
||||
c.ssatSecs = int32s{b: buf}
|
||||
}
|
||||
|
||||
// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly
|
||||
// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns
|
||||
// -1 when i is past the end of the SSAT or the backing sector is truncated.
|
||||
func (c *cdf) ssatAt(i int32) int32 {
|
||||
if i < 0 {
|
||||
return -1
|
||||
}
|
||||
perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two
|
||||
secIdx := int(i / perSec)
|
||||
if secIdx >= c.ssatSecs.len() {
|
||||
return -1
|
||||
}
|
||||
sid := c.ssatSecs.at(secIdx)
|
||||
buf, ok := c.sector(sid)
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
entryIdx := i % perSec
|
||||
//nolint:gosec // anything divided by 4 fits int32
|
||||
if entryIdx >= int32(len(buf)/4) {
|
||||
return -1 // sector truncated short of this entry
|
||||
}
|
||||
//nolint:gosec // intentional two's-complement reinterpretation of a sector id
|
||||
return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:]))
|
||||
return -1
|
||||
}
|
||||
|
||||
// shortStream returns the root storage short-stream pool, loading it on first
|
||||
@@ -544,9 +435,6 @@ func (c *cdf) readShort(sid int32, length uint32) []byte {
|
||||
}
|
||||
off := int(off64)
|
||||
out = append(out, sst[off:off+c.shortSecSize]...)
|
||||
if length > 0 && int64(len(out)) >= int64(length) {
|
||||
break // read enough to satisfy the stream's declared length
|
||||
}
|
||||
if len(out) >= len(sst) {
|
||||
break // chain longer than the pool: cyclic SSAT, stop
|
||||
}
|
||||
@@ -588,19 +476,18 @@ func (c *cdf) dirAt(i int, out *dirEntry) {
|
||||
}
|
||||
out.nameLen = k
|
||||
out.typ = raw[66]
|
||||
out.left = readSecID(raw[68:72])
|
||||
out.right = readSecID(raw[72:76])
|
||||
out.child = readSecID(raw[76:80])
|
||||
out.streamFirst = readSecID(raw[116:120])
|
||||
out.size = binary.LittleEndian.Uint32(raw[120:])
|
||||
copy(out.storageUUID[:], raw[80:96])
|
||||
}
|
||||
|
||||
// userStream finds a root-level user stream by name and returns its bytes.
|
||||
// userStream finds a user stream by name and returns its bytes.
|
||||
func (c *cdf) userStream(name string) ([]byte, bool) {
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name {
|
||||
buf := c.readChain(it.d.streamFirst, it.d.size)
|
||||
var d dirEntry
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
c.dirAt(i, &d)
|
||||
if d.typ == dirTypeUserStream && string(d.nameBytes()) == name {
|
||||
buf := c.readChain(d.streamFirst, d.size)
|
||||
if buf == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
+12
-15
@@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool {
|
||||
|
||||
// AAC matches an Advanced Audio Coding file.
|
||||
func AAC(raw []byte, _ uint32) bool {
|
||||
return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9)
|
||||
return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9))
|
||||
}
|
||||
|
||||
// MP3 matches a .mp3 file.
|
||||
@@ -128,30 +128,27 @@ func id3v2(raw []byte) bool {
|
||||
}
|
||||
|
||||
size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9])
|
||||
// The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB
|
||||
// cap rejected legitimate files with large ID3v2 album art. #839
|
||||
return size > 0
|
||||
}
|
||||
|
||||
// iff checks for an Interchange File Format layout: 4-byte container tag,
|
||||
// 4-byte size, 4-byte format tag.
|
||||
func iff(raw []byte, container, format []byte) bool {
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[:4], container) &&
|
||||
bytes.Equal(raw[8:12], format)
|
||||
// Disallow too big frames, let's say 10MB.
|
||||
return size > 0 && size < 10*1024*1024
|
||||
}
|
||||
|
||||
// Wav matches a Waveform Audio File Format file.
|
||||
func Wav(raw []byte, limit uint32) bool {
|
||||
return iff(raw, []byte("RIFF"), []byte("WAVE"))
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[:4], []byte("RIFF")) &&
|
||||
bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45})
|
||||
}
|
||||
|
||||
// Aiff matches Audio Interchange File Format file.
|
||||
func Aiff(raw []byte, limit uint32) bool {
|
||||
return iff(raw, []byte("FORM"), []byte("AIFF"))
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) &&
|
||||
bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46})
|
||||
}
|
||||
|
||||
// Qcp matches a Qualcomm Pure Voice file.
|
||||
func Qcp(raw []byte, limit uint32) bool {
|
||||
return iff(raw, []byte("RIFF"), []byte("QLCM"))
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[:4], []byte("RIFF")) &&
|
||||
bytes.Equal(raw[8:12], []byte("QLCM"))
|
||||
}
|
||||
+16
-9
@@ -121,22 +121,29 @@ func Dbf(raw []byte, limit uint32) bool {
|
||||
return slices.Contains(dbfTypes, raw[0])
|
||||
}
|
||||
|
||||
func elfType(raw []byte, t byte) bool {
|
||||
return len(raw) > 17 &&
|
||||
((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t))
|
||||
// ElfObj matches an object file.
|
||||
func ElfObj(raw []byte, limit uint32) bool {
|
||||
return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) ||
|
||||
(raw[16] == 0x00 && raw[17] == 0x01))
|
||||
}
|
||||
|
||||
// ElfObj matches an object file.
|
||||
func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 0x01) }
|
||||
|
||||
// ElfExe matches an executable file.
|
||||
func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) }
|
||||
func ElfExe(raw []byte, limit uint32) bool {
|
||||
return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) ||
|
||||
(raw[16] == 0x00 && raw[17] == 0x02))
|
||||
}
|
||||
|
||||
// ElfLib matches a shared library file.
|
||||
func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) }
|
||||
func ElfLib(raw []byte, limit uint32) bool {
|
||||
return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) ||
|
||||
(raw[16] == 0x00 && raw[17] == 0x03))
|
||||
}
|
||||
|
||||
// ElfDump matches a core dump file.
|
||||
func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) }
|
||||
func ElfDump(raw []byte, limit uint32) bool {
|
||||
return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) ||
|
||||
(raw[16] == 0x00 && raw[17] == 0x04))
|
||||
}
|
||||
|
||||
// Dcm matches a DICOM medical format file.
|
||||
func Dcm(raw []byte, limit uint32) bool {
|
||||
|
||||
+3
-1
@@ -178,7 +178,9 @@ func jpeg2k(raw []byte, sig []byte) bool {
|
||||
|
||||
// Webp matches a WebP file.
|
||||
func Webp(raw []byte, _ uint32) bool {
|
||||
return iff(raw, []byte("RIFF"), []byte("WEBP"))
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[0:4], []byte("RIFF")) &&
|
||||
bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50})
|
||||
}
|
||||
|
||||
// Dwg matches a CAD drawing file.
|
||||
|
||||
+13
-1
@@ -101,13 +101,25 @@ func markup(b scan.Bytes, sigs ...[]byte) bool {
|
||||
return false
|
||||
}
|
||||
func markupCheck(sig, raw []byte) bool {
|
||||
if !ciCheck(sig, raw) {
|
||||
if len(raw) < len(sig)+1 {
|
||||
return false
|
||||
}
|
||||
|
||||
// perform case insensitive check
|
||||
for i, b := range sig {
|
||||
db := raw[i]
|
||||
if 'A' <= b && b <= 'Z' {
|
||||
db &= 0xDF
|
||||
}
|
||||
if b != db {
|
||||
return false
|
||||
}
|
||||
}
|
||||
// Next byte must be space or right angle bracket.
|
||||
if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+59
-31
@@ -46,16 +46,26 @@ func Ole(raw []byte, limit uint32) bool {
|
||||
return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1})
|
||||
}
|
||||
|
||||
// cdfOrClsid checks if the raw input is detected as the given CDF type, and if
|
||||
// the CDF parser returns a generic result, falls back to matching root storage CLSIDs.
|
||||
func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
|
||||
// Doc matches a Microsoft Word 97-2003 file.
|
||||
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
|
||||
func Doc(raw []byte, _ uint32) bool {
|
||||
fromParsing := cdf.Detect(raw)
|
||||
if fromParsing == want {
|
||||
if fromParsing == cdf.CDFTypeDoc {
|
||||
return true
|
||||
}
|
||||
if fromParsing != cdf.CDFTypeGeneric {
|
||||
return false
|
||||
}
|
||||
// Fallback for inputs where the CDF directory is past the read limit: match
|
||||
// the root storage CLSID, which often lies within the first sectors.
|
||||
clsids := [][]byte{
|
||||
// Microsoft Word 97-2003 Document (Word.Document.8)
|
||||
{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
|
||||
{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
// Microsoft Word Picture (Word.Picture.8)
|
||||
{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
}
|
||||
for _, clsid := range clsids {
|
||||
if matchOleClsid(raw, clsid) {
|
||||
return true
|
||||
@@ -64,27 +74,25 @@ func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// Doc matches a Microsoft Word 97-2003 file.
|
||||
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py
|
||||
func Doc(raw []byte, _ uint32) bool {
|
||||
return cdfOrClsid(raw, cdf.CDFTypeDoc,
|
||||
// Microsoft Word 97-2003 Document (Word.Document.8)
|
||||
[]byte{0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
// Microsoft Word 6.0-7.0 Document (Word.Document.6)
|
||||
[]byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
// Microsoft Word Picture (Word.Picture.8)
|
||||
[]byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
)
|
||||
}
|
||||
|
||||
// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation.
|
||||
func Ppt(raw []byte, limit uint32) bool {
|
||||
if cdfOrClsid(raw, cdf.CDFTypePpt,
|
||||
[]byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
|
||||
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8},
|
||||
[]byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
|
||||
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3},
|
||||
) {
|
||||
fromParsing := cdf.Detect(raw)
|
||||
if fromParsing == cdf.CDFTypePpt {
|
||||
return true
|
||||
}
|
||||
if fromParsing != cdf.CDFTypeGeneric {
|
||||
return false
|
||||
}
|
||||
// Fallback for inputs where the CDF directory is past the read limit.
|
||||
// Root CLSID test is the safest way to identify the OLE, however, the format
|
||||
// often places the root CLSID at the end of the file.
|
||||
if matchOleClsid(raw, []byte{
|
||||
0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
|
||||
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8,
|
||||
}) || matchOleClsid(raw, []byte{
|
||||
0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
|
||||
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3,
|
||||
}) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -109,10 +117,21 @@ func Ppt(raw []byte, limit uint32) bool {
|
||||
|
||||
// Xls matches a Microsoft Excel 97-2003 file.
|
||||
func Xls(raw []byte, limit uint32) bool {
|
||||
if cdfOrClsid(raw, cdf.CDFTypeXls,
|
||||
[]byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
|
||||
[]byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
|
||||
) {
|
||||
fromParsing := cdf.Detect(raw)
|
||||
if fromParsing == cdf.CDFTypeXls {
|
||||
return true
|
||||
}
|
||||
if fromParsing != cdf.CDFTypeGeneric {
|
||||
return false
|
||||
}
|
||||
// Fallback for inputs where the CDF directory is past the read limit.
|
||||
// Root CLSID test is the safest way to identify the OLE, however, the format
|
||||
// often places the root CLSID at the end of the file.
|
||||
if matchOleClsid(raw, []byte{
|
||||
0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
}) || matchOleClsid(raw, []byte{
|
||||
0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
}) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -149,10 +168,19 @@ func Pub(raw []byte, limit uint32) bool {
|
||||
|
||||
// Msg matches a Microsoft Outlook email file.
|
||||
func Msg(raw []byte, limit uint32) bool {
|
||||
return cdfOrClsid(raw, cdf.CDFTypeMsg,
|
||||
[]byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
)
|
||||
fromParsing := cdf.Detect(raw)
|
||||
if fromParsing == cdf.CDFTypeMsg {
|
||||
return true
|
||||
}
|
||||
if fromParsing != cdf.CDFTypeGeneric {
|
||||
return false
|
||||
}
|
||||
// Fallback for inputs where the CDF directory does not carry the streams the
|
||||
// parser keys on: match the root storage CLSID instead.
|
||||
return matchOleClsid(raw, []byte{
|
||||
0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46,
|
||||
})
|
||||
}
|
||||
|
||||
// Msi matches a Microsoft Windows Installer file.
|
||||
|
||||
-3
@@ -15,9 +15,6 @@ targets:
|
||||
- name: github
|
||||
tagPrefix: otel/otlp/v
|
||||
tagOnly: true
|
||||
- name: github
|
||||
tagPrefix: cron/v
|
||||
tagOnly: true
|
||||
- name: github
|
||||
tagPrefix: echo/v
|
||||
tagOnly: true
|
||||
|
||||
-35
@@ -1,40 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## 0.50.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
- adds NoopClient implementation. The SDK now returns a non-nil noop client and handles the previous nil checks with checking for a disabled client. Code paths that were using nil checks now need to check for `client.IsEnabled`. by @giortzisg in [#1365](https://github.com/getsentry/sentry-go/pull/1365)
|
||||
|
||||
### New Features ✨
|
||||
|
||||
#### Crons
|
||||
|
||||
- Add `sentry.WithMonitor` and `Hub.WithMonitor` to wrap a job in cron check-ins and create or update the monitor from code. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
- Add `sentrycron.AddFunc` to report robfig/cron jobs to Sentry Crons, using the job's spec as the monitor schedule. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
- Docs: https://github.com/getsentry/sentry-docs/pull/19778 by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
|
||||
### Bug Fixes 🐛
|
||||
|
||||
- (dsn) Build envelope URL without re-parsing by @giortzisg in [#1436](https://github.com/getsentry/sentry-go/pull/1436)
|
||||
- (httpclient) Decouple span creation from trace propagation by @giortzisg in [#1421](https://github.com/getsentry/sentry-go/pull/1421)
|
||||
- (slog) Stop replaceAttrs from mutating the handler's grouped attrs by @breken-ai in [#1439](https://github.com/getsentry/sentry-go/pull/1439)
|
||||
- (zerolog) Unescape JSON string values before sending to Sentry by @breken-ai in [#1440](https://github.com/getsentry/sentry-go/pull/1440)
|
||||
- Guard concurrent flushes by @giortzisg in [#1449](https://github.com/getsentry/sentry-go/pull/1449)
|
||||
- Keep http.Hijacker when wrapping a response writer by @knQzx in [#1387](https://github.com/getsentry/sentry-go/pull/1387)
|
||||
|
||||
### Internal Changes 🔧
|
||||
|
||||
#### Deps
|
||||
|
||||
- Bump getsentry/craft from 2.30.1 to 2.31.2 by @dependabot in [#1441](https://github.com/getsentry/sentry-go/pull/1441)
|
||||
- Bump getsentry/github-workflows/validate-pr from 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 to 36c729264d2edc29ebae61950c50e1e9f043ad7e by @dependabot in [#1442](https://github.com/getsentry/sentry-go/pull/1442)
|
||||
- Bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.43.0 to 1.45.0 in /otel/otlp by @dependabot in [#1430](https://github.com/getsentry/sentry-go/pull/1430)
|
||||
- Bump go.opentelemetry.io/otel/sdk from 1.44.0 to 1.45.0 by @dependabot in [#1431](https://github.com/getsentry/sentry-go/pull/1431)
|
||||
- Bump google.golang.org/grpc from 1.83.1 to 1.83.2 by @dependabot in [#1422](https://github.com/getsentry/sentry-go/pull/1422)
|
||||
- Bump getsentry/craft from 2.27.2 to 2.30.1 by @dependabot in [#1411](https://github.com/getsentry/sentry-go/pull/1411)
|
||||
- Bump google.golang.org/grpc from 1.82.1 to 1.83.1 by @dependabot in [#1413](https://github.com/getsentry/sentry-go/pull/1413)
|
||||
|
||||
## 0.49.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
+4
-6
@@ -305,8 +305,6 @@ func (t Type) String() string {
|
||||
return "invalid"
|
||||
}
|
||||
|
||||
const arrayType = "array"
|
||||
|
||||
// mapTypesToStr is a map from attribute.Type to the primitive types the server understands.
|
||||
// https://develop.sentry.dev/sdk/foundations/data-model/attributes/#primitive-types
|
||||
var mapTypesToStr = map[Type]string{
|
||||
@@ -315,9 +313,9 @@ var mapTypesToStr = map[Type]string{
|
||||
INT64: "integer",
|
||||
FLOAT64: "double",
|
||||
STRING: "string",
|
||||
BOOLSLICE: arrayType,
|
||||
INT64SLICE: arrayType,
|
||||
FLOAT64SLICE: arrayType,
|
||||
STRINGSLICE: arrayType,
|
||||
BOOLSLICE: "array",
|
||||
INT64SLICE: "array",
|
||||
FLOAT64SLICE: "array",
|
||||
STRINGSLICE: "array",
|
||||
UINT64: "integer", // wire format: same "integer" type
|
||||
}
|
||||
+9
-85
@@ -133,8 +133,8 @@ type ClientOptions struct {
|
||||
// The DSN to use. If the DSN is not set, the client is effectively
|
||||
// disabled.
|
||||
Dsn string
|
||||
// In debug mode, diagnostic information is written to DebugWriter, which
|
||||
// defaults to stderr.
|
||||
// In debug mode, the debug information is printed to stdout to help you
|
||||
// understand what sentry is doing.
|
||||
Debug bool
|
||||
// Configures whether SDK should generate and attach stacktraces to pure
|
||||
// capture message calls.
|
||||
@@ -298,7 +298,6 @@ type ClientOptions struct {
|
||||
// instances. It must be created with NewClient.
|
||||
type Client struct {
|
||||
mu sync.RWMutex
|
||||
disabled bool
|
||||
options ClientOptions
|
||||
dsn *protocol.Dsn
|
||||
eventProcessors []EventProcessor
|
||||
@@ -451,45 +450,6 @@ func NewClient(options ClientOptions) (*Client, error) {
|
||||
return &client, nil
|
||||
}
|
||||
|
||||
var noopClient = &Client{
|
||||
disabled: true,
|
||||
options: ClientOptions{
|
||||
DisableTelemetryBuffer: true,
|
||||
MaxErrorDepth: maxErrorDepth,
|
||||
MaxSpans: defaultMaxSpans,
|
||||
TraceIgnoreStatusCodes: [][]int{{404}},
|
||||
},
|
||||
sdkIdentifier: sdkIdentifier,
|
||||
sdkVersion: SDKVersion,
|
||||
Transport: new(noopTransport),
|
||||
reportRecorder: report.NoopRecorder(),
|
||||
reportProvider: report.NoopProvider(),
|
||||
}
|
||||
|
||||
// NewNoopClient returns the shared client that safely discards telemetry.
|
||||
// Its mutating methods have no effect.
|
||||
func NewNoopClient() *Client {
|
||||
return noopClient
|
||||
}
|
||||
|
||||
// IsEnabled reports whether the client processes captured telemetry.
|
||||
//
|
||||
// It returns false for a nil receiver and for clients returned by
|
||||
// NewNoopClient. A client can be enabled while using a transport that discards
|
||||
// telemetry, such as a client configured with an empty DSN.
|
||||
func (client *Client) IsEnabled() bool {
|
||||
return client != nil && !client.disabled
|
||||
}
|
||||
|
||||
// normalizeClient returns client, or the shared no-op client when client is
|
||||
// nil.
|
||||
func normalizeClient(client *Client) *Client {
|
||||
if client == nil {
|
||||
return noopClient
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func (client *Client) setupTransport() {
|
||||
opts := client.options
|
||||
transport := opts.Transport
|
||||
@@ -595,9 +555,6 @@ func (client *Client) setupIntegrations() {
|
||||
// client is shared among multiple hubs, one per goroutine, such that adding an
|
||||
// event processor to the client affects all hubs that share the client.
|
||||
func (client *Client) AddEventProcessor(processor EventProcessor) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.eventProcessors = append(client.eventProcessors, processor)
|
||||
}
|
||||
|
||||
@@ -606,9 +563,6 @@ func (client *Client) AddEventProcessor(processor EventProcessor) {
|
||||
//
|
||||
// This is intended for integrations such as OpenTelemetry.
|
||||
func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
@@ -642,7 +596,7 @@ func (client *Client) Options() ClientOptions {
|
||||
// GetDataCollection returns a copy of the resolved data collection
|
||||
// configuration used by the client.
|
||||
func (client *Client) GetDataCollection() DataCollection {
|
||||
if !client.IsEnabled() || client.options.DataCollection == nil {
|
||||
if client == nil || client.options.DataCollection == nil {
|
||||
return DataCollection{}
|
||||
}
|
||||
return *cloneDataCollection(client.options.DataCollection)
|
||||
@@ -650,32 +604,22 @@ func (client *Client) GetDataCollection() DataCollection {
|
||||
|
||||
// CaptureMessage captures an arbitrary message.
|
||||
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
event := client.EventFromMessage(message, LevelInfo)
|
||||
return client.CaptureEvent(event, hint, scope)
|
||||
}
|
||||
|
||||
// CaptureException captures an error.
|
||||
func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
event := client.EventFromException(exception, LevelError)
|
||||
return client.CaptureEvent(event, hint, scope)
|
||||
}
|
||||
|
||||
// CaptureCheckIn captures a check in.
|
||||
func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
event := client.EventFromCheckIn(checkIn, monitorConfig)
|
||||
if event != nil && event.CheckIn != nil {
|
||||
if client.CaptureEvent(event, nil, scope) != nil {
|
||||
return &event.CheckIn.ID
|
||||
}
|
||||
client.CaptureEvent(event, nil, scope)
|
||||
return &event.CheckIn.ID
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -686,9 +630,6 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon
|
||||
// the utility methods like CaptureException. The return value is the
|
||||
// event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
|
||||
func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
return client.processEvent(event, hint, scope)
|
||||
}
|
||||
|
||||
@@ -786,9 +727,6 @@ func (client *Client) RecoverWithContext(
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ctx != nil {
|
||||
if hint == nil {
|
||||
@@ -813,8 +751,7 @@ func (client *Client) RecoverWithContext(
|
||||
|
||||
// Flush waits until the underlying Transport sends any buffered events to the
|
||||
// Sentry server, blocking for at most the given timeout. It returns false if
|
||||
// the client is disabled or the timeout was reached. In the latter case, some
|
||||
// events may not have been sent.
|
||||
// the timeout was reached. In that case, some events may not have been sent.
|
||||
//
|
||||
// Flush should be called before terminating the program to avoid
|
||||
// unintentionally dropping events.
|
||||
@@ -824,9 +761,6 @@ func (client *Client) RecoverWithContext(
|
||||
// the network synchronously, configure it to use the HTTPSyncTransport in the
|
||||
// call to Init.
|
||||
func (client *Client) Flush(timeout time.Duration) bool {
|
||||
if !client.IsEnabled() {
|
||||
return false
|
||||
}
|
||||
if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
@@ -836,10 +770,9 @@ func (client *Client) Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
// FlushWithContext waits until the underlying Transport sends any buffered events
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if the client is disabled or the context is
|
||||
// canceled before the events are sent. In the latter case, some events may not
|
||||
// be delivered.
|
||||
// to the Sentry server, blocking for at most the duration specified by the context.
|
||||
// It returns false if the context is canceled before the events are sent. In such a case,
|
||||
// some events may not be delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
@@ -849,9 +782,6 @@ func (client *Client) Flush(timeout time.Duration) bool {
|
||||
// configure the SDK to use HTTPSyncTransport during initialization with Init.
|
||||
|
||||
func (client *Client) FlushWithContext(ctx context.Context) bool {
|
||||
if !client.IsEnabled() {
|
||||
return false
|
||||
}
|
||||
if client.batchLogger != nil {
|
||||
client.batchLogger.Flush(ctx.Done())
|
||||
}
|
||||
@@ -869,9 +799,6 @@ func (client *Client) FlushWithContext(ctx context.Context) bool {
|
||||
// Close should be called after Flush and before terminating the program
|
||||
// otherwise some events may be lost.
|
||||
func (client *Client) Close() {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
if client.telemetryProcessor != nil {
|
||||
client.telemetryProcessor.Close(5 * time.Second)
|
||||
}
|
||||
@@ -948,9 +875,6 @@ func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorC
|
||||
}
|
||||
|
||||
func (client *Client) SetSDKIdentifier(identifier string) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
|
||||
+4
-4
@@ -43,7 +43,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
|
||||
scope := hub.Scope()
|
||||
client := hub.Client()
|
||||
|
||||
if !client.IsEnabled() || scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return DynamicSamplingContext{
|
||||
Entries: map[string]string{},
|
||||
Frozen: false,
|
||||
@@ -53,7 +53,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
|
||||
entries := make(map[string]string)
|
||||
|
||||
if traceID := span.TraceID.String(); traceID != "" {
|
||||
entries[traceIDContextKey] = traceID
|
||||
entries["trace_id"] = traceID
|
||||
}
|
||||
if sampleRate := span.sampleRate; sampleRate != 0 {
|
||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
||||
@@ -122,7 +122,7 @@ func (d DynamicSamplingContext) String() string {
|
||||
func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
|
||||
entries := map[string]string{}
|
||||
|
||||
if !client.IsEnabled() || scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return DynamicSamplingContext{
|
||||
Entries: entries,
|
||||
Frozen: false,
|
||||
@@ -132,7 +132,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli
|
||||
propagationContext := scope.propagationContext
|
||||
|
||||
if traceID := propagationContext.TraceID.String(); traceID != "" {
|
||||
entries[traceIDContextKey] = traceID
|
||||
entries["trace_id"] = traceID
|
||||
}
|
||||
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
|
||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ type visited struct {
|
||||
|
||||
func (v *visited) seenError(err error) bool {
|
||||
t := reflect.ValueOf(err)
|
||||
if t.Kind() == reflect.Pointer && !t.IsNil() {
|
||||
if t.Kind() == reflect.Ptr && !t.IsNil() {
|
||||
ptr := t.Pointer()
|
||||
if _, ok := v.ptrs[ptr]; ok {
|
||||
return true
|
||||
|
||||
-1
@@ -2,7 +2,6 @@ go 1.25.0
|
||||
|
||||
use (
|
||||
.
|
||||
./cron
|
||||
./crosstest
|
||||
./echo
|
||||
./fasthttp
|
||||
|
||||
-18
@@ -1,7 +1,5 @@
|
||||
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
|
||||
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
|
||||
cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k=
|
||||
cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
@@ -16,7 +14,6 @@ git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm9
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
|
||||
@@ -63,7 +60,6 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
@@ -89,9 +85,6 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
|
||||
github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY=
|
||||
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
|
||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
@@ -145,7 +138,6 @@ github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY=
|
||||
github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
|
||||
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs=
|
||||
github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
|
||||
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502 h1:34icjjmqJ2HPjrSuJYEkdZ+0ItmGQAQ75cRHIiftIyE=
|
||||
github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090 h1:ok0U1tNDp9ICD93bMrZuFtHLwDoW+5nfSfF8e/x36Y0=
|
||||
@@ -169,13 +161,9 @@ go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
|
||||
@@ -184,12 +172,10 @@ golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
@@ -198,7 +184,6 @@ golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
@@ -214,7 +199,6 @@ golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
@@ -228,13 +212,11 @@ golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
|
||||
gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg=
|
||||
gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c h1:cJWOvXtcaFSGXz2F4z2AMM0VV7edDDGrxb5GLQH7ayQ=
|
||||
gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM=
|
||||
google.golang.org/genproto v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:p3MLuOwURrGBRoEyFHBT3GjUwaCQVKeNqqWxlcISGdw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
|
||||
+36
-52
@@ -20,7 +20,7 @@ const (
|
||||
RequestContextKey = contextKey(2)
|
||||
)
|
||||
|
||||
// currentHub is the initial Hub with a no-op Client and an empty Scope.
|
||||
// currentHub is the initial Hub with no Client bound and an empty Scope.
|
||||
var currentHub = NewHub(nil, NewScope())
|
||||
|
||||
// Hub is the central object that manages scopes and clients.
|
||||
@@ -58,7 +58,7 @@ func (l *layer) Client() *Client {
|
||||
func (l *layer) SetClient(c *Client) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.client = normalizeClient(c)
|
||||
l.client = c
|
||||
}
|
||||
|
||||
type stack []*layer
|
||||
@@ -67,7 +67,7 @@ type stack []*layer
|
||||
func NewHub(client *Client, scope *Scope) *Hub {
|
||||
hub := Hub{
|
||||
stack: &stack{{
|
||||
client: normalizeClient(client),
|
||||
client: client,
|
||||
scope: scope,
|
||||
}},
|
||||
}
|
||||
@@ -218,12 +218,12 @@ func (hub *Hub) CaptureEvent(event *Event) *EventID {
|
||||
// CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint.
|
||||
func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureEvent(event, hint, scope)
|
||||
|
||||
if event != nil && event.Type != transactionType && eventID != nil {
|
||||
if event.Type != transactionType && eventID != nil {
|
||||
hub.mu.Lock()
|
||||
hub.lastEventID = *eventID
|
||||
hub.mu.Unlock()
|
||||
@@ -236,7 +236,7 @@ func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
|
||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
||||
func (hub *Hub) CaptureMessage(message string) *EventID {
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureMessage(message, nil, scope)
|
||||
@@ -254,7 +254,7 @@ func (hub *Hub) CaptureMessage(message string) *EventID {
|
||||
// Returns EventID if successfully, or nil if there's no Scope or Client available.
|
||||
func (hub *Hub) CaptureException(exception error) *EventID {
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope)
|
||||
@@ -272,44 +272,11 @@ func (hub *Hub) CaptureException(exception error) *EventID {
|
||||
// Returns CheckInID if the check-in was captured successfully, or nil otherwise.
|
||||
func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
return client.CaptureCheckIn(checkIn, monitorConfig, scope)
|
||||
}
|
||||
|
||||
// WithMonitor runs fn and reports its outcome as check-ins for the cron
|
||||
// monitor identified by monitorSlug.
|
||||
//
|
||||
// An in_progress check-in carrying monitorConfig is sent before fn runs. When
|
||||
// monitorConfig is not nil, Sentry creates the monitor if it does not exist,
|
||||
// or updates its configuration. After fn returns, an ok check-in is sent if
|
||||
// it returned nil, or an error check-in otherwise, along with the measured
|
||||
// duration. If fn panics, an error check-in is sent and the panic continues.
|
||||
//
|
||||
// The error returned by fn is returned unchanged.
|
||||
func (hub *Hub) WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
|
||||
checkInID := hub.CaptureCheckIn(&CheckIn{
|
||||
MonitorSlug: monitorSlug,
|
||||
Status: CheckInStatusInProgress,
|
||||
}, monitorConfig)
|
||||
start := time.Now()
|
||||
|
||||
status := CheckInStatusError
|
||||
defer func() {
|
||||
checkIn := &CheckIn{
|
||||
MonitorSlug: monitorSlug,
|
||||
Status: status,
|
||||
Duration: time.Since(start),
|
||||
}
|
||||
if checkInID != nil {
|
||||
checkIn.ID = *checkInID
|
||||
}
|
||||
hub.CaptureCheckIn(checkIn, nil)
|
||||
}()
|
||||
|
||||
err := fn()
|
||||
if err == nil {
|
||||
status = CheckInStatusOK
|
||||
if client == nil {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
|
||||
return client.CaptureCheckIn(checkIn, monitorConfig, scope)
|
||||
}
|
||||
|
||||
// AddBreadcrumb records a new breadcrumb.
|
||||
@@ -319,6 +286,12 @@ func (hub *Hub) WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn
|
||||
func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
|
||||
client := hub.Client()
|
||||
|
||||
// If there's no client, just store it on the scope straight away
|
||||
if client == nil {
|
||||
hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs)
|
||||
return
|
||||
}
|
||||
|
||||
limit := client.options.MaxBreadcrumbs
|
||||
switch {
|
||||
case limit < 0:
|
||||
@@ -348,7 +321,7 @@ func (hub *Hub) Recover(err interface{}) *EventID {
|
||||
err = recover()
|
||||
}
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return nil
|
||||
}
|
||||
return client.Recover(err, &EventHint{RecoveredException: err}, scope)
|
||||
@@ -362,7 +335,7 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
|
||||
err = recover()
|
||||
}
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if scope == nil {
|
||||
if client == nil || scope == nil {
|
||||
return nil
|
||||
}
|
||||
return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope)
|
||||
@@ -380,14 +353,19 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
|
||||
// the network synchronously, configure it to use the HTTPSyncTransport in the
|
||||
// call to Init.
|
||||
func (hub *Hub) Flush(timeout time.Duration) bool {
|
||||
return hub.Client().Flush(timeout)
|
||||
client := hub.Client()
|
||||
|
||||
if client == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return client.Flush(timeout)
|
||||
}
|
||||
|
||||
// FlushWithContext waits until the underlying Transport sends any buffered events
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if capture is disabled or the context is canceled
|
||||
// before the events are sent. In the latter case, some events may not be
|
||||
// delivered.
|
||||
// to the Sentry server, blocking for at most the duration specified by the context.
|
||||
// It returns false if the context is canceled before the events are sent. In such a case,
|
||||
// some events may not be delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
@@ -397,7 +375,13 @@ func (hub *Hub) Flush(timeout time.Duration) bool {
|
||||
// configure the SDK to use HTTPSyncTransport during initialization with Init.
|
||||
|
||||
func (hub *Hub) FlushWithContext(ctx context.Context) bool {
|
||||
return hub.Client().FlushWithContext(ctx)
|
||||
client := hub.Client()
|
||||
|
||||
if client == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return client.FlushWithContext(ctx)
|
||||
}
|
||||
|
||||
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
|
||||
|
||||
-36
@@ -48,12 +48,6 @@ func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWr
|
||||
if fl && hj && rf {
|
||||
return &httpFancyWriter{bw}
|
||||
}
|
||||
if fl && hj {
|
||||
return &flushHijackWriter{bw}
|
||||
}
|
||||
if hj {
|
||||
return &hijackWriter{bw}
|
||||
}
|
||||
}
|
||||
if fl {
|
||||
return &flushWriter{bw}
|
||||
@@ -149,36 +143,6 @@ func (f *flushWriter) Flush() {
|
||||
|
||||
var _ http.Flusher = &flushWriter{}
|
||||
|
||||
// flushHijackWriter is a HTTP writer that additionally satisfies http.Flusher
|
||||
// and http.Hijacker, for writers that do not implement io.ReaderFrom.
|
||||
type flushHijackWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *flushHijackWriter) Flush() {
|
||||
f.wroteHeader = true
|
||||
f.ResponseWriter.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return f.ResponseWriter.(http.Hijacker).Hijack()
|
||||
}
|
||||
|
||||
var _ http.Flusher = &flushHijackWriter{}
|
||||
var _ http.Hijacker = &flushHijackWriter{}
|
||||
|
||||
// hijackWriter is a HTTP writer that additionally satisfies http.Hijacker, for
|
||||
// writers that implement neither http.Flusher nor io.ReaderFrom.
|
||||
type hijackWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *hijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return f.ResponseWriter.(http.Hijacker).Hijack()
|
||||
}
|
||||
|
||||
var _ http.Hijacker = &hijackWriter{}
|
||||
|
||||
// httpFancyWriter is a HTTP writer that additionally satisfies
|
||||
// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case
|
||||
// of wrapping the http.ResponseWriter that package http gives you, in order to
|
||||
|
||||
+8
-12
@@ -3,7 +3,6 @@ package protocol
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -211,20 +210,17 @@ func (dsn *Dsn) SetOrgID(orgID uint64) {
|
||||
// GetAPIURL returns the URL of the envelope endpoint of the project
|
||||
// associated with the DSN.
|
||||
func (dsn Dsn) GetAPIURL() *url.URL {
|
||||
host := dsn.host
|
||||
port := ""
|
||||
var rawURL string
|
||||
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host)
|
||||
if dsn.port != dsn.scheme.defaultPort() {
|
||||
port = strconv.Itoa(dsn.port)
|
||||
rawURL += fmt.Sprintf(":%d", dsn.port)
|
||||
}
|
||||
// JoinHostPort correctly adds brackets for IPv6 hosts. However with an
|
||||
// empty port it leaves a trailing ":", which we trim to omit the default port.
|
||||
host = net.JoinHostPort(host, port)
|
||||
host = strings.TrimSuffix(host, ":")
|
||||
return &url.URL{
|
||||
Scheme: string(dsn.scheme),
|
||||
Host: host,
|
||||
Path: dsn.path + "/api/" + dsn.projectID + "/envelope/",
|
||||
if dsn.path != "" {
|
||||
rawURL += dsn.path
|
||||
}
|
||||
rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope")
|
||||
parsedURL, _ := url.Parse(rawURL)
|
||||
return parsedURL
|
||||
}
|
||||
|
||||
// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events
|
||||
|
||||
+2
-26
@@ -26,9 +26,6 @@ type Scheduler struct {
|
||||
cancel context.CancelFunc
|
||||
processingWg sync.WaitGroup
|
||||
|
||||
// processing serializes buffer-to-transport handoffs and allows cancelable waits.
|
||||
processing chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
startOnce sync.Once
|
||||
@@ -82,7 +79,6 @@ func NewScheduler(
|
||||
currentCycle: currentCycle,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
processing: make(chan struct{}, 1),
|
||||
}
|
||||
s.cond = sync.NewCond(&s.mu)
|
||||
|
||||
@@ -149,9 +145,7 @@ func (s *Scheduler) Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
func (s *Scheduler) FlushWithContext(ctx context.Context) bool {
|
||||
if !s.flushBuffers(ctx) {
|
||||
return false
|
||||
}
|
||||
s.flushBuffers()
|
||||
return s.transport.FlushWithContext(ctx)
|
||||
}
|
||||
|
||||
@@ -199,13 +193,6 @@ func (s *Scheduler) hasWork() bool {
|
||||
}
|
||||
|
||||
func (s *Scheduler) processNextBatch() {
|
||||
select {
|
||||
case s.processing <- struct{}{}:
|
||||
defer func() { <-s.processing }()
|
||||
case <-s.ctx.Done():
|
||||
return
|
||||
}
|
||||
|
||||
if len(s.currentCycle) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -303,23 +290,12 @@ func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) flushBuffers(ctx context.Context) bool {
|
||||
select {
|
||||
case s.processing <- struct{}{}:
|
||||
defer func() { <-s.processing }()
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Scheduler) flushBuffers() {
|
||||
for category, buffer := range s.buffers {
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
if !buffer.IsEmpty() {
|
||||
s.processItems(buffer, category, true)
|
||||
}
|
||||
}
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) isRateLimited(category ratelimit.Category) bool {
|
||||
|
||||
+2
-2
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
|
||||
}
|
||||
|
||||
client := hub.Client()
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
// Build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -111,7 +111,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
|
||||
hub = l.hub
|
||||
}
|
||||
client := hub.Client()
|
||||
if !client.IsEnabled() {
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
|
||||
hub = CurrentHub()
|
||||
}
|
||||
client := hub.Client()
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
// build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -110,7 +110,7 @@ func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name stri
|
||||
}
|
||||
|
||||
client := hub.Client()
|
||||
if !client.IsEnabled() {
|
||||
if client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+2
-7
@@ -4,11 +4,6 @@ import (
|
||||
"crypto/rand"
|
||||
)
|
||||
|
||||
const (
|
||||
traceIDContextKey = "trace_id"
|
||||
spanIDContextKey = "span_id"
|
||||
)
|
||||
|
||||
type PropagationContext struct {
|
||||
TraceID TraceID `json:"trace_id"`
|
||||
SpanID SpanID `json:"span_id"`
|
||||
@@ -18,8 +13,8 @@ type PropagationContext struct {
|
||||
|
||||
func (p PropagationContext) Map() map[string]interface{} {
|
||||
m := map[string]interface{}{
|
||||
traceIDContextKey: p.TraceID,
|
||||
spanIDContextKey: p.SpanID,
|
||||
"trace_id": p.TraceID,
|
||||
"span_id": p.SpanID,
|
||||
}
|
||||
|
||||
if p.ParentSpanID != zeroSpanID {
|
||||
|
||||
+13
-33
@@ -30,15 +30,7 @@ import (
|
||||
// an event for reporting, the current client adds information from the current
|
||||
// scope into the event.
|
||||
type Scope struct {
|
||||
mu sync.RWMutex
|
||||
// eventProcessors are retained by Clear and inherited by Clone.
|
||||
eventProcessors []EventProcessor
|
||||
|
||||
// scopeData keeps track of all scope specific data
|
||||
scopeData
|
||||
}
|
||||
|
||||
type scopeData struct {
|
||||
mu sync.RWMutex
|
||||
attributes map[string]attribute.Value
|
||||
breadcrumbs []*Breadcrumb
|
||||
attachments []*Attachment
|
||||
@@ -57,6 +49,7 @@ type scopeData struct {
|
||||
// size.
|
||||
Overflow() bool
|
||||
}
|
||||
eventProcessors []EventProcessor
|
||||
|
||||
propagationContext PropagationContext
|
||||
span *Span
|
||||
@@ -64,18 +57,14 @@ type scopeData struct {
|
||||
|
||||
// NewScope creates a new Scope.
|
||||
func NewScope() *Scope {
|
||||
return &Scope{scopeData: newScopeData(NewPropagationContext())}
|
||||
}
|
||||
|
||||
func newScopeData(propagationContext PropagationContext) scopeData {
|
||||
return scopeData{
|
||||
return &Scope{
|
||||
attributes: make(map[string]attribute.Value),
|
||||
breadcrumbs: make([]*Breadcrumb, 0),
|
||||
attachments: make([]*Attachment, 0),
|
||||
tags: make(map[string]string),
|
||||
contexts: make(map[string]Context),
|
||||
fingerprint: make([]string, 0),
|
||||
propagationContext: propagationContext,
|
||||
propagationContext: NewPropagationContext(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -293,7 +282,6 @@ func (scope *Scope) Clone() *Scope {
|
||||
|
||||
clone := NewScope()
|
||||
clone.user = scope.user
|
||||
clone.user.Data = maps.Clone(scope.user.Data)
|
||||
clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs))
|
||||
copy(clone.breadcrumbs, scope.breadcrumbs)
|
||||
clone.attachments = make([]*Attachment, len(scope.attachments))
|
||||
@@ -312,16 +300,9 @@ func (scope *Scope) Clone() *Scope {
|
||||
return clone
|
||||
}
|
||||
|
||||
// Clear removes enrichment data while preserving event processors and trace
|
||||
// correlation. It is safe for concurrent use.
|
||||
// Clear removes the data from the current scope. Not safe for concurrent use.
|
||||
func (scope *Scope) Clear() {
|
||||
scope.mu.Lock()
|
||||
defer scope.mu.Unlock()
|
||||
|
||||
propagationContext := scope.propagationContext
|
||||
span := scope.span
|
||||
scope.scopeData = newScopeData(propagationContext)
|
||||
scope.span = span
|
||||
*scope = *NewScope()
|
||||
}
|
||||
|
||||
// AddEventProcessor adds an event processor to the current scope.
|
||||
@@ -394,7 +375,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
event.Contexts["trace"] = scope.propagationContext.Map()
|
||||
|
||||
dsc := scope.propagationContext.DynamicSamplingContext
|
||||
if !dsc.HasEntries() && client.IsEnabled() {
|
||||
if !dsc.HasEntries() && client != nil {
|
||||
dsc = DynamicSamplingContextFromScope(scope, client)
|
||||
}
|
||||
event.sdkMetaData.dsc = dsc
|
||||
@@ -402,7 +383,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
|
||||
// If an external trace resolver is registered (e.g. OTel), override
|
||||
// trace/span IDs from the hint context or the scope's request context.
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
var ctx context.Context
|
||||
if hint != nil {
|
||||
ctx = hint.Context
|
||||
@@ -412,14 +393,13 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
}
|
||||
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok {
|
||||
traceCtx := event.Contexts["trace"]
|
||||
traceCtx[traceIDContextKey] = traceID.String()
|
||||
traceCtx[spanIDContextKey] = spanID.String()
|
||||
traceCtx["trace_id"] = traceID.String()
|
||||
traceCtx["span_id"] = spanID.String()
|
||||
}
|
||||
}
|
||||
|
||||
if event.User.IsEmpty() {
|
||||
event.User = scope.user
|
||||
event.User.Data = maps.Clone(scope.user.Data)
|
||||
}
|
||||
|
||||
if len(event.Fingerprint) == 0 {
|
||||
@@ -454,7 +434,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
event = processor(event, hint)
|
||||
if event == nil {
|
||||
debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
client.reportRecorder.RecordOne(report.ReasonEventProcessor, category)
|
||||
if category == ratelimit.CategoryTransaction {
|
||||
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore))
|
||||
@@ -463,7 +443,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
return nil
|
||||
}
|
||||
if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 {
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans))
|
||||
}
|
||||
}
|
||||
@@ -544,7 +524,7 @@ func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceI
|
||||
if ctx == nil {
|
||||
continue
|
||||
}
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok {
|
||||
return traceID, spanID
|
||||
}
|
||||
|
||||
+4
-25
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// The version of the SDK.
|
||||
const SDKVersion = "0.50.0"
|
||||
const SDKVersion = "0.49.0"
|
||||
|
||||
// apiVersion is the minimum version of the Sentry API compatible with the
|
||||
// sentry-go SDK.
|
||||
@@ -54,26 +54,6 @@ func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
|
||||
return hub.CaptureCheckIn(checkIn, monitorConfig)
|
||||
}
|
||||
|
||||
// WithMonitor runs fn and reports its outcome as check-ins for the cron
|
||||
// monitor identified by monitorSlug, creating or updating the monitor with
|
||||
// monitorConfig when it is not nil. It is a shorthand for
|
||||
// CurrentHub().WithMonitor.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// err := sentry.WithMonitor("nightly-cleanup", &sentry.MonitorConfig{
|
||||
// Schedule: sentry.CrontabSchedule("0 3 * * *"),
|
||||
// CheckInMargin: 5,
|
||||
// MaxRuntime: 30,
|
||||
// Timezone: "UTC",
|
||||
// }, func() error {
|
||||
// return cleanup()
|
||||
// })
|
||||
func WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
|
||||
hub := CurrentHub()
|
||||
return hub.WithMonitor(monitorSlug, monitorConfig, fn)
|
||||
}
|
||||
|
||||
// CaptureEvent captures an event on the currently active client if any.
|
||||
//
|
||||
// The event must already be assembled. Typically code would instead use
|
||||
@@ -149,10 +129,9 @@ func Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
// FlushWithContext waits until the underlying Transport sends any buffered events
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if capture is disabled or the context is canceled
|
||||
// before the events are sent. In the latter case, some events may not be
|
||||
// delivered.
|
||||
// to the Sentry server, blocking for at most the duration specified by the context.
|
||||
// It returns false if the context is canceled before the events are sent. In such a case,
|
||||
// some events may not be delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ type spanRecorder struct {
|
||||
// span tree.
|
||||
func (r *spanRecorder) record(s *Span) {
|
||||
maxSpans := defaultMaxSpans
|
||||
if client := CurrentHub().Client(); client.IsEnabled() {
|
||||
if client := CurrentHub().Client(); client != nil {
|
||||
maxSpans = client.options.MaxSpans
|
||||
}
|
||||
r.mu.Lock()
|
||||
|
||||
+4
-4
@@ -551,7 +551,7 @@ func (s *Span) updateFromBaggage(header []byte) {
|
||||
|
||||
func (s *Span) clientOptions() *ClientOptions {
|
||||
client := hubFromContext(s.ctx).Client()
|
||||
if client.IsEnabled() {
|
||||
if client != nil {
|
||||
return &client.options
|
||||
}
|
||||
return &ClientOptions{}
|
||||
@@ -933,8 +933,8 @@ type TraceContext struct {
|
||||
|
||||
func (tc TraceContext) Map() map[string]interface{} {
|
||||
m := map[string]interface{}{
|
||||
traceIDContextKey: tc.TraceID,
|
||||
spanIDContextKey: tc.SpanID,
|
||||
"trace_id": tc.TraceID,
|
||||
"span_id": tc.SpanID,
|
||||
}
|
||||
|
||||
if tc.ParentSpanID != [8]byte{} {
|
||||
@@ -1202,7 +1202,7 @@ func HTTPtoSpanStatus(code int) SpanStatus {
|
||||
}
|
||||
|
||||
func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool {
|
||||
if !client.IsEnabled() {
|
||||
if client == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+1
-4
@@ -63,7 +63,6 @@ const (
|
||||
ChineseFirstNameTag = "chinese_first_name"
|
||||
ChineseLastNameTag = "chinese_last_name"
|
||||
ChineseNameTag = "chinese_name"
|
||||
ChinesePhoneNumberTag = "chinese_phone_number"
|
||||
GENDER = "gender"
|
||||
UnixTimeTag = "unix_time"
|
||||
DATE = "date"
|
||||
@@ -108,7 +107,7 @@ const (
|
||||
var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag,
|
||||
IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber,
|
||||
E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag,
|
||||
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, ChinesePhoneNumberTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
|
||||
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
|
||||
YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH,
|
||||
CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag,
|
||||
UserAgentTag,
|
||||
@@ -170,7 +169,6 @@ func initDefaultTag() {
|
||||
defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag)
|
||||
defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag)
|
||||
defaultTag.Store(ChineseNameTag, ChineseNameTag)
|
||||
defaultTag.Store(ChinesePhoneNumberTag, ChinesePhoneNumberTag)
|
||||
defaultTag.Store(GENDER, GENDER)
|
||||
defaultTag.Store(UnixTimeTag, UnixTimeTag)
|
||||
defaultTag.Store(DATE, DATE)
|
||||
@@ -222,7 +220,6 @@ func initMapperTagDefault() {
|
||||
mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName)
|
||||
mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName)
|
||||
mapperTag.Store(ChineseNameTag, GetPerson().ChineseName)
|
||||
mapperTag.Store(ChinesePhoneNumberTag, GetPhoner().ChinesePhoneNumber)
|
||||
mapperTag.Store(GENDER, GetPerson().Gender)
|
||||
mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime)
|
||||
mapperTag.Store(DATE, GetDateTimer().Date)
|
||||
|
||||
-34
@@ -9,20 +9,6 @@ import (
|
||||
"github.com/go-faker/faker/v4/pkg/slice"
|
||||
)
|
||||
|
||||
// chineseMobilePrefixes holds the 3-digit prefixes of Mainland China mobile
|
||||
// numbers, allocated to China Mobile, China Unicom, China Telecom and China
|
||||
// Broadnet (including MVNO & IoT segments). Each prefix is followed by 8
|
||||
// subscriber digits to form an 11-digit number.
|
||||
var chineseMobilePrefixes = []string{
|
||||
"130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
|
||||
"145", "146", "147", "148", "149",
|
||||
"150", "151", "152", "153", "155", "156", "157", "158", "159",
|
||||
"162", "165", "166", "167",
|
||||
"170", "171", "172", "173", "174", "175", "176", "177", "178",
|
||||
"180", "181", "182", "183", "184", "185", "186", "187", "188", "189",
|
||||
"190", "191", "192", "193", "195", "196", "197", "198", "199",
|
||||
}
|
||||
|
||||
// GetPhoner serves as a constructor for Phoner interface
|
||||
func GetPhoner() Phoner {
|
||||
phone := &Phone{}
|
||||
@@ -34,7 +20,6 @@ type Phoner interface {
|
||||
PhoneNumber(v reflect.Value) (any, error)
|
||||
TollFreePhoneNumber(v reflect.Value) (any, error)
|
||||
E164PhoneNumber(v reflect.Value) (any, error)
|
||||
ChinesePhoneNumber(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Phone struct
|
||||
@@ -110,22 +95,3 @@ func E164PhoneNumber(opts ...options.OptionFunc) string {
|
||||
return p.e164PhoneNumber()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
func (p Phone) chinesePhoneNumber() string {
|
||||
prefix := chineseMobilePrefixes[rand.Intn(len(chineseMobilePrefixes))]
|
||||
return prefix + randomStringNumber(8)
|
||||
}
|
||||
|
||||
// ChinesePhoneNumber generates a Mainland-China mobile phone number of the
|
||||
// form "13812345678" (11 digits, starting with a valid operator prefix)
|
||||
func (p Phone) ChinesePhoneNumber(v reflect.Value) (any, error) {
|
||||
return p.chinesePhoneNumber(), nil
|
||||
}
|
||||
|
||||
// ChinesePhoneNumber get fake Chinese phone number
|
||||
func ChinesePhoneNumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ChinesePhoneNumberTag, func() any {
|
||||
p := Phone{}
|
||||
return p.chinesePhoneNumber()
|
||||
}, opts...).(string)
|
||||
}
|
||||
+5
-7
@@ -139,13 +139,11 @@ func main() {
|
||||
fmt.Println(l.CardinalPluralRule(1.0, 1))
|
||||
fmt.Println(l.CardinalPluralRule(3, 0))
|
||||
|
||||
// Ordinal Plural Rules. The method returns the locales/plurals.Rule
|
||||
// (e.g. One, Two, Few, Other) for the number; converting that rule into
|
||||
// the actual suffix ("st", "nd", "rd", "th") is left to the caller.
|
||||
fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st")
|
||||
fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd")
|
||||
fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd")
|
||||
fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th")
|
||||
// Ordinal Plural Rules
|
||||
fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st
|
||||
fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd
|
||||
fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd
|
||||
fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th
|
||||
|
||||
// Range Plural Rules
|
||||
fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1
|
||||
|
||||
+16
-12
@@ -498,9 +498,10 @@ func (en *en) FmtTimeShort(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -527,9 +528,10 @@ func (en *en) FmtTimeMedium(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -563,9 +565,10 @@ func (en *en) FmtTimeLong(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -604,9 +607,10 @@ func (en *en) FmtTimeFull(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
|
||||
+10
-13
@@ -98,7 +98,7 @@ type Translator interface {
|
||||
// returns the locales narrow weekday given the 'weekday' provided
|
||||
WeekdayNarrow(weekday time.Weekday) string
|
||||
|
||||
// WeekdaysNarrow returns the locales narrow weekdays
|
||||
// WeekdaysNarrowreturns the locales narrow weekdays
|
||||
WeekdaysNarrow() []string
|
||||
|
||||
// returns the locales short weekday given the 'weekday' provided
|
||||
@@ -113,7 +113,7 @@ type Translator interface {
|
||||
// returns the locales wide weekdays
|
||||
WeekdaysWide() []string
|
||||
|
||||
// The following Functions are common Formatting functions for the Translator's Locale
|
||||
// The following Functions are common Formatting functionsfor the Translator's Locale
|
||||
|
||||
// returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v'
|
||||
FmtNumber(num float64, v uint64) string
|
||||
@@ -228,14 +228,14 @@ func W(n float64, v uint64) (w int64) {
|
||||
|
||||
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
|
||||
|
||||
// will either be '0' or '0.xxxx', so if 1 then w will be zero
|
||||
// with either be '0' or '0.xxxx', so if 1 then w will be zero
|
||||
// otherwise need to parse
|
||||
if len(s) != 1 {
|
||||
|
||||
s = s[2:]
|
||||
end := 0
|
||||
end := len(s) + 1
|
||||
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
for i := end; i >= 0; i-- {
|
||||
if s[i] != '0' {
|
||||
end = i + 1
|
||||
break
|
||||
@@ -253,7 +253,7 @@ func F(n float64, v uint64) (f int64) {
|
||||
|
||||
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
|
||||
|
||||
// will either be '0' or '0.xxxx', so if 1 then f will be zero
|
||||
// with either be '0' or '0.xxxx', so if 1 then f will be zero
|
||||
// otherwise need to parse
|
||||
if len(s) != 1 {
|
||||
|
||||
@@ -270,14 +270,14 @@ func T(n float64, v uint64) (t int64) {
|
||||
|
||||
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
|
||||
|
||||
// will either be '0' or '0.xxxx', so if 1 then t will be zero
|
||||
// with either be '0' or '0.xxxx', so if 1 then t will be zero
|
||||
// otherwise need to parse
|
||||
if len(s) != 1 {
|
||||
|
||||
s = s[2:]
|
||||
end := 0
|
||||
end := len(s) + 1
|
||||
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
for i := end; i >= 0; i-- {
|
||||
if s[i] != '0' {
|
||||
end = i + 1
|
||||
break
|
||||
@@ -286,11 +286,8 @@ func T(n float64, v uint64) (t int64) {
|
||||
|
||||
// ignoring error, because it can't fail as we generated
|
||||
// the string internally from a real number
|
||||
if end > 0 {
|
||||
t, _ = strconv.ParseInt(s[:end], 10, 64)
|
||||
}
|
||||
t, _ = strconv.ParseInt(s[:end], 10, 64)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
`universal-translator` (`ut`) is a Go i18n library that wraps `github.com/go-playground/locales` (CLDR locale data) to provide translation registration, plural rule handling (cardinal, ordinal, range), and `{0}`-style parameter substitution. Translations can be registered programmatically or loaded from JSON files.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Run tests with race detection and coverage
|
||||
make test
|
||||
|
||||
# Run benchmarks
|
||||
make bench
|
||||
|
||||
# Lint
|
||||
make lint # or: golangci-lint run
|
||||
|
||||
# Run a single test
|
||||
go test -run TestTranslatorAdd -race -v ./...
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Flat package `ut` at the repo root — no sub-packages.
|
||||
|
||||
- **`universal_translator.go`** — `UniversalTranslator` struct: holds a `map[string]Translator` (keyed by lowercased locale) plus a fallback. Constructor: `New(fallback, ...supportedLocales)`. Methods: `FindTranslator`, `GetTranslator`, `AddTranslator`, `VerifyTranslations`.
|
||||
- **`translator.go`** — `Translator` interface (embeds `locales.Translator`) and private `translator` impl. Registration: `Add`, `AddCardinal`, `AddOrdinal`, `AddRange`. Resolution: `T`, `C`, `O`, `R`. Each translation key is `interface{}` (string or int). Parameter substitution indexes are precomputed at registration time via `transText`.
|
||||
- **`import_export.go`** — JSON import/export. `Export` writes per-locale JSON files. `Import` reads them (supports recursive directory traversal). `ImportByReader` for streaming.
|
||||
- **`errors.go`** — Typed error structs: `ErrUnknownTranslation`, `ErrExistingTranslator`, `ErrConflictingTranslation`, `ErrRangeTranslation`, `ErrOrdinalTranslation`, `ErrCardinalTranslation`, `ErrMissingPluralTranslation`, `ErrMissingBracket`, `ErrBadParamSyntax`, `ErrMissingLocale`, `ErrBadPluralDefinition`.
|
||||
|
||||
Note: the private field names `cardinalTanslations`, `ordinalTanslations`, `rangeTanslations` are historical typos — do not "fix" them as it would break serialization/deserialization compatibility.
|
||||
|
||||
## Testing
|
||||
|
||||
Tests live at the repo root alongside source files. Test data JSON files are in `testdata/`. The library is goroutine-safe for reads once translations are registered — benchmarks in `benchmarks_test.go` test both serial and parallel `T()` calls.
|
||||
|
||||
## CI
|
||||
|
||||
GitHub Actions (`.github/workflows/workflow.yml`): Go 1.19.x matrix across ubuntu/macos/windows with race detection, coverage via goveralls, and golangci-lint.
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
## AI Agents
|
||||
|
||||
AI-assisted contributions are welcome but must be clearly attributed. If you are an AI agent or using an AI agent to contribute:
|
||||
|
||||
- **Commits**: Include a `Co-Authored-By:` trailer identifying the AI model used.
|
||||
- **Pull requests and issues**: State that the content was AI-generated or AI-assisted in the description.
|
||||
- **Code review comments**: Prefix with `[AI]` when posting automated review comments.
|
||||
|
||||
Contributions that obscure their AI origin may be closed.
|
||||
-11
@@ -82,17 +82,6 @@ Help With Tests
|
||||
To anyone interesting in helping or contributing, I sure could use some help creating tests for each language.
|
||||
Please see issue [here](https://github.com/go-playground/locales/issues/1) for details.
|
||||
|
||||
Supported Go Versions
|
||||
---------------------
|
||||
This package is aligned with the [Go release policy](https://go.dev/doc/devel/release) in that support is guaranteed for
|
||||
the two most recent major versions.
|
||||
|
||||
This does not mean the package will not work with older versions of Go, only that we reserve the right to increase the
|
||||
MSGV(Minimum Supported Go Version) when the need arises to address Security issues/patches, OS issues & support or newly
|
||||
introduced functionality that would greatly benefit the maintenance and/or usage of this package.
|
||||
|
||||
If and when the MSGV is increased it will be done so in a minimum of a `Minor` release bump.
|
||||
|
||||
License
|
||||
------
|
||||
Distributed under MIT License, please see license file in code for more details.
|
||||
+2
-5
@@ -8,11 +8,8 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnknownTranslation indicates the translation could not be found
|
||||
ErrUnknownTranslation = errors.New("unknown translation")
|
||||
|
||||
// Deprecated: Use ErrUnknownTranslation instead.
|
||||
ErrUnknowTranslation = ErrUnknownTranslation
|
||||
// ErrUnknowTranslation indicates the translation could not be found
|
||||
ErrUnknowTranslation = errors.New("Unknown Translation")
|
||||
)
|
||||
|
||||
var _ error = new(ErrConflictingTranslation)
|
||||
|
||||
+1
-1
@@ -163,7 +163,7 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
defer f.Close()
|
||||
|
||||
return t.ImportByReader(format, f)
|
||||
}
|
||||
|
||||
+33
-83
@@ -101,87 +101,35 @@ func (t *translator) Add(key interface{}, text string, override bool) error {
|
||||
return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text}
|
||||
}
|
||||
|
||||
indexes, err := parseParamPlaceholders(text, t.Locale(), key)
|
||||
if err != nil {
|
||||
return err
|
||||
lb := strings.Count(text, "{")
|
||||
rb := strings.Count(text, "}")
|
||||
|
||||
if lb != rb {
|
||||
return &ErrMissingBracket{locale: t.Locale(), key: key, text: text}
|
||||
}
|
||||
|
||||
t.translations[key] = &transText{text: text, indexes: indexes}
|
||||
trans := &transText{
|
||||
text: text,
|
||||
}
|
||||
|
||||
var idx int
|
||||
|
||||
for i := 0; i < lb; i++ {
|
||||
s := "{" + strconv.Itoa(i) + "}"
|
||||
idx = strings.Index(text, s)
|
||||
if idx == -1 {
|
||||
return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text}
|
||||
}
|
||||
|
||||
trans.indexes = append(trans.indexes, idx)
|
||||
trans.indexes = append(trans.indexes, idx+len(s))
|
||||
}
|
||||
|
||||
t.translations[key] = trans
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseParamPlaceholders scans text for {N} placeholders where N is a canonical
|
||||
// non-negative integer (no leading zeros). Returns triplets [start, end, paramIdx, ...]
|
||||
// sorted by text position. Requires consecutive param indices starting from 0.
|
||||
func parseParamPlaceholders(text string, locale string, key interface{}) ([]int, error) {
|
||||
var indexes []int
|
||||
seen := make(map[int]struct{})
|
||||
maxParam := -1
|
||||
|
||||
for i := 0; i < len(text); i++ {
|
||||
if text[i] != '{' {
|
||||
continue
|
||||
}
|
||||
|
||||
j := i + 1
|
||||
for j < len(text) && text[j] >= '0' && text[j] <= '9' {
|
||||
j++
|
||||
}
|
||||
|
||||
digitLen := j - i - 1
|
||||
if digitLen == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if j >= len(text) {
|
||||
return nil, &ErrMissingBracket{locale: locale, key: key, text: text}
|
||||
}
|
||||
|
||||
if text[j] != '}' {
|
||||
i = j - 1
|
||||
continue
|
||||
}
|
||||
|
||||
if digitLen > 1 && text[i+1] == '0' {
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
|
||||
if digitLen > 9 {
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
|
||||
n := 0
|
||||
for k := i + 1; k < j; k++ {
|
||||
n = n*10 + int(text[k]-'0')
|
||||
}
|
||||
|
||||
indexes = append(indexes, i, j+1, n)
|
||||
seen[n] = struct{}{}
|
||||
if n > maxParam {
|
||||
maxParam = n
|
||||
}
|
||||
|
||||
i = j
|
||||
}
|
||||
|
||||
if len(seen) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if maxParam != len(seen)-1 {
|
||||
for i := 0; i <= maxParam; i++ {
|
||||
if _, ok := seen[i]; !ok {
|
||||
return nil, &ErrBadParamSyntax{locale: locale, param: "{" + strconv.Itoa(i) + "}", key: key, text: text}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return indexes, nil
|
||||
}
|
||||
|
||||
// AddCardinal adds a cardinal plural translation for a particular language/locale
|
||||
// {0} is the only replacement type accepted and only one variable is accepted as
|
||||
// multiple cannot be used for a plural rule determination, unless it is a range;
|
||||
@@ -350,18 +298,20 @@ func (t *translator) T(key interface{}, params ...string) (string, error) {
|
||||
|
||||
trans, ok := t.translations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
}
|
||||
|
||||
b := make([]byte, 0, 64)
|
||||
|
||||
var start, end int
|
||||
var start, end, count int
|
||||
|
||||
for i := 0; i < len(trans.indexes); i += 3 {
|
||||
for i := 0; i < len(trans.indexes); i++ {
|
||||
end = trans.indexes[i]
|
||||
b = append(b, trans.text[start:end]...)
|
||||
b = append(b, params[trans.indexes[i+2]]...)
|
||||
start = trans.indexes[i+1]
|
||||
b = append(b, params[count]...)
|
||||
i++
|
||||
start = trans.indexes[i]
|
||||
count++
|
||||
}
|
||||
|
||||
b = append(b, trans.text[start:]...)
|
||||
@@ -374,7 +324,7 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string
|
||||
|
||||
tarr, ok := t.cardinalTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
}
|
||||
|
||||
rule := t.CardinalPluralRule(num, digits)
|
||||
@@ -394,7 +344,7 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string
|
||||
|
||||
tarr, ok := t.ordinalTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
}
|
||||
|
||||
rule := t.OrdinalPluralRule(num, digits)
|
||||
@@ -415,7 +365,7 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float
|
||||
|
||||
tarr, ok := t.rangeTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
}
|
||||
|
||||
rule := t.RangePluralRule(num1, digits1, num2, digits2)
|
||||
|
||||
-47
@@ -18,50 +18,6 @@ func (e InvalidTemplateError) Error() string {
|
||||
|
||||
// Parse parses the string representation of path template
|
||||
func Parse(tmpl string) (Compiler, error) {
|
||||
return parse(tmpl)
|
||||
}
|
||||
|
||||
// Segment is a top-level segment of a parsed path template.
|
||||
type Segment struct {
|
||||
// FieldPath is the field path bound by a variable segment, e.g. "name"
|
||||
// for "{name=projects/*}". It is empty for literal and wildcard segments.
|
||||
FieldPath string
|
||||
// Value is the literal or wildcard ("*" or "**") of a non-variable
|
||||
// segment, or the pattern of a variable segment, e.g. "projects/*" for
|
||||
// "{name=projects/*}". A variable without an explicit pattern, such as
|
||||
// "{name}", has the pattern "*".
|
||||
Value string
|
||||
}
|
||||
|
||||
// SplitTemplate parses the string representation of path template and
|
||||
// returns its top-level segments and its verb. The root template "/" has no
|
||||
// segments.
|
||||
func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) {
|
||||
t, err := parse(tmpl)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for _, s := range t.segments {
|
||||
switch s := s.(type) {
|
||||
case literal:
|
||||
if s == eof {
|
||||
continue
|
||||
}
|
||||
segments = append(segments, Segment{Value: string(s)})
|
||||
case variable:
|
||||
pattern := make([]string, 0, len(s.segments))
|
||||
for _, vs := range s.segments {
|
||||
pattern = append(pattern, vs.String())
|
||||
}
|
||||
segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")})
|
||||
default:
|
||||
segments = append(segments, Segment{Value: s.String()})
|
||||
}
|
||||
}
|
||||
return segments, t.verb, nil
|
||||
}
|
||||
|
||||
func parse(tmpl string) (template, error) {
|
||||
if !strings.HasPrefix(tmpl, "/") {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
|
||||
}
|
||||
@@ -72,9 +28,6 @@ func parse(tmpl string) (template, error) {
|
||||
if err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
|
||||
}
|
||||
if err := expectPChars(verb); err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)}
|
||||
}
|
||||
|
||||
return template{
|
||||
segments: segs,
|
||||
|
||||
-6
@@ -38,7 +38,6 @@ go_library(
|
||||
"@org_golang_google_protobuf//reflect/protoreflect",
|
||||
"@org_golang_google_protobuf//reflect/protoregistry",
|
||||
"@org_golang_google_protobuf//types/known/durationpb",
|
||||
"@org_golang_google_protobuf//types/known/emptypb",
|
||||
"@org_golang_google_protobuf//types/known/fieldmaskpb",
|
||||
"@org_golang_google_protobuf//types/known/structpb",
|
||||
"@org_golang_google_protobuf//types/known/timestamppb",
|
||||
@@ -50,16 +49,13 @@ go_test(
|
||||
name = "runtime_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"context_internal_test.go",
|
||||
"context_test.go",
|
||||
"convert_test.go",
|
||||
"errors_test.go",
|
||||
"fieldmask_empty_object_test.go",
|
||||
"fieldmask_test.go",
|
||||
"handler_test.go",
|
||||
"marshal_httpbodyproto_test.go",
|
||||
"marshal_json_test.go",
|
||||
"marshal_jsonpb_bench_test.go",
|
||||
"marshal_jsonpb_test.go",
|
||||
"marshal_proto_test.go",
|
||||
"marshaler_registry_test.go",
|
||||
@@ -67,7 +63,6 @@ go_test(
|
||||
"mux_test.go",
|
||||
"pattern_test.go",
|
||||
"query_fuzz_test.go",
|
||||
"query_internal_test.go",
|
||||
"query_test.go",
|
||||
],
|
||||
embed = [":runtime"],
|
||||
@@ -81,7 +76,6 @@ go_test(
|
||||
"@org_golang_google_genproto_googleapis_rpc//status",
|
||||
"@org_golang_google_grpc//:grpc",
|
||||
"@org_golang_google_grpc//codes",
|
||||
"@org_golang_google_grpc//credentials/insecure",
|
||||
"@org_golang_google_grpc//health/grpc_health_v1",
|
||||
"@org_golang_google_grpc//metadata",
|
||||
"@org_golang_google_grpc//status",
|
||||
|
||||
+14
-76
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
@@ -37,13 +36,6 @@ const metadataHeaderBinarySuffix = "-Bin"
|
||||
const xForwardedFor = "X-Forwarded-For"
|
||||
const xForwardedHost = "X-Forwarded-Host"
|
||||
|
||||
// gRPC metadata keys are lower-case, so these two are appended to the pairs under their
|
||||
// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request
|
||||
// path, where it allocated a new string for a compile-time constant on every call, and lets
|
||||
// metadata.Pairs skip its own lower-casing for these keys as well.
|
||||
const xForwardedForKey = "x-forwarded-for"
|
||||
const xForwardedHostKey = "x-forwarded-host"
|
||||
|
||||
// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound
|
||||
// header isn't present. If the value is 0 the sent `context` will not have a timeout.
|
||||
var DefaultContextTimeout = 0 * time.Second
|
||||
@@ -115,10 +107,6 @@ func isValidGRPCMetadataKey(key string) bool {
|
||||
// This means 0-9 a-z _ - .
|
||||
// Only lowercase letters are valid in the wire protocol, but the client library will normalize
|
||||
// uppercase ASCII to lowercase, so uppercase ASCII is also acceptable.
|
||||
// An empty key is not a valid header name, and gRPC fails the call with one.
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode.
|
||||
for _, ch := range bytes {
|
||||
validLowercaseLetter := ch >= 'a' && ch <= 'z'
|
||||
@@ -158,21 +146,7 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
|
||||
}
|
||||
}
|
||||
// Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the
|
||||
// gateway derives below add two more. Sizing for that up front replaces the handful of
|
||||
// reallocations an empty slice goes through while it doubles.
|
||||
pairs := make([]string, 0, 2*(len(req.Header)+2))
|
||||
// For backwards-compatibility, pass through 'authorization' header with no prefix.
|
||||
// It is added before the header loop so that it is always the first
|
||||
// "authorization" value: the loop iterates a map, so a header the matcher
|
||||
// forwards under the same key (Grpc-Metadata-Authorization with the default
|
||||
// matcher) would otherwise land ahead of it in random order, and a backend
|
||||
// reading the first value would get the client-forwarded one.
|
||||
for _, val := range req.Header.Values("Authorization") {
|
||||
if isValidGRPCMetadataTextValue(val) {
|
||||
pairs = append(pairs, "authorization", val)
|
||||
}
|
||||
}
|
||||
var pairs []string
|
||||
for key, vals := range req.Header {
|
||||
key = textproto.CanonicalMIMEHeaderKey(key)
|
||||
switch key {
|
||||
@@ -182,17 +156,11 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
|
||||
for _, val := range vals {
|
||||
// For backwards-compatibility, pass through 'authorization' header with no prefix.
|
||||
if key == "Authorization" {
|
||||
pairs = append(pairs, "authorization", val)
|
||||
}
|
||||
if h, ok := mux.incomingHeaderMatcher(key); ok {
|
||||
// The gateway derives x-forwarded-host and x-forwarded-for below from
|
||||
// the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends
|
||||
// rely on those metadata keys for client host/IP decisions. Refuse a
|
||||
// forwarded header that the matcher strips into one of them (e.g.
|
||||
// Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value
|
||||
// in ahead of the gateway-set one.
|
||||
if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) {
|
||||
grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h)
|
||||
continue
|
||||
}
|
||||
if !isValidGRPCMetadataKey(h) {
|
||||
grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h)
|
||||
continue
|
||||
@@ -214,52 +182,28 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
}
|
||||
}
|
||||
if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) {
|
||||
pairs = append(pairs, xForwardedHostKey, host)
|
||||
} else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) {
|
||||
pairs = append(pairs, xForwardedHostKey, req.Host)
|
||||
if host := req.Header.Get(xForwardedHost); host != "" {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedHost), host)
|
||||
} else if req.Host != "" {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host)
|
||||
}
|
||||
|
||||
// Validate each X-Forwarded-For value on its own, so that an invalid
|
||||
// client-supplied value is dropped without also dropping the remote
|
||||
// address the gateway appends.
|
||||
var xff []string
|
||||
for _, value := range req.Header.Values(xForwardedFor) {
|
||||
if isValidGRPCMetadataTextValue(value) {
|
||||
xff = append(xff, value)
|
||||
}
|
||||
}
|
||||
xff := req.Header.Values(xForwardedFor)
|
||||
if addr := req.RemoteAddr; addr != "" {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
|
||||
xff = append(xff, remoteIP)
|
||||
}
|
||||
}
|
||||
if len(xff) > 0 {
|
||||
pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", "))
|
||||
pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", "))
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
ctx, _ = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
md := metadata.Pairs(pairs...)
|
||||
var annotated metadata.MD
|
||||
for _, mda := range mux.metadataAnnotators {
|
||||
annotated = metadata.Join(annotated, mda(ctx, req))
|
||||
}
|
||||
// Annotators are the gateway's own code, so their values replace whatever
|
||||
// the request headers put under the same key. Joining them after the
|
||||
// header values would let a client send Grpc-Metadata-<key> and have its
|
||||
// value read first by a backend that trusts the annotator.
|
||||
//
|
||||
// With no annotators registered -- the default -- there is nothing to merge, and
|
||||
// metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and
|
||||
// appends every key's values into a fresh slice, so the result is an identical copy of md
|
||||
// bought with one allocation per key.
|
||||
if len(annotated) > 0 {
|
||||
for k := range annotated {
|
||||
delete(md, strings.ToLower(k))
|
||||
}
|
||||
md = metadata.Join(md, annotated)
|
||||
md = metadata.Join(md, mda(ctx, req))
|
||||
}
|
||||
if len(md) == 0 {
|
||||
return ctx, nil, nil
|
||||
@@ -358,16 +302,10 @@ func timeoutDecode(s string) (time.Duration, error) {
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
|
||||
}
|
||||
t, err := strconv.ParseUint(s[:size-1], 10, 64)
|
||||
t, err := strconv.ParseInt(s[:size-1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Guard against overflowing time.Duration, which is an int64 nanosecond
|
||||
// count: without this a large value wraps to a bogus (often negative)
|
||||
// deadline instead of the long timeout the client asked for.
|
||||
if t > uint64(math.MaxInt64)/uint64(d) {
|
||||
return time.Duration(math.MaxInt64), nil
|
||||
}
|
||||
return d * time.Duration(t), nil
|
||||
}
|
||||
|
||||
|
||||
+17
-50
@@ -3,7 +3,6 @@ package runtime
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -45,40 +44,9 @@ func BoolSlice(val, sep string) ([]bool, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// parseFloat parses a floating point value the way the proto3 JSON mapping
|
||||
// does: a decimal number, or the exact strings "Infinity", "-Infinity" and
|
||||
// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"),
|
||||
// underscore digit separators ("1_000") and alternate infinity/NaN spellings
|
||||
// ("Inf", "nan", "infinity"), none of which protojson (and so the request body
|
||||
// and backend) accept. Reject those so a value bound from a query or path
|
||||
// parameter can't differ from the same value sent in the body.
|
||||
func parseFloat(val string, bitSize int) (float64, error) {
|
||||
switch val {
|
||||
case "Infinity":
|
||||
return math.Inf(1), nil
|
||||
case "-Infinity":
|
||||
return math.Inf(-1), nil
|
||||
case "NaN":
|
||||
return math.NaN(), nil
|
||||
}
|
||||
if strings.ContainsAny(val, "xX_") {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
f, err := strconv.ParseFloat(val, bitSize)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// ParseFloat only yields Inf/NaN without an error for the alternate
|
||||
// spellings handled above; overflow returns a range error instead.
|
||||
if math.IsInf(f, 0) || math.IsNaN(f) {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Float64 converts the given string representation into representation of a floating point number into float64.
|
||||
func Float64(val string) (float64, error) {
|
||||
return parseFloat(val, 64)
|
||||
return strconv.ParseFloat(val, 64)
|
||||
}
|
||||
|
||||
// Float64Slice converts 'val' where individual floating point numbers are separated by
|
||||
@@ -98,7 +66,7 @@ func Float64Slice(val, sep string) ([]float64, error) {
|
||||
|
||||
// Float32 converts the given string representation of a floating point number into float32.
|
||||
func Float32(val string) (float32, error) {
|
||||
f, err := parseFloat(val, 32)
|
||||
f, err := strconv.ParseFloat(val, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -122,7 +90,7 @@ func Float32Slice(val, sep string) ([]float32, error) {
|
||||
|
||||
// Int64 converts the given string representation of an integer into int64.
|
||||
func Int64(val string) (int64, error) {
|
||||
return strconv.ParseInt(val, 10, 64)
|
||||
return strconv.ParseInt(val, 0, 64)
|
||||
}
|
||||
|
||||
// Int64Slice converts 'val' where individual integers are separated by
|
||||
@@ -142,7 +110,7 @@ func Int64Slice(val, sep string) ([]int64, error) {
|
||||
|
||||
// Int32 converts the given string representation of an integer into int32.
|
||||
func Int32(val string) (int32, error) {
|
||||
i, err := strconv.ParseInt(val, 10, 32)
|
||||
i, err := strconv.ParseInt(val, 0, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -166,7 +134,7 @@ func Int32Slice(val, sep string) ([]int32, error) {
|
||||
|
||||
// Uint64 converts the given string representation of an integer into uint64.
|
||||
func Uint64(val string) (uint64, error) {
|
||||
return strconv.ParseUint(val, 10, 64)
|
||||
return strconv.ParseUint(val, 0, 64)
|
||||
}
|
||||
|
||||
// Uint64Slice converts 'val' where individual integers are separated by
|
||||
@@ -186,7 +154,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) {
|
||||
|
||||
// Uint32 converts the given string representation of an integer into uint32.
|
||||
func Uint32(val string) (uint32, error) {
|
||||
i, err := strconv.ParseUint(val, 10, 32)
|
||||
i, err := strconv.ParseUint(val, 0, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -208,22 +176,21 @@ func Uint32Slice(val, sep string) ([]uint32, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// Bytes converts the given string representation of a byte sequence into a slice of bytes.
|
||||
// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or
|
||||
// without padding.
|
||||
// Bytes converts the given string representation of a byte sequence into a slice of bytes
|
||||
// A bytes sequence is encoded in URL-safe base64 without padding
|
||||
func Bytes(val string) ([]byte, error) {
|
||||
enc := base64.StdEncoding
|
||||
if strings.ContainsAny(val, "-_") {
|
||||
enc = base64.URLEncoding
|
||||
b, err := base64.StdEncoding.DecodeString(val)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if len(val)%4 != 0 {
|
||||
enc = enc.WithPadding(base64.NoPadding)
|
||||
}
|
||||
return enc.DecodeString(val)
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or
|
||||
// URL-safe base64, are separated by 'sep' into a slice of byte slices.
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe
|
||||
// base64 without padding, are separated by 'sep' into a slice of byte slices.
|
||||
func BytesSlice(val, sep string) ([][]byte, error) {
|
||||
s := strings.Split(val, sep)
|
||||
values := make([][]byte, len(s))
|
||||
|
||||
+1
-2
@@ -134,8 +134,7 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
if s.Code() == codes.Unauthenticated {
|
||||
// Canonical spelling, so Header.Set does not have to build one.
|
||||
w.Header().Set("Www-Authenticate", s.Message())
|
||||
w.Header().Set("WWW-Authenticate", s.Message())
|
||||
}
|
||||
|
||||
buf, merr := marshaler.Marshal(respRw)
|
||||
|
||||
+24
-52
@@ -6,7 +6,6 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
@@ -66,16 +65,14 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
}
|
||||
|
||||
if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
|
||||
vm, _ := v.(map[string]interface{})
|
||||
if _, hasTypeField := vm["@type"]; !hasTypeField {
|
||||
_, hasTypeField := v.(map[string]interface{})["@type"]
|
||||
if hasTypeField {
|
||||
queue = append(queue, fieldMaskPathItem{path: k})
|
||||
continue
|
||||
} else {
|
||||
return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName())
|
||||
}
|
||||
newPath := string(fd.FullName().Name())
|
||||
if item.path != "" {
|
||||
newPath = item.path + "." + newPath
|
||||
}
|
||||
queue = append(queue, fieldMaskPathItem{path: newPath})
|
||||
continue
|
||||
|
||||
}
|
||||
|
||||
child := fieldMaskPathItem{
|
||||
@@ -99,10 +96,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
queue = append(queue, child)
|
||||
}
|
||||
}
|
||||
case ok && len(m) == 0:
|
||||
fallthrough
|
||||
case len(item.path) > 0:
|
||||
// otherwise, it's a leaf node (an empty object counts as one) so
|
||||
// print its path. The root has no path: an empty body such as {}
|
||||
// sets nothing, and an empty path is not a valid FieldMask path.
|
||||
// otherwise, it's a leaf node so print its path
|
||||
fm.Paths = append(fm.Paths, item.path)
|
||||
}
|
||||
}
|
||||
@@ -129,55 +126,30 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool {
|
||||
// passed in name and json value.
|
||||
func buildPathsBlindly(name string, in interface{}) []string {
|
||||
m, ok := in.(map[string]interface{})
|
||||
if !ok || len(m) == 0 {
|
||||
if !ok {
|
||||
return []string{name}
|
||||
}
|
||||
|
||||
// A google.protobuf.Struct/Value field carries arbitrary client JSON, so
|
||||
// its nesting depth is attacker controlled. Keep each queue entry pointing
|
||||
// at its parent and its own segment rather than carrying the full path
|
||||
// string, so a path is concatenated once at the leaf (O(depth)) instead of
|
||||
// rebuilding the growing prefix at every level (O(depth^2)). A deeply
|
||||
// nested object otherwise makes this allocate quadratically in the depth
|
||||
// while producing only a handful of paths.
|
||||
type pathNode struct {
|
||||
parent *pathNode
|
||||
segment string
|
||||
}
|
||||
type queueItem struct {
|
||||
path *pathNode
|
||||
node map[string]any
|
||||
}
|
||||
|
||||
var paths []string
|
||||
queue := []queueItem{{path: &pathNode{segment: name}, node: m}}
|
||||
queue := []fieldMaskPathItem{{path: name, node: m}}
|
||||
for len(queue) > 0 {
|
||||
cur := queue[0]
|
||||
queue = queue[1:]
|
||||
|
||||
for k, v := range cur.node {
|
||||
child := &pathNode{parent: cur.path, segment: k}
|
||||
if mi, ok := v.(map[string]any); ok && len(mi) > 0 {
|
||||
queue = append(queue, queueItem{path: child, node: mi})
|
||||
continue
|
||||
m, ok := cur.node.(map[string]interface{})
|
||||
if !ok {
|
||||
// This should never happen since we should always check that we only add
|
||||
// nodes of type map[string]interface{} to the queue.
|
||||
continue
|
||||
}
|
||||
for k, v := range m {
|
||||
if mi, ok := v.(map[string]interface{}); ok {
|
||||
queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi})
|
||||
} else {
|
||||
// This is not a struct, so there are no more levels to descend.
|
||||
curPath := cur.path + "." + k
|
||||
paths = append(paths, curPath)
|
||||
}
|
||||
// No populated object remains, so there are no more levels to
|
||||
// descend. Walk back to the root to materialize the path once.
|
||||
var segments []string
|
||||
n := 0
|
||||
for p := child; p != nil; p = p.parent {
|
||||
segments = append(segments, p.segment)
|
||||
n += len(p.segment) + 1
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(n - 1)
|
||||
for i := len(segments) - 1; i >= 0; i-- {
|
||||
b.WriteString(segments[i])
|
||||
if i > 0 {
|
||||
b.WriteByte('.')
|
||||
}
|
||||
}
|
||||
paths = append(paths, b.String())
|
||||
}
|
||||
}
|
||||
return paths
|
||||
|
||||
+1
-4
@@ -210,10 +210,7 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
|
||||
}
|
||||
|
||||
func requestAcceptsTrailers(req *http.Request) bool {
|
||||
// "Te", not "TE": Header.Get canonicalises the key it is given, and a key that is already
|
||||
// canonical is returned as is, while any other spelling costs an allocated copy on every
|
||||
// call. This one runs once per response.
|
||||
te := req.Header.Get("Te")
|
||||
te := req.Header.Get("TE")
|
||||
return strings.Contains(strings.ToLower(te), "trailers")
|
||||
}
|
||||
|
||||
|
||||
+2
-98
@@ -5,13 +5,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
)
|
||||
|
||||
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
|
||||
@@ -32,21 +30,6 @@ func (*JSONPb) ContentType(_ interface{}) string {
|
||||
|
||||
// Marshal marshals "v" into JSON.
|
||||
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
|
||||
if p, ok := v.(proto.Message); ok {
|
||||
// protojson already returns a freshly allocated slice that the caller owns, so
|
||||
// routing it through a bytes.Buffer only added an allocation and a copy of the
|
||||
// whole message per call. Every unary response goes through here.
|
||||
//
|
||||
// The error is returned with a nil slice rather than whatever protojson produced
|
||||
// alongside it, matching what the bytes.Buffer path did: marshalTo returned before
|
||||
// writing anything, so a failed Marshal never handed back partial output.
|
||||
b, err := j.MarshalOptions.Marshal(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := j.marshalTo(&buf, v); err != nil {
|
||||
return nil, err
|
||||
@@ -268,36 +251,18 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
|
||||
}
|
||||
|
||||
var raw json.RawMessage
|
||||
if err := d.Decode(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
m := make(map[string]*json.RawMessage)
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
if err := d.Decode(&m); err != nil {
|
||||
return err
|
||||
}
|
||||
// encoding/json keeps the last value of a repeated key, while protojson
|
||||
// rejects a duplicate map key, also when two spellings convert to the
|
||||
// same key (e.g. "1" and "01"). Reject both here too.
|
||||
if k, ok := duplicateObjectKey(raw); ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen := make(map[any]struct{}, len(m))
|
||||
for k, v := range m {
|
||||
result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
|
||||
if err := result[1].Interface(); err != nil {
|
||||
return err.(error)
|
||||
}
|
||||
bk := result[0]
|
||||
if _, ok := seen[bk.Interface()]; ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen[bk.Interface()] = struct{}{}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if v == nil {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
null := json.RawMessage("null")
|
||||
v = &null
|
||||
}
|
||||
@@ -328,11 +293,6 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
|
||||
}
|
||||
for _, item := range sl {
|
||||
if string(item) == "null" {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
|
||||
return err
|
||||
@@ -348,30 +308,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
}
|
||||
switch v := repr.(type) {
|
||||
case string:
|
||||
// protojson writes enums by name, so accept the name here too.
|
||||
if e, ok := rv.Interface().(protoreflect.Enum); ok {
|
||||
if ev := e.Descriptor().Values().ByName(protoreflect.Name(v)); ev != nil {
|
||||
rv.SetInt(int64(ev.Number()))
|
||||
return nil
|
||||
}
|
||||
if unmarshaler.DiscardUnknown {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value %q for enum %s", v, e.Descriptor().FullName())
|
||||
}
|
||||
// TODO(yugui) Should use proto.StructProperties?
|
||||
return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
|
||||
case float64:
|
||||
// Enum values are int32 on the wire. A fractional or out-of-range
|
||||
// number would otherwise be silently truncated/wrapped into a bogus
|
||||
// enum here, unlike protojson which rejects it, so reject it too.
|
||||
if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 {
|
||||
return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface())
|
||||
}
|
||||
rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
|
||||
return nil
|
||||
case nil:
|
||||
// protojson leaves a null enum field unset.
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
|
||||
}
|
||||
@@ -379,43 +320,6 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
// rejectNullEnumItem returns an error when t is an enum other than
|
||||
// google.protobuf.NullValue. protojson leaves a null enum field unset, but
|
||||
// rejects null as a list item or map value of such an enum.
|
||||
func rejectNullEnumItem(t reflect.Type) error {
|
||||
e, ok := reflect.Zero(t).Interface().(protoreflect.Enum)
|
||||
if !ok || e.Descriptor().FullName() == "google.protobuf.NullValue" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value null for enum %s", e.Descriptor().FullName())
|
||||
}
|
||||
|
||||
// duplicateObjectKey returns the first key that appears more than once in the
|
||||
// JSON object in data.
|
||||
func duplicateObjectKey(data []byte) (string, bool) {
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
if t, err := d.Token(); err != nil || t != json.Delim('{') {
|
||||
return "", false
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
for d.More() {
|
||||
t, err := d.Token()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
k, _ := t.(string)
|
||||
if _, ok := seen[k]; ok {
|
||||
return k, true
|
||||
}
|
||||
seen[k] = struct{}{}
|
||||
var v json.RawMessage
|
||||
if err := d.Decode(&v); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
type protoEnum interface {
|
||||
fmt.Stringer
|
||||
EnumDescriptor() ([]byte, []int)
|
||||
|
||||
-7
@@ -40,13 +40,6 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ReadAll drains the reader, so a call with nothing left to read has
|
||||
// to report io.EOF like the other decoders. Otherwise it decodes an
|
||||
// empty message every time, and a loop decoding until io.EOF, such as
|
||||
// the generated client streaming handlers, never terminates.
|
||||
if len(buffer) == 0 {
|
||||
return io.EOF
|
||||
}
|
||||
return marshaller.Unmarshal(buffer, value)
|
||||
})
|
||||
}
|
||||
|
||||
-12
@@ -44,18 +44,6 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out
|
||||
}
|
||||
|
||||
for _, contentTypeVal := range r.Header[contentTypeHeader] {
|
||||
// A header that is already exactly a registered media type -- "application/json",
|
||||
// which is what clients send -- needs no parsing. mime.ParseMediaType allocates a
|
||||
// parameter map even when the value carries no parameters, and it would return this
|
||||
// value unchanged, so the lookup below would be the same one.
|
||||
//
|
||||
// This is also what the Accept loop above already does: the registry is keyed by the
|
||||
// strings passed to WithMarshalerOption, and that loop matches the header value
|
||||
// against them directly.
|
||||
if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok {
|
||||
inbound = m
|
||||
break
|
||||
}
|
||||
contentType, _, err := mime.ParseMediaType(contentTypeVal)
|
||||
if err != nil {
|
||||
grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err)
|
||||
|
||||
+24
-129
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
@@ -45,9 +44,7 @@ const (
|
||||
UnescapingModeDefault = UnescapingModeLegacy
|
||||
)
|
||||
|
||||
// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an
|
||||
// escaped path separator has to be recognized in either spelling.
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])")
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2F)")
|
||||
|
||||
// A HandlerFunc handles a specific pair of path pattern and HTTP method.
|
||||
type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)
|
||||
@@ -78,7 +75,6 @@ type ServeMux struct {
|
||||
unescapingMode UnescapingMode
|
||||
writeContentLength bool
|
||||
disableChunkedEncoding bool
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// ServeMuxOption is an option that can be given to a ServeMux on construction.
|
||||
@@ -141,19 +137,6 @@ func WithDisableChunkedEncoding() ServeMuxOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least
|
||||
// one path segment when preceded by another segment. For example,
|
||||
// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still
|
||||
// provides an empty segment, so "/v3/files/" continues to match.
|
||||
//
|
||||
// This option applies to all patterns registered with the ServeMux, including
|
||||
// generated routes and routes registered with HandlePath.
|
||||
func WithStrictDeepWildcardMatching() ServeMuxOption {
|
||||
return func(mux *ServeMux) {
|
||||
mux.strictDeepWildcard = true
|
||||
}
|
||||
}
|
||||
|
||||
// SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters.
|
||||
// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be
|
||||
// done with careful consideration.
|
||||
@@ -168,55 +151,24 @@ type HeaderMatcherFunc func(string) (string, bool)
|
||||
|
||||
// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header
|
||||
// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function.
|
||||
// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
|
||||
// Other headers are not added to the gRPC metadata.
|
||||
//
|
||||
// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the
|
||||
// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an
|
||||
// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the
|
||||
// WithLegacyHeaderMatching option, to keep forwarding those headers.
|
||||
func DefaultHeaderMatcher(key string) (string, bool) {
|
||||
if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) {
|
||||
return MetadataPrefix + key, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the
|
||||
// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped
|
||||
// to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
|
||||
//
|
||||
// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for
|
||||
// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway.
|
||||
func LegacyHeaderMatcher(key string) (string, bool) {
|
||||
switch key = textproto.CanonicalMIMEHeaderKey(key); {
|
||||
case isPermanentHTTPHeader(key):
|
||||
return MetadataPrefix + key, true
|
||||
case strings.HasPrefix(key, MetadataHeaderPrefix):
|
||||
mdKey := key[len(MetadataHeaderPrefix):]
|
||||
// The grpcgateway- namespace is reserved for permanent HTTP headers the
|
||||
// gateway maps itself, so refuse to forward a Grpc-Metadata- header that
|
||||
// strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client
|
||||
// inject a value indistinguishable from the gateway-set grpcgateway-host.
|
||||
if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) {
|
||||
return "", false
|
||||
}
|
||||
return mdKey, true
|
||||
return key[len(MetadataHeaderPrefix):], true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header
|
||||
// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again.
|
||||
func WithLegacyHeaderMatching() ServeMuxOption {
|
||||
return WithIncomingHeaderMatcher(LegacyHeaderMatcher)
|
||||
}
|
||||
|
||||
func defaultOutgoingHeaderMatcher(key string) (string, bool) {
|
||||
return MetadataHeaderPrefix + key, true
|
||||
return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true
|
||||
}
|
||||
|
||||
func defaultOutgoingTrailerMatcher(key string) (string, bool) {
|
||||
return MetadataTrailerPrefix + key, true
|
||||
return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true
|
||||
}
|
||||
|
||||
// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.
|
||||
@@ -424,28 +376,15 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux {
|
||||
serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher
|
||||
}
|
||||
|
||||
// Options such as WithHealthEndpointAt register handlers while the options
|
||||
// are still being applied, so they were wrapped with only the middlewares
|
||||
// configured before them. Rewrap them now that all middlewares are known.
|
||||
if len(serveMux.middlewares) > 0 {
|
||||
chain := chainMiddlewares(serveMux.middlewares)
|
||||
for _, handlers := range serveMux.handlers {
|
||||
for i := range handlers {
|
||||
handlers[i].h = chain(handlers[i].raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return serveMux
|
||||
}
|
||||
|
||||
// Handle associates "h" to the pair of HTTP method and path pattern.
|
||||
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
|
||||
raw := h
|
||||
if len(s.middlewares) > 0 {
|
||||
h = chainMiddlewares(s.middlewares)(h)
|
||||
}
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...)
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...)
|
||||
}
|
||||
|
||||
// HandlePath allows users to configure custom path handlers.
|
||||
@@ -476,22 +415,11 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// TODO(v3): remove UnescapingModeLegacy
|
||||
unescapingMode := s.unescapingMode
|
||||
if unescapingMode != UnescapingModeLegacy {
|
||||
if r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
} else {
|
||||
// net/url only sets RawPath when the request path is not in its
|
||||
// default encoding. Without it, Path is all there is and it has
|
||||
// already been unescaped once, so unescaping it again while matching
|
||||
// would decode a sequence like %252F twice.
|
||||
unescapingMode = UnescapingModeLegacy
|
||||
}
|
||||
if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
}
|
||||
|
||||
// "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a
|
||||
// canonicalised copy of any other, and this lookup happens on every request.
|
||||
if override := r.Header.Get("X-Http-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
|
||||
if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
sterr := status.Error(codes.InvalidArgument, err.Error())
|
||||
@@ -506,7 +434,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the
|
||||
// path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default
|
||||
// behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved
|
||||
if unescapingMode == UnescapingModeAllCharacters {
|
||||
if s.unescapingMode == UnescapingModeAllCharacters {
|
||||
pathComponents = encodedPathSplitter.Split(path[1:], -1)
|
||||
} else {
|
||||
pathComponents = strings.Split(path[1:], "/")
|
||||
@@ -532,33 +460,20 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
if idx == 0 {
|
||||
// The last component is the bare verb with nothing before it,
|
||||
// which this pattern cannot match. Other patterns still might, so
|
||||
// move on rather than ending the search with a 404.
|
||||
continue
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Only copy the components when the verb has to be split off the last
|
||||
// one. MatchAndEscape never mutates its input, so sharing the slice
|
||||
// across handlers is safe, and copying it per handler otherwise costs
|
||||
// len(pathComponents) allocations for every registered pattern.
|
||||
comps := pathComponents
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
if err != nil {
|
||||
// ErrNotMatch is returned once for every registered pattern the request does not
|
||||
// match, so it is by far the most common error reaching this branch. Checking it
|
||||
// first keeps errors.As off that path: its target parameter is an any, so &mse is
|
||||
// boxed onto the heap on every call -- one allocation per route a request did not
|
||||
// match, which grows with the number of registered routes.
|
||||
if errors.Is(err, ErrNotMatch) {
|
||||
continue
|
||||
}
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
@@ -580,24 +495,11 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// Note we are not eagerly checking the request here as we want to return the
|
||||
// right HTTP status code, and we need to process the fallback candidates in
|
||||
// order to do that.
|
||||
// GET is tried first when the request is subject to path length fallback:
|
||||
// map iteration order is random, and a match for another method would
|
||||
// otherwise return 405 before the GET handler is reached.
|
||||
methods := make([]string, 0, len(s.handlers))
|
||||
if s.isPathLengthFallback(r) {
|
||||
methods = append(methods, http.MethodGet)
|
||||
}
|
||||
for m := range s.handlers {
|
||||
if m == http.MethodGet && s.isPathLengthFallback(r) {
|
||||
continue
|
||||
}
|
||||
methods = append(methods, m)
|
||||
}
|
||||
for _, m := range methods {
|
||||
for m, handlers := range s.handlers {
|
||||
if m == r.Method {
|
||||
continue
|
||||
}
|
||||
for _, h := range s.handlers[m] {
|
||||
for _, h := range handlers {
|
||||
var verb string
|
||||
patVerb := h.pat.Verb()
|
||||
|
||||
@@ -606,14 +508,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
|
||||
comps := pathComponents
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
if err != nil {
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
@@ -656,19 +558,12 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp
|
||||
}
|
||||
|
||||
func (s *ServeMux) isPathLengthFallback(r *http.Request) bool {
|
||||
if s.disablePathLengthFallback || r.Method != http.MethodPost {
|
||||
return false
|
||||
}
|
||||
// Like net/http's ParseForm, ignore parameters such as charset.
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
return err == nil && mediaType == "application/x-www-form-urlencoded"
|
||||
return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
pat Pattern
|
||||
h HandlerFunc
|
||||
// raw is h before middlewares were applied.
|
||||
raw HandlerFunc
|
||||
}
|
||||
|
||||
func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
|
||||
|
||||
+5
-83
@@ -26,9 +26,6 @@ func (e MalformedSequenceError) Error() string {
|
||||
type op struct {
|
||||
code utilities.OpCode
|
||||
operand int
|
||||
// multisegment is set on an OpPush that is one segment of a variable
|
||||
// spanning several segments, such as the "*" in {name=shelves/*}.
|
||||
multisegment bool
|
||||
}
|
||||
|
||||
// Pattern is a template pattern of http request paths defined in
|
||||
@@ -46,20 +43,6 @@ type Pattern struct {
|
||||
tailLen int
|
||||
// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
|
||||
verb string
|
||||
// strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one
|
||||
// remaining path component.
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// PatternOpt configures optional behavior of a Pattern.
|
||||
type PatternOpt func(*Pattern)
|
||||
|
||||
// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another
|
||||
// segment refuse to match zero path segments. For example, "/v3/files/{path=**}"
|
||||
// will not match "/v3/files". A bare "**" with nothing preceding it still matches
|
||||
// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
func WithStrictDeepWildcard() PatternOpt {
|
||||
return func(p *Pattern) { p.strictDeepWildcard = true }
|
||||
}
|
||||
|
||||
// NewPattern returns a new Pattern from the given definition values.
|
||||
@@ -68,12 +51,6 @@ func WithStrictDeepWildcard() PatternOpt {
|
||||
// "version" must be 1 for now.
|
||||
// It returns an error if the given definition is invalid.
|
||||
func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) {
|
||||
return NewPatternWithOptions(version, ops, pool, verb)
|
||||
}
|
||||
|
||||
// NewPatternWithOptions is like NewPattern but additionally accepts options that modify
|
||||
// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard.
|
||||
func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) {
|
||||
if version != 1 {
|
||||
grpclog.Errorf("unsupported version: %d", version)
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
@@ -129,15 +106,6 @@ func NewPatternWithOptions(version int, ops []int, pool []string, verb string, o
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
}
|
||||
stack++
|
||||
// The segments of a variable are the ops pushed right before its
|
||||
// OpConcatN, so these are the ones of a multi-segment variable.
|
||||
if op.operand > 1 {
|
||||
for j := len(typedOps) - op.operand; j < len(typedOps); j++ {
|
||||
if typedOps[j].code == utilities.OpPush {
|
||||
typedOps[j].multisegment = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case utilities.OpCapture:
|
||||
if op.operand < 0 || len(pool) <= op.operand {
|
||||
grpclog.Errorf("variable name index out of bound: %d", op.operand)
|
||||
@@ -161,18 +129,14 @@ func NewPatternWithOptions(version int, ops []int, pool []string, verb string, o
|
||||
}
|
||||
typedOps = append(typedOps, op)
|
||||
}
|
||||
pat := Pattern{
|
||||
return Pattern{
|
||||
ops: typedOps,
|
||||
pool: pool,
|
||||
vars: vars,
|
||||
stacksize: maxstack,
|
||||
tailLen: tailLen,
|
||||
verb: verb,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(&pat)
|
||||
}
|
||||
return pat, nil
|
||||
}, nil
|
||||
}
|
||||
|
||||
// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.
|
||||
@@ -188,10 +152,6 @@ func MustPattern(p Pattern, err error) Pattern {
|
||||
// matched but contained malformed escape sequences. If successful, the function
|
||||
// returns a mapping from field paths to their captured values.
|
||||
func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) {
|
||||
return p.matchAndEscape(components, verb, unescapingMode, false)
|
||||
}
|
||||
|
||||
func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) {
|
||||
if p.verb != verb {
|
||||
if p.verb != "" {
|
||||
return nil, ErrNotMatch
|
||||
@@ -205,29 +165,8 @@ func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode
|
||||
}
|
||||
|
||||
var pos int
|
||||
|
||||
// Scratch space for the match. Neither backing array escapes -- only the individual
|
||||
// strings they hold are copied into the returned bindings -- so fixed-size arrays keep
|
||||
// both off the heap for the patterns generated code registers, where the stack size and
|
||||
// the variable count are single digits.
|
||||
//
|
||||
// This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per
|
||||
// registered pattern until one matches, and both allocations happened before the
|
||||
// non-match return below, so a request paid for them once for every route it did not
|
||||
// match. With a few dozen routes registered that was the largest single source of
|
||||
// allocations in routing.
|
||||
var stackArr, capturedArr [8]string
|
||||
stack := stackArr[:0]
|
||||
if p.stacksize > len(stackArr) {
|
||||
stack = make([]string, 0, p.stacksize)
|
||||
}
|
||||
var captured []string
|
||||
if n := len(p.vars); n <= len(capturedArr) {
|
||||
captured = capturedArr[:n]
|
||||
} else {
|
||||
captured = make([]string, n)
|
||||
}
|
||||
|
||||
stack := make([]string, 0, p.stacksize)
|
||||
captured := make([]string, len(p.vars))
|
||||
l := len(components)
|
||||
for _, op := range p.ops {
|
||||
var err error
|
||||
@@ -245,14 +184,7 @@ func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
} else if op.code == utilities.OpPush {
|
||||
// google.api.http decodes a variable spanning several segments
|
||||
// "except %2F and %2f", so a "*" in it can't add a path separator
|
||||
// to the bound value. Other escapes are decoded as for {var}.
|
||||
mode := unescapingMode
|
||||
if op.multisegment && mode == UnescapingModeAllExceptReserved {
|
||||
mode = UnescapingModeAllExceptSlash
|
||||
}
|
||||
if c, err = unescape(c, mode, op.multisegment); err != nil {
|
||||
if c, err = unescape(c, unescapingMode, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -264,16 +196,6 @@ func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
end -= p.tailLen
|
||||
if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end {
|
||||
// A deep wildcard ("**") is allowed to match zero path segments when it is
|
||||
// the first thing being matched in the pattern (pos == 0). But once a literal
|
||||
// or variable segment has already consumed a component, "**" needs the request
|
||||
// path to continue past that segment — it cannot succeed with nothing left to
|
||||
// consume at all (though an empty trailing segment, e.g. from a trailing slash,
|
||||
// still counts as a real component and is fine).
|
||||
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
c := strings.Join(components[pos:end], "/")
|
||||
if c, err = unescape(c, unescapingMode, true); err != nil {
|
||||
return nil, err
|
||||
|
||||
+17
-145
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -15,41 +16,13 @@ import (
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/reflect/protoregistry"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
field_mask "google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
// splitMapKey splits a query parameter name of the form "field[key]" into the part before the
|
||||
// bracket and the key inside it, reporting whether the name has that shape at all.
|
||||
//
|
||||
// This replaces a FindStringSubmatch against `^(.*)\[(.*)\]$`, which ran for every query
|
||||
// parameter and cost two allocations each -- the submatch slice and the backtracker's state --
|
||||
// to answer a question that is two index operations. The returned strings are slices of the
|
||||
// caller's key, so nothing is copied; the caller rebuilds "[key]" as key[len(prefix):] rather
|
||||
// than concatenating it back together.
|
||||
//
|
||||
// The regexp is matched exactly, including two details worth spelling out:
|
||||
//
|
||||
// - The first group is greedy, so the bracket that counts is the last one before the final
|
||||
// "]". "a[b]c]" splits into "a" and "b]c", which is what LastIndexByte over everything but
|
||||
// the final byte finds.
|
||||
// - Go's regexp does not let "." match a newline and anchors ^ and $ at the ends of the text,
|
||||
// so a key containing a newline could never match the pattern no matter where the brackets
|
||||
// sat. The explicit newline check keeps that, rather than quietly starting to treat
|
||||
// "a\n[b]" as a map key.
|
||||
func splitMapKey(key string) (prefix, inner string, ok bool) {
|
||||
if len(key) < 2 || key[len(key)-1] != ']' || strings.IndexByte(key, '\n') >= 0 {
|
||||
return "", "", false
|
||||
}
|
||||
open := strings.LastIndexByte(key[:len(key)-1], '[')
|
||||
if open < 0 {
|
||||
return "", "", false
|
||||
}
|
||||
return key[:open], key[open+1 : len(key)-1], true
|
||||
}
|
||||
var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`)
|
||||
|
||||
var currentQueryParser QueryParameterParser = &DefaultQueryParser{}
|
||||
|
||||
@@ -71,67 +44,30 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili
|
||||
type DefaultQueryParser struct{}
|
||||
|
||||
// Parse populates "values" into "msg".
|
||||
// A value is ignored if its key starts with one of the elements in "filter",
|
||||
// or names a field that contains one of them.
|
||||
// A value is ignored if its key starts with one of the elements in "filter".
|
||||
func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
|
||||
// A field is addressable by both its proto name and its JSON name, so two
|
||||
// keys can set the same one. Record which fields have been set and refuse a
|
||||
// second key for a field, the way protojson refuses a duplicate field in a
|
||||
// body, instead of letting map iteration order pick the value that survives.
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for key, values := range values {
|
||||
fieldKey, mapKey := key, ""
|
||||
if prefix, inner, ok := splitMapKey(key); ok {
|
||||
fieldKey, mapKey = prefix, key[len(prefix):]
|
||||
values = append([]string{inner}, values...)
|
||||
if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 {
|
||||
key = match[1]
|
||||
values = append([]string{match[2]}, values...)
|
||||
}
|
||||
|
||||
msgValue := msg.ProtoReflect()
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) {
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(key, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) {
|
||||
continue
|
||||
}
|
||||
field := strings.Join(fieldPath, ".") + mapKey
|
||||
if _, ok := seen[field]; ok {
|
||||
return fmt.Errorf("duplicate field %q", field)
|
||||
}
|
||||
seen[field] = struct{}{}
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil {
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// containsFilteredField reports whether fieldPath names a field that contains
|
||||
// one of the sequences in filter, such as "id" for a path parameter bound to
|
||||
// "id.value". Setting such a field from the query, which the parser can do for
|
||||
// well-known types like wrappers and timestamps, would replace the whole
|
||||
// message and with it the value already bound from the path or body.
|
||||
func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool {
|
||||
if len(filter.Base) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
var i int
|
||||
for _, t := range fieldPath {
|
||||
code, ok := filter.Encoding[t]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
j := filter.Base[i] + code
|
||||
if len(filter.Check) <= j || filter.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// PopulateFieldFromPath sets a value in a nested Protobuf structure.
|
||||
func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error {
|
||||
fieldPath := strings.Split(fieldPathString, ".")
|
||||
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false)
|
||||
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value})
|
||||
}
|
||||
|
||||
func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string {
|
||||
@@ -166,7 +102,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str
|
||||
return newFieldPath
|
||||
}
|
||||
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error {
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error {
|
||||
if len(fieldPath) < 1 {
|
||||
return errors.New("no field path")
|
||||
}
|
||||
@@ -213,18 +149,6 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin
|
||||
msgValue = msgValue.Mutable(fieldDescriptor).Message()
|
||||
}
|
||||
|
||||
// A key using the map syntax (field[key]=value) must name a map field,
|
||||
// or a repeated field of key/value messages laid out like map entries.
|
||||
// Otherwise the bracket content would be bound as if it were a regular
|
||||
// value: appended as a phantom element of a repeated field, or counted
|
||||
// as a second value for a singular one.
|
||||
if hasMapKey && !fieldDescriptor.IsMap() {
|
||||
if isKeyValueList(fieldDescriptor) {
|
||||
return populateKeyValueListField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
}
|
||||
return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name())
|
||||
}
|
||||
|
||||
switch {
|
||||
case fieldDescriptor.IsList():
|
||||
return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
@@ -281,48 +205,6 @@ func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protorefl
|
||||
return nil
|
||||
}
|
||||
|
||||
// isKeyValueList reports whether fieldDescriptor is a repeated message field
|
||||
// whose message has exactly a singular "key" and a singular "value" field.
|
||||
// Such a field is shaped like a map entry list, but can hold more than one
|
||||
// value for a key.
|
||||
func isKeyValueList(fieldDescriptor protoreflect.FieldDescriptor) bool {
|
||||
if !fieldDescriptor.IsList() || fieldDescriptor.Message() == nil {
|
||||
return false
|
||||
}
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
if fields.Len() != 2 {
|
||||
return false
|
||||
}
|
||||
key, value := fields.ByName("key"), fields.ByName("value")
|
||||
return key != nil && key.Cardinality() != protoreflect.Repeated &&
|
||||
value != nil && value.Cardinality() != protoreflect.Repeated
|
||||
}
|
||||
|
||||
// populateKeyValueListField appends one key/value message to list for each of
|
||||
// values[1:], all with the key values[0].
|
||||
func populateKeyValueListField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error {
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
keyField, valueField := fields.ByName("key"), fields.ByName("value")
|
||||
|
||||
key, err := parseField(keyField, values[0])
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
|
||||
for _, value := range values[1:] {
|
||||
v, err := parseField(valueField, value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
entry := list.NewElement()
|
||||
entry.Message().Set(keyField, key)
|
||||
entry.Message().Set(valueField, v)
|
||||
list.Append(entry)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) {
|
||||
switch fieldDescriptor.Kind() {
|
||||
case protoreflect.BoolKind:
|
||||
@@ -342,7 +224,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
// Look for enum by name
|
||||
v := enum.Descriptor().Values().ByName(protoreflect.Name(value))
|
||||
if v == nil {
|
||||
i, err := strconv.ParseInt(value, 10, 32)
|
||||
i, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value)
|
||||
}
|
||||
@@ -377,13 +259,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
}
|
||||
return protoreflect.ValueOfUint64(v), nil
|
||||
case protoreflect.FloatKind:
|
||||
v, err := parseFloat(value, 32)
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
return protoreflect.ValueOfFloat32(float32(v)), nil
|
||||
case protoreflect.DoubleKind:
|
||||
v, err := parseFloat(value, 64)
|
||||
v, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -423,13 +305,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
}
|
||||
msg = durationpb.New(d)
|
||||
case "google.protobuf.DoubleValue":
|
||||
v, err := parseFloat(value, 64)
|
||||
v, err := strconv.ParseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = wrapperspb.Double(v)
|
||||
case "google.protobuf.FloatValue":
|
||||
v, err := parseFloat(value, 32)
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -474,9 +356,7 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
msg = wrapperspb.Bytes(v)
|
||||
case "google.protobuf.FieldMask":
|
||||
fm := &field_mask.FieldMask{}
|
||||
if value != "" {
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
}
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
msg = fm
|
||||
case "google.protobuf.Value":
|
||||
var v structpb.Value
|
||||
@@ -490,14 +370,6 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = &v
|
||||
case "google.protobuf.Empty":
|
||||
// An Empty carries nothing, so the only thing the value can say is that the
|
||||
// field is present. Accept the two spellings of "no content" and reject
|
||||
// anything else, rather than silently ignoring it.
|
||||
if value != "" && value != "{}" {
|
||||
return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value)
|
||||
}
|
||||
msg = &emptypb.Empty{}
|
||||
default:
|
||||
return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName()))
|
||||
}
|
||||
|
||||
+4
-12
@@ -72,7 +72,6 @@ func (n node) children(seqs [][]int) []*node {
|
||||
if lastVal == seqs[i][n.col+1] {
|
||||
continue
|
||||
}
|
||||
lastVal = seqs[i][n.col+1]
|
||||
last.right = i
|
||||
last = &node{
|
||||
row: i,
|
||||
@@ -157,11 +156,6 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
|
||||
var i int
|
||||
for _, t := range seq {
|
||||
// A sequence ending at this node is already a prefix of seq, even if
|
||||
// a longer sequence shares the path and the walk could carry on.
|
||||
if da.hasTerminator(i) {
|
||||
return true
|
||||
}
|
||||
code, ok := da.Encoding[t]
|
||||
if !ok {
|
||||
break
|
||||
@@ -172,11 +166,9 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return da.hasTerminator(i)
|
||||
}
|
||||
|
||||
// hasTerminator reports whether a sequence in the DoubleArray ends at node i.
|
||||
func (da *DoubleArray) hasTerminator(i int) bool {
|
||||
j := da.Base[i] + len(da.Encoding)
|
||||
return j < len(da.Check) && da.Check[j] == i+1
|
||||
if len(da.Check) <= j || da.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
Loaded 100 of 725 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user