Compare commits

..
18 Commits
Author SHA1 Message Date
chashintv e2af9c4978 MSP-8974 fix 2026-11-23 13:27:39 +03:00
chashintv 24a8ea2578 MSP-8974 fix 2026-11-23 13:00:25 +03:00
chashintv ebc99c6ae4 MSP-8974 remove unused structs 2026-11-23 13:00:03 +03:00
chashintv 7bac2e403f MSP-8974 review fixes 2026-11-23 13:00:03 +03:00
chashintv 1ea3ef186c MSP-8974 up swagger 2026-11-23 13:00:03 +03:00
chashintv 1d1c5dbde6 MSP-8974 lint fixes 2026-11-23 13:00:03 +03:00
chashintv 11ef48bbeb MSP-8974 up deps 2026-11-23 13:00:01 +03:00
chashintv 5263e1504d MSP-8974 Bump version to 7.2.0 2026-11-23 12:59:29 +03:00
chashintv 06acaba5b3 MSP-8974 add download flow test 2026-11-23 12:58:54 +03:00
chashintv 2f29af5e76 MSP-8974 update doc 2026-11-23 12:58:54 +03:00
chashintv 3e707244dd MSP-8974 fix tests for http 2026-11-23 12:58:51 +03:00
chashintv fa8bc6c1b7 MSP-8974 fix tests 2026-11-23 12:58:04 +03:00
chashintv 71498785ea MSP-8974 add download flow, server migration to http 2026-11-23 12:54:59 +03:00
Иван Перлов aa68f6028a Merge branch 'MSP-8976' into 'dev'
Resolve MSP-8976

See merge request isp/isp-admin-service!5
2026-11-20 17:23:21 +03:00
Иван Перлов 11d705124d MSP-8976 Up deps 2026-11-20 17:19:44 +03:00
Иван Перлов b8ef777339 MSP-8976 Bump version to 7.2.0 2026-11-20 17:19:44 +03:00
Иван Перлов 7589203719 MSP-8976 Add application_group field and filter 2026-11-20 17:19:38 +03:00
Иван Перлов 67e9b563b4 MSP-8976 Up Go version to 1.27, linter conf 2026-11-18 16:02:49 +03:00
724 changed files with 54131 additions and 17996 deletions

No files matched your search

+3 -3
View File
@@ -21,6 +21,7 @@ linters:
- godoclint # ругается на // nolint, не удобно - godoclint # ругается на // nolint, не удобно
- prealloc # слишком аггресивный, в большинстве случаев не требуется - prealloc # слишком аггресивный, в большинстве случаев не требуется
- gomodguard # deprecated - gomodguard # deprecated
- goconst # слишком агрессивный
settings: settings:
exhaustruct_v5: exhaustruct_v5:
allow-empty: true allow-empty: true
@@ -29,8 +30,6 @@ linters:
max-complexity: 15 # по умолчанию 10 мало max-complexity: 15 # по умолчанию 10 мало
funlen: funlen:
lines: 80 lines: 80
goconst:
ignore-tests: true # тестовые фикстуры не выносим в константы
lll: lll:
line-length: 150 line-length: 150
revive: revive:
@@ -81,4 +80,5 @@ formatters:
paths: paths:
- third_party$ - third_party$
- builtin$ - builtin$
- examples$ - examples$
+1 -1
View File
@@ -1 +1 @@
7.1.0 7.2.0
+5
View File
@@ -1,3 +1,8 @@
### v7.2.0
* Добавлено поле `application_group` в таблицу `roles`
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
* Добавлена возможность скачивания и формирования CSV
### v7.1.0 ### v7.1.0
* переименование авторизации через SUDIR в OAuth: * переименование авторизации через SUDIR в OAuth:
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth` * Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
+5 -5
View File
@@ -16,7 +16,7 @@ import (
"github.com/txix-open/isp-kit/dbrx" "github.com/txix-open/isp-kit/dbrx"
"github.com/txix-open/isp-kit/dbx" "github.com/txix-open/isp-kit/dbx"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix" "github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
@@ -26,7 +26,7 @@ import (
type Assembly struct { type Assembly struct {
boot *bootstrap.Bootstrap boot *bootstrap.Bootstrap
db *dbrx.Client db *dbrx.Client
server *grpc.Server server *http.Server
oauthCli *httpcli.Client oauthCli *httpcli.Client
logger *log.Adapter logger *log.Adapter
bgjobCli *bgjobx.Client bgjobCli *bgjobx.Client
@@ -43,7 +43,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
return &Assembly{ return &Assembly{
boot: boot, boot: boot,
db: db, db: db,
server: grpc.NewServer(), server: http.NewServer(logger),
logger: logger, logger: logger,
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))), oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
bgjobCli: bgjobCli, bgjobCli: bgjobCli,
@@ -109,7 +109,7 @@ func (a *Assembly) Runners() []app.Runner {
app.RunnerFunc(func(ctx context.Context) error { app.RunnerFunc(func(ctx context.Context) error {
err := a.server.ListenAndServe(a.boot.BindingAddress) err := a.server.ListenAndServe(a.boot.BindingAddress)
if err != nil { if err != nil {
return errors.WithMessage(err, "listen ans serve grpc server") return errors.WithMessage(err, "listen and serve http server")
} }
return nil return nil
}), }),
@@ -127,7 +127,7 @@ func (a *Assembly) Closers() []app.Closer {
return []app.Closer{ return []app.Closer{
a.boot.ClusterCli, a.boot.ClusterCli,
app.CloserFunc(func() error { app.CloserFunc(func() error {
a.server.Shutdown() _ = a.server.Shutdown(context.Background())
return nil return nil
}), }),
app.CloserFunc(func() error { app.CloserFunc(func() error {
+17 -4
View File
@@ -18,9 +18,10 @@ import (
"github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/bgjobx"
"github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/endpoint" "github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
@@ -44,7 +45,7 @@ func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
} }
type Config struct { type Config struct {
Handler isp.BackendServiceServer Handler *router.Router
BgJobCfg []bgjobx.WorkerConfig BgJobCfg []bgjobx.WorkerConfig
} }
@@ -97,6 +98,14 @@ func (l Locator) Config(
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings) uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
downloadService := service.NewDownload(
auditService,
userService,
tokenService,
roleService,
permissionsService,
)
userController := controller.NewUser(userService) userController := controller.NewUser(userService)
customizationController := controller.NewCustomization(cfg.UiDesign) customizationController := controller.NewCustomization(cfg.UiDesign)
authController := controller.NewAuth(authService, l.logger) authController := controller.NewAuth(authService, l.logger)
@@ -106,8 +115,11 @@ func (l Locator) Config(
roleController := controller.NewRole(roleService) roleController := controller.NewRole(roleService)
permissionController := controller.NewPermissions(permissionsService) permissionController := controller.NewPermissions(permissionsService)
uiSettingsController := controller.NewUiSettings(uiSettingsService) uiSettingsController := controller.NewUiSettings(uiSettingsService)
downloadController := controller.NewDownload(downloadService)
wrapper := endpoint.DefaultWrapper(l.logger, httplog.Log(l.logger, true))
handler := routes.Handler( handler := routes.Handler(
endpoint.DefaultWrapper(l.logger), wrapper,
routes.Controllers{ routes.Controllers{
User: userController, User: userController,
Customization: customizationController, Customization: customizationController,
@@ -118,6 +130,7 @@ func (l Locator) Config(
Role: roleController, Role: roleController,
Permissions: permissionController, Permissions: permissionController,
UiSettings: uiSettingsController, UiSettings: uiSettingsController,
Download: downloadController,
}, },
) )
+35
View File
@@ -0,0 +1,35 @@
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
}
+36 -35
View File
@@ -2,12 +2,12 @@ package controller
import ( import (
"context" "context"
"net/http"
"isp-admin-service/domain" "isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"google.golang.org/grpc/codes" "github.com/txix-open/isp-kit/http/apierrors"
"google.golang.org/grpc/status"
) )
type AuditService interface { type AuditService interface {
@@ -27,16 +27,17 @@ func NewAudit(service AuditService) Audit {
} }
// All // All
// @Tags log //
// @Summary Получение списка логов // @Tags log
// @Accept json // @Summary Получение списка логов
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.AuditPageRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.AuditResponse // @Param body body domain.AuditPageRequest true "Тело запроса (пагинация, сортировка, фильтры)"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.AuditResponse
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /log/all [POST] // @Failure 500 {object} apierrors.Error
// @Router /log/all [POST]
func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) { func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.AuditResponse, error) {
if req.Order == nil { if req.Order == nil {
req.Order = &domain.OrderParams{ req.Order = &domain.OrderParams{
@@ -49,38 +50,38 @@ func (c Audit) All(ctx context.Context, req domain.AuditPageRequest) (*domain.Au
} }
// Events // Events
// @Tags log //
// @Summary Получение списка логов // @Tags log
// @Description Возвращает полный список доступных событий аудита // @Summary Получение списка событий аудита
// @Accept json // @Description Возвращает полный список доступных событий аудита
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.AuditResponse true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {array} domain.AuditEvent // @Success 200 {array} domain.AuditEvent
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Failure 500 {object} apierrors.Error
// @Failure 500 {object} domain.GrpcError // @Router /log/events [POST]
// @Router /log/events [POST]
func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) { func (c Audit) Events(ctx context.Context) ([]domain.AuditEvent, error) {
return c.service.Events(ctx) return c.service.Events(ctx)
} }
// SetEvents // SetEvents
// @Tags log //
// @Summary Получение списка логов // @Tags log
// @Description Всегда возвращает полный список доступных событий аудита // @Summary Установить события аудита
// @Accept json // @Description Устанавливает (обновляет) набор активных событий аудита.
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.SetAuditEvent true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body []domain.SetAuditEvent true "Список событий аудита для установки"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} map[string]interface{} "События успешно установлены"
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Неизвестное событие аудита"
// @Router /log/set_events [POST] // @Failure 500 {object} apierrors.Error
// @Router /log/set_events [POST]
func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error { func (c Audit) SetEvents(ctx context.Context, req []domain.SetAuditEvent) error {
err := c.service.SetEvents(ctx, req) err := c.service.SetEvents(ctx, req)
switch { switch {
case errors.As(err, &domain.UnknownAuditEventError{}): case errors.As(err, &domain.UnknownAuditEventError{}):
return status.Error(codes.InvalidArgument, err.Error()) return apierrors.New(http.StatusBadRequest, domain.UnknownAuditEventErrorCode, err.Error(), err)
default: default:
return err return err
} }
+64 -60
View File
@@ -2,16 +2,15 @@ package controller
import ( import (
"context" "context"
"net/http"
"strconv" "strconv"
"isp-admin-service/auth"
"isp-admin-service/domain" "isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/http/apierrors"
"github.com/txix-open/isp-kit/log" "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 { type authService interface {
@@ -33,18 +32,19 @@ func NewAuth(authService authService, logger log.Logger) Auth {
} }
// Logout // Logout
// @Tags auth //
// @Summary Выход из авторизованной сессии // @Tags auth
// @Description Выход из авторизованной сессии администрирования // @Summary Выход из авторизованной сессии
// @Accept json // @Description Выход из авторизованной сессии администрирования
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Success 200 // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Success 200 {object} map[string]interface{} "Успешный выход"
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Router /auth/logout [POST] // @Failure 500 {object} apierrors.Error
func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error { // @Router /auth/logout [POST]
adminId, err := getAdminId(authData) func (a Auth) Logout(ctx context.Context, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return err return err
} }
@@ -58,19 +58,20 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
} }
// LogoutWithReason // LogoutWithReason
// @Tags auth //
// @Summary Выход по бездействию из авторизованной сессии // @Tags auth
// @Description Выход по бездействию из авторизованной сессии администрирования // @Summary Выход по бездействию из авторизованной сессии
// @Accept json // @Description Выход по бездействию из авторизованной сессии администрирования
// @Produce json // @Accept json
// @Param body body domain.LogoutRequest true "Тело запроса" // @Produce json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body domain.LogoutRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Success 200 {object} map[string]interface{} "Успешный выход"
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Router /auth/logout_with_reason [POST] // @Failure 500 {object} apierrors.Error
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error { // @Router /auth/logout_with_reason [POST]
adminId, err := getAdminId(authData) func (a Auth) LogoutWithReason(ctx context.Context, logoutRequest domain.LogoutRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return err return err
} }
@@ -84,28 +85,30 @@ func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logo
} }
// Login // Login
// @Tags auth //
// @Summary Авторизация по логину и паролю // @Tags auth
// @Description Авторизация с получением токена администратора // @Summary Авторизация по логину и паролю
// @Accept json // @Description Авторизация с получением токена администратора
// @Produce json // @Accept json
// @Param body body domain.LoginRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.LoginResponse // @Param body body domain.LoginRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError // @Success 200 {object} domain.LoginResponse
// @Failure 401 {object} domain.GrpcError "Данные для авторизации не верны" // @Failure 400 {object} apierrors.Error
// @Failure 500 {object} domain.GrpcError // @Failure 401 {object} apierrors.Error "Данные для авторизации не верны"
// @Router /auth/login [POST] // @Failure 429 {object} apierrors.Error "Слишком много запросов на авторизацию"
// @Failure 500 {object} apierrors.Error
// @Router /auth/login [POST]
func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) { func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.Login(ctx, authRequest) auth, err := a.authService.Login(ctx, authRequest)
switch { switch {
case errors.Is(err, domain.ErrOauthAuthorization): case errors.Is(err, domain.ErrOauthAuthorization):
return nil, status.Error(codes.InvalidArgument, "plain auth is not available") return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthAuthorizationCode, err.Error(), err)
case errors.Is(err, domain.ErrUnauthenticated): case errors.Is(err, domain.ErrUnauthenticated):
a.logger.Error(ctx, err.Error()) a.logger.Error(ctx, err.Error())
return nil, status.Error(codes.Unauthenticated, "invalid credential") return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case errors.Is(err, domain.ErrTooManyLoginRequests): case errors.Is(err, domain.ErrTooManyLoginRequests):
return nil, status.Error(codes.ResourceExhausted, "too many requests") return nil, apierrors.New(http.StatusTooManyRequests, domain.ErrTooManyLoginRequestsCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "login") return nil, errors.WithMessage(err, "login")
default: default:
@@ -114,25 +117,26 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
} }
// LoginWithOauth // LoginWithOauth
// @Tags auth //
// @Summary Авторизация по авторизационному коду от OAuth // @Tags auth
// @Description Авторизация с получением токена администратора // @Summary Авторизация по авторизационному коду от OAuth
// @Accept json // @Description Авторизация с получением токена администратора.
// @Produce json // @Accept json
// @Param body body domain.LoginOauthRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.LoginResponse // @Param body body domain.LoginOauthRequest true "Тело запроса"
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента" // @Success 200 {object} domain.LoginResponse
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере" // @Failure 400 {object} apierrors.Error "Авторизация OAuth не настроена на сервере"
// @Failure 500 {object} domain.GrpcError // @Failure 401 {object} apierrors.Error "Некорректный код для авторизации или неизвестное название клиента"
// @Router /auth/login_with_oauth [POST] // @Failure 500 {object} apierrors.Error
// @Router /auth/login_with_oauth [POST]
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) { func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
auth, err := a.authService.LoginWithOauth(ctx, request) auth, err := a.authService.LoginWithOauth(ctx, request)
switch { switch {
case errors.Is(err, domain.ErrOauthIsMissed): case errors.Is(err, domain.ErrOauthIsMissed):
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured") return nil, apierrors.New(http.StatusBadRequest, domain.ErrOauthIsMissedCode, err.Error(), err)
case errors.Is(err, domain.ErrUnauthenticated): case errors.Is(err, domain.ErrUnauthenticated):
return nil, status.Error(codes.Unauthenticated, "invalid code") return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "login with oauth") return nil, errors.WithMessage(err, "login with oauth")
default: default:
@@ -140,15 +144,15 @@ func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthReque
} }
} }
func getAdminId(authData grpc.AuthData) (int64, error) { func getAdminId(r *http.Request) (int64, error) {
token, err := grpc.StringFromMd(domain.AdminAuthIdHeader, metadata.MD(authData)) token, err := auth.StringFromHeader(domain.AdminAuthIdHeader, r.Header)
if err != nil { if err != nil {
return 0, status.Error(codes.InvalidArgument, err.Error()) return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
} }
adminId, err := strconv.Atoi(token) adminId, err := strconv.Atoi(token)
if err != nil { if err != nil {
return 0, status.Error(codes.InvalidArgument, "admin id is not a number") return 0, apierrors.NewBusinessError(http.StatusBadRequest, err.Error(), err)
} }
return int64(adminId), nil return int64(adminId), nil
+11 -10
View File
@@ -19,16 +19,17 @@ func NewCustomization(uiCfg conf.UIDesign) Customization {
} }
// GetUIDesign // GetUIDesign
// @Tags user //
// @Summary Получение внешнего вида // @Tags user
// @Description Получение внешнего вида (палитра и наименование) админ-интерфейса // @Summary Получение внешнего вида
// @Accept json // @Description Получение внешнего вида (палитра и наименование) админ-интерфейса
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Success 200 {object} domain.UIDesign // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Success 200 {object} domain.UIDesign
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидный токен"
// @Router /user/get_design [POST] // @Failure 500 {object} apierrors.Error
// @Router /user/get_design [POST]
func (c Customization) GetUIDesign() (domain.UIDesign, error) { func (c Customization) GetUIDesign() (domain.UIDesign, error) {
return c.uiCfg, nil return c.uiCfg, nil
} }
+102
View File
@@ -0,0 +1,102 @@
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, 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, w http.ResponseWriter) error {
err := c.service.DownloadRoles(ctx, w)
if err != nil {
return errors.WithMessage(err, "download roles")
}
return nil
}
+9 -7
View File
@@ -21,13 +21,15 @@ func NewPermissions(permissionsService permissionsService) Permissions {
} }
// GetPermissions // GetPermissions
// @Tags user //
// @Summary Получить все разрашения // @Tags user
// @Description Получить все разрашения // @Summary Получить все разрешения
// @Accept json // @Description Получить все разрешения
// @Produce json // @Accept json
// @Success 200 {array} domain.Permission // @Produce json
// @Router /user/get_permissions [POST] // @Success 200 {array} domain.Permission
// @Failure 500 {object} apierrors.Error
// @Router /user/get_permissions [POST]
func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission { func (u Permissions) GetPermissions(ctx context.Context) []domain.Permission {
return u.permissionsService.All(ctx) return u.permissionsService.All(ctx)
} }
+63 -60
View File
@@ -2,17 +2,16 @@ package controller
import ( import (
"context" "context"
"net/http"
"isp-admin-service/domain" "isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/http/apierrors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type roleService interface { type roleService interface {
All(ctx context.Context) ([]domain.Role, error) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*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) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
@@ -29,18 +28,19 @@ func NewRole(roleService roleService) Role {
} }
// All // All
// @Tags role //
// @Summary Список ролей // @Tags role
// @Description Получить список ролей // @Summary Список ролей
// @Accept json // @Description Получить список ролей
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Success 200 {array} domain.Role // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} domain.GrpcError // @Success 200 {array} domain.Role
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error
// @Router /role/all [POST] // @Failure 500 {object} apierrors.Error
func (u Role) All(ctx context.Context) ([]domain.Role, error) { // @Router /role/all [POST]
users, err := u.roleService.All(ctx) func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
users, err := u.roleService.All(ctx, req)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "get roles") return nil, errors.WithMessage(err, "get roles")
} }
@@ -49,20 +49,21 @@ func (u Role) All(ctx context.Context) ([]domain.Role, error) {
} }
// CreateRole // CreateRole
// @Tags user //
// @Summary Создать роль // @Tags role
// @Description Создать роль // @Summary Создать роль
// @Accept json // @Description Создать роль
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.CreateRoleRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.User // @Param body body domain.CreateRoleRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.Role
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError // @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
// @Router /role/create [POST] // @Failure 500 {object} apierrors.Error
func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain.CreateRoleRequest) (*domain.Role, error) { // @Router /role/create [POST]
adminId, err := getAdminId(authData) func (u Role) CreateRole(ctx context.Context, req domain.CreateRoleRequest, r *http.Request) (*domain.Role, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -70,7 +71,7 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
role, err := u.roleService.Create(ctx, req, adminId) role, err := u.roleService.Create(ctx, req, adminId)
switch { switch {
case errors.Is(err, domain.ErrAlreadyExists): case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "role with current name already exists") return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "create role") return nil, errors.WithMessage(err, "create role")
default: default:
@@ -79,20 +80,21 @@ func (u Role) CreateRole(ctx context.Context, authData grpc.AuthData, req domain
} }
// UpdateRole // UpdateRole
// @Tags role //
// @Summary Обновить роль // @Tags role
// @Description Обновить данные существующую роль // @Summary Обновить роль
// @Accept json // @Description Обновить данные существующую роль
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.UpdateRoleRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.Role // @Param body body domain.UpdateRoleRequest true "Тело запроса"
// @Failure 404 {object} domain.GrpcError "Роль с указанным id не существует" // @Success 200 {object} domain.Role
// @Failure 409 {object} domain.GrpcError "Роль с указанным именем уже существует" // @Failure 404 {object} apierrors.Error "Роль с указанным id не существует"
// @Failure 500 {object} domain.GrpcError // @Failure 409 {object} apierrors.Error "Роль с указанным именем уже существует"
// @Router /role/update [POST] // @Failure 500 {object} apierrors.Error
func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain.UpdateRoleRequest) (*domain.Role, error) { // @Router /role/update [POST]
adminId, err := getAdminId(authData) func (u Role) UpdateRole(ctx context.Context, req domain.UpdateRoleRequest, r *http.Request) (*domain.Role, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -100,9 +102,9 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
result, err := u.roleService.Update(ctx, req, adminId) result, err := u.roleService.Update(ctx, req, adminId)
switch { switch {
case errors.Is(err, domain.ErrNotFound): case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "role not found") return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case errors.Is(err, domain.ErrAlreadyExists): case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "role with current name already exists") return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "update role") return nil, errors.WithMessage(err, "update role")
default: default:
@@ -111,19 +113,20 @@ func (u Role) UpdateRole(ctx context.Context, authData grpc.AuthData, req domain
} }
// DeleteRole // DeleteRole
// @Tags role //
// @Summary Удалить роль // @Tags role
// @Description Удалить существующую роль // @Summary Удалить роль
// @Accept json // @Description Удалить существующую роль
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.DeleteRoleRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body domain.DeleteRoleRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /role/delete [POST] // @Failure 500 {object} apierrors.Error
func (u Role) DeleteRole(ctx context.Context, authData grpc.AuthData, req domain.DeleteRoleRequest) error { // @Router /role/delete [POST]
adminId, err := getAdminId(authData) func (u Role) DeleteRole(ctx context.Context, req domain.DeleteRoleRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return err return err
} }
+21 -19
View File
@@ -6,7 +6,7 @@ import (
"isp-admin-service/domain" "isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors" "github.com/txix-open/isp-kit/http/apierrors"
) )
type SecureService interface { type SecureService interface {
@@ -25,15 +25,16 @@ func NewSecure(service SecureService) Secure {
} }
// Authenticate // Authenticate
// @Tags secure //
// @Summary Метод аутентификации токена // @Tags secure
// @Description Проверяет токен и возвращает идентификатор администратора // @Summary Метод аутентификации токена
// @Accept json // @Description Проверяет токен и возвращает идентификатор администратора
// @Produce json // @Accept json
// @Param body body domain.SecureAuthRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.SecureAuthResponse // @Param body body domain.SecureAuthRequest true "Тело запроса"
// @Failure 500 {object} domain.GrpcError // @Success 200 {object} domain.SecureAuthResponse
// @Router /secure/authenticate [POST] // @Failure 500 {object} apierrors.Error
// @Router /secure/authenticate [POST]
func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) { func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest) (*domain.SecureAuthResponse, error) {
adminId, err := s.service.Authenticate(ctx, req.Token) adminId, err := s.service.Authenticate(ctx, req.Token)
switch { switch {
@@ -61,15 +62,16 @@ func (s Secure) Authenticate(ctx context.Context, req domain.SecureAuthRequest)
} }
// Authorize // Authorize
// @Tags secure //
// @Summary Метод авторизации для администратора // @Tags secure
// @Description Проверяет наличие у администратора необходимого разрешения // @Summary Метод авторизации для администратора
// @Accept json // @Description Проверяет наличие у администратора необходимого разрешения
// @Produce json // @Accept json
// @Param body body domain.SecureAuthzRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.SecureAuthzResponse // @Param body body domain.SecureAuthzRequest true "Тело запроса"
// @Failure 500 {object} domain.GrpcError // @Success 200 {object} domain.SecureAuthzResponse
// @Router /secure/authorize [POST] // @Failure 500 {object} apierrors.Error
// @Router /secure/authorize [POST]
func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) { func (s Secure) Authorize(ctx context.Context, req domain.SecureAuthzRequest) (*domain.SecureAuthzResponse, error) {
ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission) ok, err := s.service.Authorize(ctx, req.AdminId, req.Permission)
if err != nil { if err != nil {
+22 -20
View File
@@ -22,16 +22,17 @@ func NewSession(service SessionService) Session {
} }
// All // All
// @Tags session //
// @Summary Получение списка сессий // @Tags session
// @Accept json // @Summary Получение списка сессий
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.SessionPageRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.SessionResponse // @Param body body domain.SessionPageRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.SessionResponse
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /session/all [POST] // @Failure 500 {object} apierrors.Error
// @Router /session/all [POST]
func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) { func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domain.SessionResponse, error) {
if req.Order == nil { if req.Order == nil {
req.Order = &domain.OrderParams{ req.Order = &domain.OrderParams{
@@ -44,16 +45,17 @@ func (c Session) All(ctx context.Context, req domain.SessionPageRequest) (*domai
} }
// Revoke // Revoke
// @Tags session //
// @Summary Отзыв сессии // @Tags session
// @Accept json // @Summary Отзыв сессии
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.RevokeRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body domain.RevokeRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /session/revoke [POST] // @Failure 500 {object} apierrors.Error
// @Router /session/revoke [POST]
func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error { func (c Session) Revoke(ctx context.Context, req domain.RevokeRequest) error {
return c.service.Revoke(ctx, req.Id) return c.service.Revoke(ctx, req.Id)
} }
+15 -14
View File
@@ -3,10 +3,10 @@ package controller
import ( import (
"context" "context"
"isp-admin-service/domain" "isp-admin-service/domain"
"net/http"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"google.golang.org/grpc/codes" "github.com/txix-open/isp-kit/http/apierrors"
"google.golang.org/grpc/status"
) )
type UiSettingsService interface { type UiSettingsService interface {
@@ -24,22 +24,23 @@ func NewUiSettings(service UiSettingsService) UiSettings {
} }
// UiOauthSettings // UiOauthSettings
// @Tags ui_settings //
// @Summary Получение настроек для ui для авторизации через OAuth // @Tags ui_settings
// @Description Получение настроек для ui для авторизации через OAuth // @Summary Получение настроек для ui для авторизации через OAuth
// @Accept json // @Description Получение настроек для ui для авторизации через OAuth
// @Produce json // @Accept json
// @Param body body domain.ClientNameRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.UiOauthSetting // @Param body body domain.ClientNameRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError // @Success 200 {object} domain.UiOauthSetting
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента" // @Failure 400 {object} apierrors.Error
// @Failure 500 {object} domain.GrpcError // @Failure 401 {object} apierrors.Error "Неизвестное название клиента"
// @Router /ui_settings/oauth [POST] // @Failure 500 {object} apierrors.Error
// @Router /ui_settings/oauth [POST]
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) { func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
resp, err := c.service.OauthSettings(ctx, req) resp, err := c.service.OauthSettings(ctx, req)
switch { switch {
case errors.Is(err, domain.ErrUnknownClient): case errors.Is(err, domain.ErrUnknownClient):
return nil, status.Error(codes.Unauthenticated, "invalid client name") return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnknownClientCode, err.Error(), err)
case err != nil: case err != nil:
return nil, err return nil, err
default: default:
+127 -120
View File
@@ -2,15 +2,13 @@ package controller
import ( import (
"context" "context"
"net/http"
"github.com/txix-open/isp-kit/grpc/apierrors" "github.com/txix-open/isp-kit/http/apierrors"
"isp-admin-service/domain" "isp-admin-service/domain"
"github.com/txix-open/isp-kit/errors" "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 { type userService interface {
@@ -36,19 +34,20 @@ func NewUser(userService userService) User {
} }
// GetProfile // GetProfile
// @Tags user //
// @Summary Получить профиль // @Tags user
// @Description Получить данные профиля // @Summary Получить профиль
// @Accept json // @Description Получить данные профиля
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Success 200 {object} domain.AdminUserShort // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Success 200 {object} domain.AdminUserShort
// @Failure 404 {object} domain.GrpcError "Пользователя не существует" // @Failure 401 {object} apierrors.Error "Невалидный токен"
// @Failure 500 {object} domain.GrpcError // @Failure 404 {object} apierrors.Error "Пользователя не существует"
// @Router /user/get_profile [POST] // @Failure 500 {object} apierrors.Error
func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.AdminUserShort, error) { // @Router /user/get_profile [POST]
adminId, err := getAdminId(authData) func (u User) GetProfile(ctx context.Context, r *http.Request) (*domain.AdminUserShort, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -56,9 +55,9 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
profile, err := u.userService.GetProfileById(ctx, adminId) profile, err := u.userService.GetProfileById(ctx, adminId)
switch { switch {
case errors.Is(err, domain.ErrUnauthenticated): case errors.Is(err, domain.ErrUnauthenticated):
return nil, status.Error(codes.Unauthenticated, "user is blocked") return nil, apierrors.New(http.StatusUnauthorized, domain.ErrUnauthenticatedCode, err.Error(), err)
case errors.Is(err, domain.ErrNotFound): case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "user not found") return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "get profile") return nil, errors.WithMessage(err, "get profile")
default: default:
@@ -67,17 +66,18 @@ func (u User) GetProfile(ctx context.Context, authData grpc.AuthData) (*domain.A
} }
// GetUsers // GetUsers
// @Tags user //
// @Summary Список пользователей // @Tags user
// @Description Получить список пользователей // @Summary Список пользователей
// @Accept json // @Description Получить список пользователей
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.UsersPageRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.UsersResponse // @Param body body domain.UsersPageRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError // @Success 200 {object} domain.UsersResponse
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error
// @Router /user/get_users [POST] // @Failure 500 {object} apierrors.Error
// @Router /user/get_users [POST]
func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) { func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domain.UsersResponse, error) {
if req.Order == nil { if req.Order == nil {
req.Order = &domain.OrderParams{ req.Order = &domain.OrderParams{
@@ -95,16 +95,17 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) (*domai
} }
// GetAllUsers // GetAllUsers
// @Tags user //
// @Summary Список пользователей // @Tags user
// @Description Получить список пользователей // @Summary Список пользователей
// @Accept json // @Description Получить список пользователей
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Success 200 {object} domain.UsersResponse // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Failure 400 {object} domain.GrpcError // @Success 200 {object} domain.UsersResponse
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error
// @Router /user/get_all_users [POST] // @Failure 500 {object} apierrors.Error
// @Router /user/get_all_users [POST]
func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) { func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
users, err := u.userService.GetAllUsers(ctx) users, err := u.userService.GetAllUsers(ctx)
if err != nil { if err != nil {
@@ -115,20 +116,21 @@ func (u User) GetAllUsers(ctx context.Context) (*domain.UsersResponse, error) {
} }
// CreateUser // CreateUser
// @Tags user //
// @Summary Создать пользователя // @Tags user
// @Description Создать пользователя // @Summary Создать пользователя
// @Accept json // @Description Создать пользователя
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.CreateUserRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.User // @Param body body domain.CreateUserRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.User
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 500 {object} domain.GrpcError // @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
// @Router /user/create_user [POST] // @Failure 500 {object} apierrors.Error
func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain.CreateUserRequest) (*domain.User, error) { // @Router /user/create_user [POST]
adminId, err := getAdminId(authData) func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, r *http.Request) (*domain.User, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -136,7 +138,7 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
user, err := u.userService.CreateUser(ctx, req, adminId) user, err := u.userService.CreateUser(ctx, req, adminId)
switch { switch {
case errors.Is(err, domain.ErrAlreadyExists): case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists") return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "create user") return nil, errors.WithMessage(err, "create user")
default: default:
@@ -145,21 +147,22 @@ func (u User) CreateUser(ctx context.Context, authData grpc.AuthData, req domain
} }
// UpdateUser // UpdateUser
// @Tags user //
// @Summary Обновить пользователя // @Tags user
// @Description Обновить данные существующего пользователя // @Summary Обновить пользователя
// @Accept json // @Description Обновить данные существующего пользователя
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.UpdateUserRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.User // @Param body body domain.UpdateUserRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.User
// @Failure 404 {object} domain.GrpcError "Пользователь с указанным id не существует" // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Failure 409 {object} domain.GrpcError "Пользователь с указанным email уже существует" // @Failure 404 {object} apierrors.Error "Пользователь с указанным id не существует"
// @Failure 500 {object} domain.GrpcError // @Failure 409 {object} apierrors.Error "Пользователь с указанным email уже существует"
// @Router /user/update_user [POST] // @Failure 500 {object} apierrors.Error
func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain.UpdateUserRequest) (*domain.User, error) { // @Router /user/update_user [POST]
adminId, err := getAdminId(authData) func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, r *http.Request) (*domain.User, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -167,11 +170,11 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
result, err := u.userService.UpdateUser(ctx, req, adminId) result, err := u.userService.UpdateUser(ctx, req, adminId)
switch { switch {
case errors.Is(err, domain.ErrNotFound): case errors.Is(err, domain.ErrNotFound):
return nil, status.Error(codes.NotFound, "user not found") return nil, apierrors.New(http.StatusNotFound, domain.ErrNotFoundCode, err.Error(), err)
case errors.Is(err, domain.ErrInvalid): case errors.Is(err, domain.ErrInvalid):
return nil, status.Error(codes.InvalidArgument, "user modification is not available") return nil, apierrors.New(http.StatusBadRequest, domain.ErrInvalidCode, err.Error(), err)
case errors.Is(err, domain.ErrAlreadyExists): case errors.Is(err, domain.ErrAlreadyExists):
return nil, status.Error(codes.AlreadyExists, "user with the same email already exists") return nil, apierrors.New(http.StatusConflict, domain.ErrAlreadyExistsCode, err.Error(), err)
case err != nil: case err != nil:
return nil, errors.WithMessage(err, "update user") return nil, errors.WithMessage(err, "update user")
default: default:
@@ -180,19 +183,20 @@ func (u User) UpdateUser(ctx context.Context, authData grpc.AuthData, req domain
} }
// DeleteUser // DeleteUser
// @Tags user //
// @Summary Удалить пользователя // @Tags user
// @Description Удалить существующего пользователя // @Summary Удалить пользователя
// @Accept json // @Description Удалить существующего пользователя
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.IdentitiesRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 {object} domain.DeleteResponse // @Param body body domain.IdentitiesRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.DeleteResponse
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /user/delete_user [POST] // @Failure 500 {object} apierrors.Error
func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities domain.IdentitiesRequest) (*domain.DeleteResponse, error) { // @Router /user/delete_user [POST]
adminId, err := getAdminId(authData) func (u User) DeleteUser(ctx context.Context, identities domain.IdentitiesRequest, r *http.Request) (*domain.DeleteResponse, error) {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -206,18 +210,19 @@ func (u User) DeleteUser(ctx context.Context, authData grpc.AuthData, identities
} }
// Block // Block
// @Tags user //
// @Summary Метод блокировки/разблокировки пользователя // @Tags user
// @Accept json // @Summary Метод блокировки/разблокировки пользователя
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.IdRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body domain.IdRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /user/block_user [POST] // @Failure 500 {object} apierrors.Error
func (u User) Block(ctx context.Context, authData grpc.AuthData, identities domain.IdRequest) error { // @Router /user/block_user [POST]
adminId, err := getAdminId(authData) func (u User) Block(ctx context.Context, identities domain.IdRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return err return err
} }
@@ -230,32 +235,34 @@ func (u User) Block(ctx context.Context, authData grpc.AuthData, identities doma
} }
// GetById // GetById
// @Tags user //
// @Summary Метод получения данных по пользователю // @Tags user
// @Accept json // @Summary Метод получения данных по пользователю
// @Produce json // @Accept json
// @Param body body domain.IdRequest true "Тело запроса" // @Produce json
// @Success 200 {object} domain.User // @Param body body domain.IdRequest true "Тело запроса"
// @Failure 400 {object} domain.GrpcError "Невалидное тело запроса" // @Success 200 {object} domain.User
// @Failure 500 {object} domain.GrpcError // @Failure 400 {object} apierrors.Error "Невалидное тело запроса"
// @Router /user/get_by_id [POST] // @Failure 500 {object} apierrors.Error
// @Router /user/get_by_id [POST]
func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) { func (u User) GetById(ctx context.Context, identities domain.IdRequest) (*domain.User, error) {
return u.userService.GetById(ctx, identities.UserId) return u.userService.GetById(ctx, identities.UserId)
} }
// ChangePassword // ChangePassword
// @Tags user //
// @Summary Метод изменения пароля пользователя // @Tags user
// @Accept json // @Summary Метод изменения пароля пользователя
// @Produce json // @Accept json
// @Param X-AUTH-ADMIN header string true "Токен администратора" // @Produce json
// @Param body body domain.ChangePasswordRequest true "Тело запроса" // @Param X-AUTH-ADMIN header string true "Токен администратора"
// @Success 200 // @Param body body domain.ChangePasswordRequest true "Тело запроса"
// @Failure 400 {object} apierrors.Error "Невалидное тело запроса" // @Success 200
// @Failure 500 {object} apierrors.Error "внутренняя ошибка" // @Failure 400 {object} apierrors.Error "Невалидное тело запроса или неверный старый пароль"
// @Router /user/change_password [POST] // @Failure 500 {object} apierrors.Error "Внутренняя ошибка"
func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req domain.ChangePasswordRequest) error { // @Router /user/change_password [POST]
adminId, err := getAdminId(authData) func (u User) ChangePassword(ctx context.Context, req domain.ChangePasswordRequest, r *http.Request) error {
adminId, err := getAdminId(r)
if err != nil { if err != nil {
return err return err
} }
@@ -263,7 +270,7 @@ func (u User) ChangePassword(ctx context.Context, authData grpc.AuthData, req do
err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword) err = u.userService.ChangePassword(ctx, adminId, req.OldPassword, req.NewPassword)
switch { switch {
case errors.Is(err, domain.ErrInvalidPassword): case errors.Is(err, domain.ErrInvalidPassword):
return apierrors.NewBusinessError(domain.ErrCodeInvalidPassword, "invalid password", err) return apierrors.New(http.StatusBadRequest, domain.ErrCodeInvalidPassword, err.Error(), err)
case err != nil: case err != nil:
return apierrors.NewInternalServiceError(err) return apierrors.NewInternalServiceError(err)
default: default:
+258 -116
View File
@@ -46,19 +46,25 @@
"400": { "400": {
"description": "Bad Request", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"401": { "401": {
"description": "Данные для авторизации не верны", "description": "Данные для авторизации не верны",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
}
},
"429": {
"description": "Слишком много запросов на авторизацию",
"schema": {
"$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -66,7 +72,7 @@
}, },
"/auth/login_with_oauth": { "/auth/login_with_oauth": {
"post": { "post": {
"description": "Авторизация с получением токена администратора", "description": "Авторизация с получением токена администратора.",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -95,22 +101,22 @@
"$ref": "#/definitions/domain.LoginResponse" "$ref": "#/definitions/domain.LoginResponse"
} }
}, },
"400": {
"description": "Авторизация OAuth не настроена на сервере",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
},
"401": { "401": {
"description": "Некорректный код для авторизации или неизвестное название клиента", "description": "Некорректный код для авторизации или неизвестное название клиента",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
}
},
"412": {
"description": "Авторизация OAuth не настроена на сервере",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -140,18 +146,22 @@
], ],
"responses": { "responses": {
"200": { "200": {
"description": "OK" "description": "Успешный выход",
"schema": {
"type": "object",
"additionalProperties": true
}
}, },
"400": { "400": {
"description": "Невалидный токен", "description": "Невалидный токен",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -171,6 +181,13 @@
], ],
"summary": "Выход по бездействию из авторизованной сессии", "summary": "Выход по бездействию из авторизованной сессии",
"parameters": [ "parameters": [
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
},
{ {
"description": "Тело запроса", "description": "Тело запроса",
"name": "body", "name": "body",
@@ -179,29 +196,26 @@
"schema": { "schema": {
"$ref": "#/definitions/domain.LogoutRequest" "$ref": "#/definitions/domain.LogoutRequest"
} }
},
{
"type": "string",
"description": "Токен администратора",
"name": "X-AUTH-ADMIN",
"in": "header",
"required": true
} }
], ],
"responses": { "responses": {
"200": { "200": {
"description": "OK" "description": "Успешный выход",
"schema": {
"type": "object",
"additionalProperties": true
}
}, },
"400": { "400": {
"description": "Невалидный токен", "description": "Невалидный токен",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -228,7 +242,7 @@
"required": true "required": true
}, },
{ {
"description": "Тело запроса", "description": "Тело запроса (пагинация, сортировка, фильтры)",
"name": "body", "name": "body",
"in": "body", "in": "body",
"required": true, "required": true,
@@ -247,13 +261,49 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$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"
} }
} }
} }
@@ -271,7 +321,7 @@
"tags": [ "tags": [
"log" "log"
], ],
"summary": "Получение списка логов", "summary": "Получение списка событий аудита",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
@@ -279,15 +329,6 @@
"name": "X-AUTH-ADMIN", "name": "X-AUTH-ADMIN",
"in": "header", "in": "header",
"required": true "required": true
},
{
"description": "Тело запроса",
"name": "body",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/domain.AuditResponse"
}
} }
], ],
"responses": { "responses": {
@@ -300,16 +341,10 @@
} }
} }
}, },
"400": {
"description": "Невалидное тело запроса",
"schema": {
"$ref": "#/definitions/domain.GrpcError"
}
},
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -317,7 +352,7 @@
}, },
"/log/set_events": { "/log/set_events": {
"post": { "post": {
"description": "Всегда возвращает полный список доступных событий аудита", "description": "Устанавливает (обновляет) набор активных событий аудита.",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -327,7 +362,7 @@
"tags": [ "tags": [
"log" "log"
], ],
"summary": "Получение списка логов", "summary": "Установить события аудита",
"parameters": [ "parameters": [
{ {
"type": "string", "type": "string",
@@ -337,29 +372,36 @@
"required": true "required": true
}, },
{ {
"description": "Тело запроса", "description": "Список событий аудита для установки",
"name": "body", "name": "body",
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/domain.SetAuditEvent" "type": "array",
"items": {
"$ref": "#/definitions/domain.SetAuditEvent"
}
} }
} }
], ],
"responses": { "responses": {
"200": { "200": {
"description": "OK" "description": "События успешно установлены",
"schema": {
"type": "object",
"additionalProperties": true
}
}, },
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Неизвестное событие аудита",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -400,13 +442,13 @@
"400": { "400": {
"description": "Bad Request", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -422,7 +464,7 @@
"application/json" "application/json"
], ],
"tags": [ "tags": [
"user" "role"
], ],
"summary": "Создать роль", "summary": "Создать роль",
"parameters": [ "parameters": [
@@ -447,25 +489,25 @@
"200": { "200": {
"description": "OK", "description": "OK",
"schema": { "schema": {
"$ref": "#/definitions/domain.User" "$ref": "#/definitions/domain.Role"
} }
}, },
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"409": { "409": {
"description": "Роль с указанным именем уже существует", "description": "Роль с указанным именем уже существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -509,13 +551,38 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$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"
} }
} }
} }
@@ -562,19 +629,19 @@
"404": { "404": {
"description": "Роль с указанным id не существует", "description": "Роль с указанным id не существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"409": { "409": {
"description": "Роль с указанным именем уже существует", "description": "Роль с указанным именем уже существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -614,7 +681,7 @@
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -654,7 +721,7 @@
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -700,13 +767,49 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$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"
} }
} }
} }
@@ -749,13 +852,13 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -795,19 +898,19 @@
"400": { "400": {
"description": "Bad Request", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"401": { "401": {
"description": "Неизвестное название клиента", "description": "Неизвестное название клиента",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -850,13 +953,13 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -897,13 +1000,13 @@
"description": "OK" "description": "OK"
}, },
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса или неверный старый пароль",
"schema": { "schema": {
"$ref": "#/definitions/apierrors.Error" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "внутренняя ошибка", "description": "Внутренняя ошибка",
"schema": { "schema": {
"$ref": "#/definitions/apierrors.Error" "$ref": "#/definitions/apierrors.Error"
} }
@@ -952,19 +1055,19 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"409": { "409": {
"description": "Пользователь с указанным email уже существует", "description": "Пользователь с указанным email уже существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1011,13 +1114,49 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$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"
} }
} }
} }
@@ -1055,13 +1194,13 @@
"400": { "400": {
"description": "Bad Request", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1100,13 +1239,13 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1144,13 +1283,13 @@
"400": { "400": {
"description": "Невалидный токен", "description": "Невалидный токен",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1158,7 +1297,7 @@
}, },
"/user/get_permissions": { "/user/get_permissions": {
"post": { "post": {
"description": "Получить все разрашения", "description": "Получить все разрешения",
"consumes": [ "consumes": [
"application/json" "application/json"
], ],
@@ -1168,7 +1307,7 @@
"tags": [ "tags": [
"user" "user"
], ],
"summary": "Получить все разрашения", "summary": "Получить все разрешения",
"responses": { "responses": {
"200": { "200": {
"description": "OK", "description": "OK",
@@ -1178,6 +1317,12 @@
"$ref": "#/definitions/domain.Permission" "$ref": "#/definitions/domain.Permission"
} }
} }
},
"500": {
"description": "Internal Server Error",
"schema": {
"$ref": "#/definitions/apierrors.Error"
}
} }
} }
} }
@@ -1211,22 +1356,22 @@
"$ref": "#/definitions/domain.AdminUserShort" "$ref": "#/definitions/domain.AdminUserShort"
} }
}, },
"400": { "401": {
"description": "Невалидный токен", "description": "Невалидный токен",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"404": { "404": {
"description": "Пользователя не существует", "description": "Пользователя не существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1273,13 +1418,13 @@
"400": { "400": {
"description": "Bad Request", "description": "Bad Request",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1326,25 +1471,25 @@
"400": { "400": {
"description": "Невалидное тело запроса", "description": "Невалидное тело запроса",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"404": { "404": {
"description": "Пользователь с указанным id не существует", "description": "Пользователь с указанным id не существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"409": { "409": {
"description": "Пользователь с указанным email уже существует", "description": "Пользователь с указанным email уже существует",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
}, },
"500": { "500": {
"description": "Internal Server Error", "description": "Internal Server Error",
"schema": { "schema": {
"$ref": "#/definitions/domain.GrpcError" "$ref": "#/definitions/apierrors.Error"
} }
} }
} }
@@ -1564,6 +1709,10 @@
"domain.CreateRoleRequest": { "domain.CreateRoleRequest": {
"type": "object", "type": "object",
"properties": { "properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": { "changeMessage": {
"description": "Причина изменений", "description": "Причина изменений",
"type": "string" "type": "string"
@@ -1656,21 +1805,6 @@
} }
} }
}, },
"domain.GrpcError": {
"type": "object",
"properties": {
"details": {
"type": "array",
"items": {}
},
"errorCode": {
"type": "string"
},
"errorMessage": {
"type": "string"
}
}
},
"domain.IdRequest": { "domain.IdRequest": {
"type": "object", "type": "object",
"required": [ "required": [
@@ -1805,6 +1939,10 @@
"domain.Role": { "domain.Role": {
"type": "object", "type": "object",
"properties": { "properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": { "changeMessage": {
"description": "Причина изменений", "description": "Причина изменений",
"type": "string" "type": "string"
@@ -2049,6 +2187,10 @@
"domain.UpdateRoleRequest": { "domain.UpdateRoleRequest": {
"type": "object", "type": "object",
"properties": { "properties": {
"applicationGroup": {
"description": "Группа приложений",
"type": "string"
},
"changeMessage": { "changeMessage": {
"description": "Причина изменений", "description": "Причина изменений",
"type": "string" "type": "string"
+1 -1
View File
@@ -17,7 +17,7 @@ type AuditResponse struct {
} }
type AuditPageRequest struct { type AuditPageRequest struct {
LimitOffestParams LimitOffsetParams
Order *OrderParams // Параметры сортировки Order *OrderParams // Параметры сортировки
Query *AuditQuery // Параметры выборки Query *AuditQuery // Параметры выборки
+13
View File
@@ -26,6 +26,19 @@ var (
ErrUnknownClient = errors.New("unknown client") 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 { type UnknownAuditEventError struct {
Event string Event string
} }
-7
View File
@@ -1,7 +0,0 @@
package domain
type GrpcError struct {
ErrorMessage string `json:"errorMessage"`
ErrorCode string `json:"errorCode"`
Details []any `json:"details"`
}
+1 -1
View File
@@ -7,7 +7,7 @@ const (
DefaultOrderType = "desc" DefaultOrderType = "desc"
) )
type LimitOffestParams struct { type LimitOffsetParams struct {
Limit uint64 `validate:"required"` // Максимальное количество записей Limit uint64 `validate:"required"` // Максимальное количество записей
Offset uint64 // Отступ для выборки Offset uint64 // Отступ для выборки
} }
+25 -18
View File
@@ -5,32 +5,39 @@ import (
) )
type Role struct { type Role struct {
Id int // Идентификатор роли Id int // Идентификатор роли
Name string // Название роли Name string // Название роли
ExternalGroup string // Внешнее название группы ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений ApplicationGroup string // Группа приложений
Permissions []string // Набор прав ChangeMessage string // Причина изменений
Immutable bool Permissions []string // Набор прав
Exclusive bool Immutable bool
CreatedAt time.Time // Дата создания Exclusive bool
UpdatedAt time.Time // Дата обновления CreatedAt time.Time // Дата создания
UpdatedAt time.Time // Дата обновления
} }
type CreateRoleRequest struct { type CreateRoleRequest struct {
Name string // Название роли Name string // Название роли
ExternalGroup string // Внешнее название группы ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений ApplicationGroup string // Группа приложений
Permissions []string // Набор прав ChangeMessage string // Причина изменений
Permissions []string // Набор прав
} }
type UpdateRoleRequest struct { type UpdateRoleRequest struct {
Id int // Идентификатор роли Id int // Идентификатор роли
Name string // Название роли Name string // Название роли
ExternalGroup string // Внешнее название группы ExternalGroup string // Внешнее название группы
ChangeMessage string // Причина изменений ApplicationGroup string // Группа приложений
Permissions []string // Набор прав ChangeMessage string // Причина изменений
Permissions []string // Набор прав
} }
type DeleteRoleRequest struct { type DeleteRoleRequest struct {
Id int // Идентификатор роли Id int // Идентификатор роли
} }
type RoleAllRequest struct {
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
}
+24 -1
View File
@@ -4,6 +4,17 @@ import (
"time" "time"
) )
const (
SessionStatusAllowed = "ALLOWED"
SessionStatusAllowedRus = "Активная"
SessionStatusExpired = "EXPIRED"
SessionStatusExpiredRus = "Истекшая"
SessionStatusRevoked = "REVOKED"
SessionStatusRevokedRus = "Отмененная"
)
type Session struct { type Session struct {
Id int // Идентификатор сессии Id int // Идентификатор сессии
UserId int // Идентификатор пользоватеккля UserId int // Идентификатор пользоватеккля
@@ -13,7 +24,7 @@ type Session struct {
} }
type SessionPageRequest struct { type SessionPageRequest struct {
LimitOffestParams LimitOffsetParams
Order *OrderParams // Параметры сортировки Order *OrderParams // Параметры сортировки
Query *SessionQuery // Параметры выборки Query *SessionQuery // Параметры выборки
@@ -35,3 +46,15 @@ type SessionResponse struct {
type RevokeRequest struct { type RevokeRequest struct {
Id int `validate:"required"` // Идентификатор сессии 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 -1
View File
@@ -32,7 +32,7 @@ type UserQuery struct {
} }
type UsersPageRequest struct { type UsersPageRequest struct {
LimitOffestParams LimitOffsetParams
Order *OrderParams // Параметры сортировки Order *OrderParams // Параметры сортировки
Query *UserQuery // Параметры выборки Query *UserQuery // Параметры выборки
+28
View File
@@ -0,0 +1,28 @@
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{"Действие", "Ключ в системе"}
}
+9 -8
View File
@@ -13,14 +13,15 @@ const (
) )
type Role struct { type Role struct {
Id int Id int
Name string Name string
ExternalGroup string ExternalGroup string
Permissions PermList ApplicationGroup string
Immutable bool Permissions PermList
Exclusive bool Immutable bool
CreatedAt time.Time Exclusive bool
UpdatedAt time.Time CreatedAt time.Time
UpdatedAt time.Time
} }
type PermList []string type PermList []string
+1
View File
@@ -5,6 +5,7 @@ import "time"
type User struct { type User struct {
OauthUserId *string OauthUserId *string
Id int64 Id int64
Roles []int
FirstName string FirstName string
LastName string LastName string
FullName string FullName string
+38 -35
View File
@@ -8,11 +8,10 @@ require (
github.com/iancoleman/strcase v0.3.0 github.com/iancoleman/strcase v0.3.0
github.com/stretchr/testify v1.12.1 github.com/stretchr/testify v1.12.1
github.com/txix-open/bgjob v1.6.0 github.com/txix-open/bgjob v1.6.0
github.com/txix-open/isp-kit v1.75.0 github.com/txix-open/isp-kit v1.76.0
github.com/txix-open/jsonschema v1.3.0 github.com/txix-open/jsonschema v1.3.0
golang.org/x/crypto v0.55.0 golang.org/x/crypto v0.59.0
golang.org/x/sync v0.22.0 golang.org/x/sync v0.25.0
google.golang.org/grpc v1.83.2
) )
require ( require (
@@ -22,61 +21,65 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.15 // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/getsentry/sentry-go v0.49.0 // indirect github.com/getsentry/sentry-go v0.50.0 // indirect
github.com/go-faker/faker/v4 v4.11.0 // indirect github.com/go-faker/faker/v4 v4.12.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect github.com/jackc/pgx/v5 v5.13.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jackc/puddle/v2 v2.2.4 // indirect
github.com/jmoiron/sqlx v1.4.0 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.19.2 // indirect github.com/julienschmidt/httprouter v1.3.0 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect github.com/leodido/go-urn v1.5.0 // indirect
github.com/mailru/easyjson v0.9.2 // indirect github.com/mailru/easyjson v0.9.2 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect github.com/mfridman/interpolate v0.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pressly/goose/v3 v3.27.3 // indirect github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/prometheus/client_golang v1.24.1 // indirect github.com/pressly/goose/v3 v3.30.1 // indirect
github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/procfs v0.21.1 // indirect github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sethvargo/go-retry v0.4.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/txix-open/bellows v1.2.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/etp/v4 v4.1.3 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // 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/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
go.opentelemetry.io/otel v1.46.0 // indirect go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.46.0 // indirect go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.46.0 // indirect go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.46.0 // indirect go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.0 // indirect go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/multierr v1.11.0 // indirect go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect go.uber.org/zap v1.28.0 // indirect
go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/net v0.58.0 // indirect golang.org/x/net v0.63.0 // indirect
golang.org/x/sys v0.47.0 // indirect golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.41.0 // indirect golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/grpc v1.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
+96 -94
View File
@@ -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/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.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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ= github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s= github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI= github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= 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-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120= github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg= github.com/go-faker/faker/v4 v4.12.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.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 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -38,15 +38,13 @@ 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-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 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.2/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.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
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.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= github.com/go-sql-driver/mysql v1.10.1/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 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -54,26 +52,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/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 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw= github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY= github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= 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 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= 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 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= 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 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= 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 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8= github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -90,12 +88,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/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 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-isatty v0.0.24/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 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= 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/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= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -105,33 +103,35 @@ 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/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 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= 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/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= 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 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek= github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= github.com/rabbitmq/amqp091-go v1.17.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 h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 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 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= 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 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 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.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= 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/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 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.75.0 h1:0/qJoDTyjsVkQTCsQ7FAilKo7a5Y5pDI4tfMXloHYCg= github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
github.com/txix-open/isp-kit v1.75.0/go.mod h1:LEBYertzXLJ3gSuxjeJTUcSGLtf28PZWDHFH9lccCHk= github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= 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/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0= 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-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA= github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc= 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/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= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
@@ -170,54 +170,56 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= 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 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= 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.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE= 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.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI= 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.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg= 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.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc= go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE= go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g= go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8= go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o= go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI= go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM= go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE= go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4= go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c= go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI= go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= 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.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= 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/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 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= 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 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
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-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0= 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-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc= 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-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA= google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= 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= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -228,11 +230,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.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 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= modernc.org/libc v1.80.2/go.mod h1:pvo25Rs3OJEbDqhUV9jdEGevxeLJrJeDmNid/AcQV1g=
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
+8 -8
View File
@@ -12,18 +12,18 @@ import (
var version = "1.0.0" var version = "1.0.0"
// @title isp-admin-service // @title isp-admin-service
// @version 1.0.0 // @version 1.0.0
// @description сервис управления администраторами // @description сервис управления администраторами
// @license.name GNU GPL v3.0 // @license.name GNU GPL v3.0
// @host localhost:9000 // @host localhost:9000
// @BasePath /api/admin // @BasePath /api/admin
//go:generate swag init -pd -ot json //go:generate swag init -pd -ot json -eot json
func main() { func main() {
boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport) boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.HttpTransport)
app := boot.App app := boot.App
logger := app.Logger() logger := app.Logger()
@@ -1,44 +0,0 @@
-- +goose Up
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_PROD',
'["profile_view", "profile_change_password", "application_group_view", "application_group_add", "application_group_edit", "application_group_delete", "application_group_app_add", "application_group_app_edit", "application_group_app_delete", "application_group_token_view", "application_group_token_add", "application_group_token_delete", "app_access_view", "app_access_edit", "variable_view", "variable_add", "variable_edit", "variable_delete", "module_view", "module_delete", "module_configuration_save_unsafe", "module_configuration_set_active", "module_history_set", "module_history_delete_version", "module_configuration_edit", "module_configuration_add"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_admin,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_STAGE',
'["profile_view", "profile_change_password", "application_group_view", "application_group_add", "application_group_edit", "application_group_delete", "application_group_app_add", "application_group_app_edit", "application_group_app_delete", "application_group_token_view", "application_group_token_add", "application_group_token_delete", "app_access_view", "app_access_edit", "variable_view", "variable_add", "variable_edit", "variable_delete", "module_view", "module_delete", "module_configuration_save_unsafe", "module_configuration_set_active", "module_history_set", "module_history_delete_version", "module_configuration_edit", "module_configuration_add"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_admin,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_IB_PROD',
'["session_view", "user_view", "user_block", "user_create", "user_update", "user_delete", "session_revoke", "session_delete", "security_log_view", "profile_view", "profile_edit", "role_view", "role_add", "role_update", "role_delete", "role_link_user", "role_link_external_group", "supervisor_view"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_admin_ib,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_IB_STAGE',
'["session_view", "user_view", "user_block", "user_create", "user_update", "user_delete", "session_revoke", "session_delete", "security_log_view", "profile_view", "profile_edit", "role_view", "role_add", "role_update", "role_delete", "role_link_user", "role_link_external_group", "supervisor_view"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_admin_ib,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_READ_ONLY_PROD',
'["profile_view", "application_group_view", "application_group_token_view", "app_access_view", "module_view"]'::jsonb,
'cn=sudir_prod_int_kkd_tech_operator_ro,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
INSERT INTO roles (name, permissions, external_group, immutable, exclusive, created_at, updated_at)
VALUES ('DIT_KKD_TECH_ADMIN_READ_ONLY_STAGE',
'["profile_view", "application_group_view", "application_group_token_view", "app_access_view", "module_view"]'::jsonb,
'cn=sudir_stage_int_kkd_tech_operator_ro,cn=groups,cn=accounts,dc=data,dc=corp', true, true, NOW(), NOW())
ON CONFLICT (name) DO UPDATE
SET permissions = EXCLUDED.permissions;
-- +goose Down
@@ -0,0 +1,5 @@
-- +goose Up
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
-- +goose Down
ALTER TABLE roles DROP COLUMN application_group;
+4 -4
View File
@@ -38,7 +38,7 @@ func (r Audit) Insert(ctx context.Context, log entity.Audit) (int, error) {
query, args, err := query.New(). query, args, err := query.New().
Insert("audit"). Insert("audit").
Columns(userIdAuditColumn, "message", "event", createdAtAuditColumn). Columns("user_id", "message", "event", "created_at").
Values(log.UserId, log.Message, log.Event, log.CreatedAt). Values(log.UserId, log.Message, log.Event, log.CreatedAt).
Suffix("returning id"). Suffix("returning id").
ToSql() ToSql()
@@ -134,7 +134,7 @@ func reqAuditQuery(q squirrel.SelectBuilder, reqQuery *domain.AuditQuery) squirr
} }
if reqQuery.UserId != nil { if reqQuery.UserId != nil {
q = q.Where(squirrel.Eq{userIdAuditColumn: reqQuery.UserId}) q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
} }
if reqQuery.Message != nil { if reqQuery.Message != nil {
@@ -142,8 +142,8 @@ func reqAuditQuery(q squirrel.SelectBuilder, reqQuery *domain.AuditQuery) squirr
} }
if reqQuery.CreatedAt != nil { if reqQuery.CreatedAt != nil {
q = q.Where(squirrel.GtOrEq{createdAtAuditColumn: reqQuery.CreatedAt.From}). q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
Where(squirrel.Lt{createdAtAuditColumn: reqQuery.CreatedAt.To}) Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
} }
return q return q
+20 -4
View File
@@ -25,6 +25,7 @@ const (
updatedAtRolesColumn = "updated_at" updatedAtRolesColumn = "updated_at"
permissionsRolesColumn = "permissions" permissionsRolesColumn = "permissions"
externalGroupRolesColumn = "external_group" externalGroupRolesColumn = "external_group"
applicationGroupColumn = "application_group"
immutableRolesColumn = "immutable" immutableRolesColumn = "immutable"
exclusiveRolesColumn = "exclusive" exclusiveRolesColumn = "exclusive"
) )
@@ -37,7 +38,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds") ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
q, args, err := query.New(). q, args, err := query.New().
Select("id, name, external_group, permissions, created_at, updated_at"). Select("id, name, external_group, application_group, permissions, created_at, updated_at").
From("roles"). From("roles").
Where(squirrel.Eq{"id": id}). Where(squirrel.Eq{"id": id}).
ToSql() ToSql()
@@ -67,6 +68,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
updatedAtRolesColumn, updatedAtRolesColumn,
permissionsRolesColumn, permissionsRolesColumn,
externalGroupRolesColumn, externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn, immutableRolesColumn,
exclusiveRolesColumn, exclusiveRolesColumn,
). ).
@@ -101,6 +103,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
updatedAtRolesColumn, updatedAtRolesColumn,
permissionsRolesColumn, permissionsRolesColumn,
externalGroupRolesColumn, externalGroupRolesColumn,
applicationGroupColumn,
immutableRolesColumn, immutableRolesColumn,
exclusiveRolesColumn, exclusiveRolesColumn,
). ).
@@ -122,7 +125,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
func (r Role) All(ctx context.Context) ([]entity.Role, error) { func (r Role) All(ctx context.Context) ([]entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All") ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at" q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
roles := make([]entity.Role, 0) roles := make([]entity.Role, 0)
err := r.db.Select(ctx, &roles, q) err := r.db.Select(ctx, &roles, q)
if err != nil { if err != nil {
@@ -131,12 +134,24 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
return roles, nil 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) { func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole") ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
q, args, err := query.New().Insert("roles"). q, args, err := query.New().Insert("roles").
Columns("name", "permissions", "external_group"). Columns("name", "permissions", "external_group", "application_group").
Values(role.Name, role.Permissions, role.ExternalGroup). Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
Suffix("RETURNING *").ToSql() Suffix("RETURNING *").ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
@@ -158,6 +173,7 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
Set("name", role.Name). Set("name", role.Name).
Set("permissions", role.Permissions). Set("permissions", role.Permissions).
Set("external_group", role.ExternalGroup). Set("external_group", role.ExternalGroup).
Set("application_group", role.ApplicationGroup).
Where(squirrel.Eq{"id": role.Id}). Where(squirrel.Eq{"id": role.Id}).
Suffix("RETURNING *").ToSql() Suffix("RETURNING *").ToSql()
if err != nil { if err != nil {
+6 -6
View File
@@ -205,10 +205,10 @@ func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int6
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessByUserIds") ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessByUserIds")
query, args, err := query.New(). query, args, err := query.New().
Select(userIdTokensColumn, "max(created_at) as created_at"). Select("user_id", "max(created_at) as created_at").
From("tokens"). From("tokens").
Where(squirrel.Eq{userIdTokensColumn: userIds}). Where(squirrel.Eq{"user_id": userIds}).
GroupBy(userIdTokensColumn). GroupBy("user_id").
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
@@ -238,7 +238,7 @@ func reqTokenQuery(q squirrel.SelectBuilder, reqQuery *domain.SessionQuery) squi
} }
if reqQuery.UserId != nil { if reqQuery.UserId != nil {
q = q.Where(squirrel.Eq{userIdTokensColumn: reqQuery.UserId}) q = q.Where(squirrel.Eq{"user_id": reqQuery.UserId})
} }
if reqQuery.Status != nil { if reqQuery.Status != nil {
@@ -246,8 +246,8 @@ func reqTokenQuery(q squirrel.SelectBuilder, reqQuery *domain.SessionQuery) squi
} }
if reqQuery.CreatedAt != nil { if reqQuery.CreatedAt != nil {
q = q.Where(squirrel.GtOrEq{createdAtTokensColumn: reqQuery.CreatedAt.From}). q = q.Where(squirrel.GtOrEq{"created_at": reqQuery.CreatedAt.From}).
Where(squirrel.Lt{createdAtTokensColumn: reqQuery.CreatedAt.To}) Where(squirrel.Lt{"created_at": reqQuery.CreatedAt.To})
} }
if reqQuery.ExpiredAt != nil { if reqQuery.ExpiredAt != nil {
+2 -2
View File
@@ -48,7 +48,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{emailUsersColumn: email}). Where(squirrel.Eq{"email": email}).
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
@@ -217,7 +217,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn, updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
fullNameUsersColumn). fullNameUsersColumn).
From("users"). From("users").
Where(squirrel.Eq{emailUsersColumn: email}). Where(squirrel.Eq{"email": email}).
ToSql() ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
+4 -8
View File
@@ -12,10 +12,6 @@ import (
"github.com/txix-open/isp-kit/metrics/sql_metrics" "github.com/txix-open/isp-kit/metrics/sql_metrics"
) )
const (
userIdUserRolesColumn = "user_id"
)
type UserRole struct { type UserRole struct {
db db.DB db db.DB
} }
@@ -27,8 +23,8 @@ func NewUserRole(db db.DB) UserRole {
func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error) { func (u UserRole) GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.GetRolesByUserIds") ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.GetRolesByUserIds")
rolesQ, args, err := query.New().Select("role_id", userIdUserRolesColumn). rolesQ, args, err := query.New().Select("role_id", "user_id").
From("user_roles").Where(squirrel.Eq{userIdUserRolesColumn: identity}).ToSql() From("user_roles").Where(squirrel.Eq{"user_id": identity}).ToSql()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "build query") return nil, errors.WithMessage(err, "build query")
} }
@@ -71,7 +67,7 @@ func (u UserRole) UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int
ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.UpsertUserRoleLinks") ctx = sql_metrics.OperationLabelToContext(ctx, "UserRole.UpsertUserRoleLinks")
deleteQ, args, err := query.New(). deleteQ, args, err := query.New().
Delete("user_roles").Where(squirrel.Eq{userIdUserRolesColumn: id}).ToSql() Delete("user_roles").Where(squirrel.Eq{"user_id": id}).ToSql()
if err != nil { if err != nil {
return errors.WithMessage(err, "build query") return errors.WithMessage(err, "build query")
} }
@@ -87,7 +83,7 @@ func (u UserRole) UpsertUserRoleLinks(ctx context.Context, id int, roleIds []int
rolesQ := query.New(). rolesQ := query.New().
Insert("user_roles"). Insert("user_roles").
Columns(userIdUserRolesColumn, "role_id") Columns("user_id", "role_id")
for _, roleId := range roleIds { for _, roleId := range roleIds {
rolesQ = rolesQ.Values(id, roleId) rolesQ = rolesQ.Values(id, roleId)
} }
+159 -102
View File
@@ -3,12 +3,12 @@ package routes
import ( import (
"isp-admin-service/controller" "isp-admin-service/controller"
"isp-admin-service/docs" "isp-admin-service/docs"
"net/http"
"github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/common_endpoints" "github.com/txix-open/isp-kit/common_endpoints"
"github.com/txix-open/isp-kit/grpc" httpEndpoint "github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/grpc/endpoint" "github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/grpc/isp"
) )
type Controllers struct { type Controllers struct {
@@ -21,6 +21,7 @@ type Controllers struct {
Role controller.Role Role controller.Role
Permissions controller.Permissions Permissions controller.Permissions
UiSettings controller.UiSettings UiSettings controller.UiSettings
Download controller.Download
} }
func EndpointDescriptors() []cluster.EndpointDescriptor { func EndpointDescriptors() []cluster.EndpointDescriptor {
@@ -30,13 +31,13 @@ func EndpointDescriptors() []cluster.EndpointDescriptor {
) )
} }
func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn func Handler(wrapper httpEndpoint.Wrapper, c Controllers) *router.Router { // nolint:ireturn
muxer := grpc.NewMux() muxer := router.New()
for _, descriptor := range endpointDescriptors(c) { for _, descriptor := range endpointDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
} }
for _, descriptor := range commonEndpoints() { for _, descriptor := range commonEndpoints() {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) muxer.Handler(descriptor.HttpMethod, "/"+descriptor.Path, wrapper.Endpoint(descriptor.Handler))
} }
return muxer return muxer
} }
@@ -45,153 +46,209 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer {
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{ return []cluster.EndpointDescriptor{
{ {
Path: "admin/auth/login", Path: "admin/auth/login",
Inner: false, Inner: false,
Handler: c.Auth.Login, Handler: c.Auth.Login,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/auth/login_with_oauth", Path: "admin/auth/login_with_oauth",
Inner: false, Inner: false,
Handler: c.Auth.LoginWithOauth, Handler: c.Auth.LoginWithOauth,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/auth/logout", Path: "admin/auth/logout",
Inner: true, Inner: true,
Handler: c.Auth.Logout, Handler: c.Auth.Logout,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/auth/logout_with_reason", Path: "admin/auth/logout_with_reason",
Inner: true, Inner: true,
Handler: c.Auth.LogoutWithReason, Handler: c.Auth.LogoutWithReason,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_profile", Path: "admin/user/get_profile",
Inner: true, Inner: true,
Handler: c.User.GetProfile, Handler: c.User.GetProfile,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_design", Path: "admin/user/get_design",
Inner: true, Inner: true,
Handler: c.Customization.GetUIDesign, Handler: c.Customization.GetUIDesign,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_users", Path: "admin/user/get_users",
Inner: true, Inner: true,
Handler: c.User.GetUsers, Handler: c.User.GetUsers,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_all_users", Path: "admin/user/get_all_users",
Inner: true, Inner: true,
Handler: c.User.GetAllUsers, Handler: c.User.GetAllUsers,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/create_user", Path: "admin/user/create_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_create"), Extra: cluster.RequireAdminPermission("user_create"),
Handler: c.User.CreateUser, Handler: c.User.CreateUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/update_user", Path: "admin/user/update_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_update"), Extra: cluster.RequireAdminPermission("user_update"),
Handler: c.User.UpdateUser, Handler: c.User.UpdateUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/delete_user", Path: "admin/user/delete_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_delete"), Extra: cluster.RequireAdminPermission("user_delete"),
Handler: c.User.DeleteUser, Handler: c.User.DeleteUser,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/block_user", Path: "admin/user/block_user",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("user_block"), Extra: cluster.RequireAdminPermission("user_block"),
Handler: c.User.Block, Handler: c.User.Block,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_by_id", Path: "admin/user/get_by_id",
Inner: true, Inner: true,
Handler: c.User.GetById, Handler: c.User.GetById,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/change_password", Path: "admin/user/change_password",
Inner: true, Inner: true,
Handler: c.User.ChangePassword, Handler: c.User.ChangePassword,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/all", Path: "admin/role/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_view"), Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Role.All, Handler: c.Role.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/user/get_permissions", Path: "admin/user/get_permissions",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_view"), Extra: cluster.RequireAdminPermission("role_view"),
Handler: c.Permissions.GetPermissions, Handler: c.Permissions.GetPermissions,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/create", Path: "admin/role/create",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_add"), Extra: cluster.RequireAdminPermission("role_add"),
Handler: c.Role.CreateRole, Handler: c.Role.CreateRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/update", Path: "admin/role/update",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_update"), Extra: cluster.RequireAdminPermission("role_update"),
Handler: c.Role.UpdateRole, Handler: c.Role.UpdateRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/role/delete", Path: "admin/role/delete",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("role_delete"), Extra: cluster.RequireAdminPermission("role_delete"),
Handler: c.Role.DeleteRole, Handler: c.Role.DeleteRole,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/session/all", Path: "admin/session/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("session_view"), Extra: cluster.RequireAdminPermission("session_view"),
Handler: c.Session.All, Handler: c.Session.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/session/revoke", Path: "admin/session/revoke",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("session_revoke"), Extra: cluster.RequireAdminPermission("session_revoke"),
Handler: c.Session.Revoke, Handler: c.Session.Revoke,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/all", Path: "admin/log/all",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("security_log_view"), Extra: cluster.RequireAdminPermission("security_log_view"),
Handler: c.Audit.All, Handler: c.Audit.All,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/events", Path: "admin/log/events",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"), Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.Events, Handler: c.Audit.Events,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/log/set_events", Path: "admin/log/set_events",
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("audit_management_view"), Extra: cluster.RequireAdminPermission("audit_management_view"),
Handler: c.Audit.SetEvents, Handler: c.Audit.SetEvents,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/secure/authenticate", Path: "admin/secure/authenticate",
Inner: true, Inner: true,
Handler: c.Secure.Authenticate, Handler: c.Secure.Authenticate,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/secure/authorize", Path: "admin/secure/authorize",
Inner: true, Inner: true,
Handler: c.Secure.Authorize, Handler: c.Secure.Authorize,
HttpMethod: http.MethodPost,
}, },
{ {
Path: "admin/ui_settings/oauth", Path: "admin/ui_settings/oauth",
Inner: false, Inner: false,
Handler: c.UiSettings.OauthSettings, 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,
}, },
} }
} }
+325
View File
@@ -0,0 +1,325 @@
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, domain.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, w http.ResponseWriter) error {
roles, err := s.roleService.All(ctx, domain.RoleAllRequest{})
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")
}
+3 -3
View File
@@ -11,12 +11,12 @@ type Permission struct {
permissions []domain.Permission permissions []domain.Permission
} }
func NewPermission(permissions []conf.Permission) *Permission { func NewPermission(permissions []conf.Permission) Permission {
return &Permission{ return Permission{
permissions: toDomain(permissions), permissions: toDomain(permissions),
} }
} }
func (s *Permission) All(_ context.Context) []domain.Permission { func (s Permission) All(_ context.Context) []domain.Permission {
return s.permissions return s.permissions
} }
+46 -35
View File
@@ -11,14 +11,9 @@ import (
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
) )
const (
roleNameLabel = "Название"
roleGroupLabel = "Группа ЕСК"
rolePermissionsLabel = "Разрешения"
)
type roleRoleRepo interface { type roleRoleRepo interface {
All(ctx context.Context) ([]entity.Role, error) 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) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
Update(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 Delete(ctx context.Context, id int) error
@@ -38,8 +33,17 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
} }
} }
func (u Role) All(ctx context.Context) ([]domain.Role, error) { func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
roles, err := u.roleRepo.All(ctx) 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)
}
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "get all roles") return nil, errors.WithMessage(err, "get all roles")
} }
@@ -64,9 +68,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
} }
role, err = u.roleRepo.InsertRole(ctx, entity.Role{ role, err = u.roleRepo.InsertRole(ctx, entity.Role{
Name: req.Name, Name: req.Name,
ExternalGroup: req.ExternalGroup, ExternalGroup: req.ExternalGroup,
Permissions: req.Permissions, ApplicationGroup: req.ApplicationGroup,
Permissions: req.Permissions,
}) })
if err != nil { if err != nil {
@@ -75,13 +80,15 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
slices.Sort(role.Permissions) slices.Sort(role.Permissions)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
roleNameLabel: "", "Название": "",
roleGroupLabel: "", "Группа ЕСК": "",
rolePermissionsLabel: []int{}, "Группа приложений": "",
"Разрешения": []int{},
}, map[string]any{ }, map[string]any{
roleNameLabel: role.Name, "Название": role.Name,
roleGroupLabel: role.ExternalGroup, "Группа ЕСК": role.ExternalGroup,
rolePermissionsLabel: role.Permissions, "Группа приложений": role.ApplicationGroup,
"Разрешения": role.Permissions,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
@@ -112,10 +119,11 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
oldRole := roles[0] oldRole := roles[0]
role, err := u.roleRepo.Update(ctx, entity.Role{ role, err := u.roleRepo.Update(ctx, entity.Role{
Id: req.Id, Id: req.Id,
Name: req.Name, Name: req.Name,
ExternalGroup: req.ExternalGroup, ExternalGroup: req.ExternalGroup,
Permissions: req.Permissions, ApplicationGroup: req.ApplicationGroup,
Permissions: req.Permissions,
}) })
if err != nil { if err != nil {
@@ -125,13 +133,15 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
slices.Sort(oldRole.Permissions) slices.Sort(oldRole.Permissions)
slices.Sort(role.Permissions) slices.Sort(role.Permissions)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
roleNameLabel: oldRole.Name, "Название": oldRole.Name,
roleGroupLabel: oldRole.ExternalGroup, "Группа ЕСК": oldRole.ExternalGroup,
rolePermissionsLabel: oldRole.Permissions, "Группа приложений": oldRole.ApplicationGroup,
"Разрешения": oldRole.Permissions,
}, map[string]any{ }, map[string]any{
roleNameLabel: role.Name, "Название": role.Name,
roleGroupLabel: role.ExternalGroup, "Группа ЕСК": role.ExternalGroup,
rolePermissionsLabel: role.Permissions, "Группа приложений": role.ApplicationGroup,
"Разрешения": role.Permissions,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff), fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
@@ -154,13 +164,14 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
func (u Role) toDomain(role entity.Role) domain.Role { func (u Role) toDomain(role entity.Role) domain.Role {
return domain.Role{ return domain.Role{
Id: role.Id, Id: role.Id,
Name: role.Name, Name: role.Name,
ExternalGroup: role.ExternalGroup, ExternalGroup: role.ExternalGroup,
Permissions: role.Permissions, ApplicationGroup: role.ApplicationGroup,
Immutable: role.Immutable, Permissions: role.Permissions,
Exclusive: role.Exclusive, Immutable: role.Immutable,
CreatedAt: role.CreatedAt, Exclusive: role.Exclusive,
UpdatedAt: role.UpdatedAt, CreatedAt: role.CreatedAt,
UpdatedAt: role.UpdatedAt,
} }
} }
+16 -23
View File
@@ -16,13 +16,6 @@ import (
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
const (
userFullNameLabel = "ФИО"
userDescriptionLabel = "Описание"
userEmailLabel = "Email"
userRolesLabel = "Роли (ID)"
)
type UserTransaction interface { type UserTransaction interface {
UserRepo UserRepo
UserRoleRepo UserRoleRepo
@@ -260,15 +253,15 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
slices.Sort(req.Roles) slices.Sort(req.Roles)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
userFullNameLabel: "", "ФИО": "",
userDescriptionLabel: "", "Описание": "",
userEmailLabel: "", "Email": "",
userRolesLabel: []int{}, "Роли (ID)": []int{},
}, map[string]any{ }, map[string]any{
userFullNameLabel: usr.FullName, "ФИО": usr.FullName,
userDescriptionLabel: req.Description, "Описание": req.Description,
userEmailLabel: req.Email, "Email": req.Email,
userRolesLabel: req.Roles, "Роли (ID)": req.Roles,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Создание пользователя %d. \n %s", usr.Id, diff), fmt.Sprintf("Пользователь. Создание пользователя %d. \n %s", usr.Id, diff),
@@ -349,15 +342,15 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
slices.Sort(req.Roles) slices.Sort(req.Roles)
diff := diffToString(map[string]any{ diff := diffToString(map[string]any{
userFullNameLabel: user.FullName, "ФИО": user.FullName,
userDescriptionLabel: user.Description, "Описание": user.Description,
userEmailLabel: user.Email, "Email": user.Email,
userRolesLabel: RolesIds(oldRoles), "Роли (ID)": RolesIds(oldRoles),
}, map[string]any{ }, map[string]any{
userFullNameLabel: updatedUser.FullName, "ФИО": updatedUser.FullName,
userDescriptionLabel: req.Description, "Описание": req.Description,
userEmailLabel: req.Email, "Email": req.Email,
userRolesLabel: req.Roles, "Роли (ID)": req.Roles,
}) })
u.auditService.SaveAuditAsync(ctx, adminId, u.auditService.SaveAuditAsync(ctx, adminId,
fmt.Sprintf("Пользователь. Изменение пользователя %d.\n %s", updatedUser.Id, diff), fmt.Sprintf("Пользователь. Изменение пользователя %d.\n %s", updatedUser.Id, diff),
+30 -32
View File
@@ -1,6 +1,7 @@
package tests_test package tests_test
import ( import (
"net/http"
"testing" "testing"
"time" "time"
@@ -12,13 +13,10 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx" "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/http/httpcli"
"github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
func TestAuditSuite(t *testing.T) { func TestAuditSuite(t *testing.T) {
@@ -31,7 +29,7 @@ type AuditSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
grpcCli *client.Client httpCli *httpcli.Client
} }
func (s *AuditSuite) SetupTest() { func (s *AuditSuite) SetupTest() {
@@ -75,20 +73,20 @@ func (s *AuditSuite) SetupTest() {
s.Require().NoError(err) s.Require().NoError(err)
s.insertAuditLogs() s.insertAuditLogs()
server, apiCli := grpct.TestServer(testInstance, cfg.Handler) server, cli := httpt.TestServer(s.test, cfg.Handler)
s.grpcCli = apiCli s.httpCli = cli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Shutdown() server.Close()
}) })
} }
func (s *AuditSuite) Test_Events_DefaultEvents() { func (s *AuditSuite) Test_Events_DefaultEvents() {
response := make([]domain.AuditEvent, 0) response := make([]domain.AuditEvent, 0)
err := s.grpcCli. err := s.httpCli.
Invoke("admin/log/events"). Post("admin/log/events").
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expectedEventList := map[string]string{ expectedEventList := map[string]string{
@@ -123,10 +121,10 @@ func (s *AuditSuite) Test_Events_SortEvents() {
s.Require().NoError(err) s.Require().NoError(err)
response := make([]domain.AuditEvent, 0) response := make([]domain.AuditEvent, 0)
err = s.grpcCli. err = s.httpCli.
Invoke("admin/log/events"). Post("admin/log/events").
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expectedSort := []bool{ expectedSort := []bool{
@@ -139,13 +137,13 @@ func (s *AuditSuite) Test_Events_SortEvents() {
} }
func (s *AuditSuite) Test_SetEvents_HappyPath() { func (s *AuditSuite) Test_SetEvents_HappyPath() {
err := s.grpcCli. err := s.httpCli.
Invoke("admin/log/set_events"). Post("admin/log/set_events").
JsonRequestBody([]domain.SetAuditEvent{ JsonRequestBody([]domain.SetAuditEvent{
{Event: entity.EventUserChanged, Enabled: true}, {Event: entity.EventUserChanged, Enabled: true},
{Event: entity.EventRoleChanged, Enabled: false}, {Event: entity.EventRoleChanged, Enabled: false},
}). }).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expectedEventList := map[string]bool{ expectedEventList := map[string]bool{
@@ -169,24 +167,24 @@ func (s *AuditSuite) Test_SetEvents_HappyPath() {
} }
func (s *AuditSuite) Test_SetEvents_InvalidEvent() { func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
err := s.grpcCli.Invoke("admin/log/set_events"). err := s.httpCli.Post("admin/log/set_events").
JsonRequestBody([]domain.SetAuditEvent{ JsonRequestBody([]domain.SetAuditEvent{
{Event: entity.EventUserChanged, Enabled: true}, {Event: entity.EventUserChanged, Enabled: true},
{Event: "новый#2", Enabled: false}, {Event: "новый#2", Enabled: false},
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
status, isStatus := status.FromError(err)
s.Require().True(isStatus) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.InvalidArgument, status.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusBadRequest, httpErr.StatusCode)
} }
func (s *AuditSuite) Test_All_Logs() { func (s *AuditSuite) Test_All_Logs() {
request := domain.AuditPageRequest{ request := domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 3,
Limit: 3, Offset: 5,
Offset: 5,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "user_id", Field: "user_id",
Type: "desc", Type: "desc",
@@ -194,11 +192,11 @@ func (s *AuditSuite) Test_All_Logs() {
} }
var response *domain.AuditResponse var response *domain.AuditResponse
err := s.grpcCli. err := s.httpCli.
Invoke("admin/log/all"). Post("admin/log/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 3) s.Require().Len(response.Items, 3)
@@ -212,11 +210,11 @@ func (s *AuditSuite) Test_All_Logs() {
request.Limit = 10 request.Limit = 10
request.Offset = 0 request.Offset = 0
err = s.grpcCli. err = s.httpCli.
Invoke("admin/log/all"). Post("admin/log/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 6) s.Require().Len(response.Items, 6)
+57 -50
View File
@@ -18,18 +18,15 @@ import (
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/test/fake" "github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/httpt"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx" "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/http/httpcli"
"github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt" "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) { func TestAuthTestSuite(t *testing.T) {
@@ -42,7 +39,7 @@ type AuthTestSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
grpcCli *client.Client httpCli *httpcli.Client
oauthCli *httpcli.Client oauthCli *httpcli.Client
oauthClientName string oauthClientName string
} }
@@ -81,11 +78,11 @@ func (s *AuthTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute) Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err) s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler) server, cli := httpt.TestServer(s.test, cfg.Handler)
s.grpcCli = apiCli s.httpCli = cli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Shutdown() server.Close()
mocksrv.Close() mocksrv.Close()
}) })
} }
@@ -99,13 +96,13 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
}) })
response := domain.LoginResponse{} response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login"). err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{ JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru", Email: "a@a.ru",
Password: "password", Password: "password",
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, response.Token) tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
@@ -115,16 +112,18 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
} }
func (s *AuthTestSuite) TestLoginNotFound() { func (s *AuthTestSuite) TestLoginNotFound() {
err := s.grpcCli.Invoke("admin/auth/login"). err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{ JsonRequestBody(domain.LoginRequest{
Email: "a1@a.ru", Email: "a1@a.ru",
Password: "password", Password: "password",
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.Unauthenticated, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
@@ -138,16 +137,18 @@ func (s *AuthTestSuite) TestBlockedUser() {
Blocked: true, Blocked: true,
}) })
err := s.grpcCli.Invoke("admin/auth/login"). err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{ JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru", Email: "a@a.ru",
Password: "password", Password: "password",
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.Unauthenticated, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
@@ -160,16 +161,18 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
Password: "password", Password: "password",
}) })
err := s.grpcCli.Invoke("admin/auth/login"). err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{ JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru", Email: "a@a.ru",
Password: "WrongPassword", Password: "WrongPassword",
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.Unauthenticated, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
} }
@@ -177,13 +180,13 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
func (s *AuthTestSuite) TestOauthLoginHappyPath() { func (s *AuthTestSuite) TestOauthLoginHappyPath() {
response := domain.LoginResponse{} response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). err := s.httpCli.Post("admin/auth/login_with_oauth").
JsonRequestBody(domain.LoginOauthRequest{ JsonRequestBody(domain.LoginOauthRequest{
AuthCode: "code", AuthCode: "code",
ClientName: s.oauthClientName, ClientName: s.oauthClientName,
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
user := entity.User{} user := entity.User{}
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1") s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
@@ -199,17 +202,19 @@ func (s *AuthTestSuite) TestOauthLoginHappyPath() {
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() { func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
response := domain.LoginResponse{} response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). err := s.httpCli.Post("admin/auth/login_with_oauth").
JsonRequestBody(domain.LoginOauthRequest{ JsonRequestBody(domain.LoginOauthRequest{
AuthCode: "code", AuthCode: "code",
ClientName: s.oauthClientName + fake.It[string](), ClientName: s.oauthClientName + fake.It[string](),
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.Unauthenticated, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
} }
func (s *AuthTestSuite) Test_Logout_HappyPath() { func (s *AuthTestSuite) Test_Logout_HappyPath() {
@@ -221,9 +226,9 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
CreatedAt: time.Time{}, CreatedAt: time.Time{},
ExpiredAt: time.Time{}, ExpiredAt: time.Time{},
}) })
err := s.grpcCli.Invoke("admin/auth/logout"). err := s.httpCli.Post("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213") tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
@@ -233,18 +238,16 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
} }
func (s *AuthTestSuite) Test_Logout_NotFound() { func (s *AuthTestSuite) Test_Logout_NotFound() {
err := s.grpcCli.Invoke("admin/auth/logout"). err := s.httpCli.Post("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, "0143218411981"). Header(domain.AdminAuthIdHeader, "0143218411981").
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
time.Sleep(time.Second) time.Sleep(time.Second)
audit := repository.NewAudit(s.db) audit := repository.NewAudit(s.db)
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{ auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 10,
Limit: 10, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "created_at", Field: "created_at",
Type: "desc", Type: "desc",
@@ -266,9 +269,9 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
CreatedAt: time.Time{}, CreatedAt: time.Time{},
ExpiredAt: time.Time{}, ExpiredAt: time.Time{},
}) })
err := s.grpcCli.Invoke("admin/auth/logout"). err := s.httpCli.Post("admin/auth/logout").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462") tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
@@ -292,20 +295,24 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
group.Go(func() error { group.Go(func() error {
start := time.Now() start := time.Now()
response := domain.LoginResponse{} response := domain.LoginResponse{}
err := s.grpcCli.Invoke("admin/auth/login"). err := s.httpCli.Post("admin/auth/login").
JsonRequestBody(domain.LoginRequest{ JsonRequestBody(domain.LoginRequest{
Email: "a@a.ru", Email: "a@a.ru",
Password: fmt.Sprintf("password %s", strconv.Itoa(index)), Password: fmt.Sprintf("password %s", strconv.Itoa(index)),
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(ctx) StatusCodeToError().
DoWithoutResponse(ctx)
s.Require().Error(err) s.Require().Error(err)
switch status.Code(err) { // nolint:exhaustive var httpErr httpcli.ErrorResponse
case codes.ResourceExhausted: s.Require().ErrorAs(err, &httpErr)
switch httpErr.StatusCode { // nolint:exhaustive
case http.StatusTooManyRequests:
tooManyRequestsErrorCount.Add(1) tooManyRequestsErrorCount.Add(1)
s.Require().True(time.Since(start) < time.Second) s.Require().True(time.Since(start) < time.Second)
case codes.Unauthenticated: case http.StatusUnauthorized:
unauthorizedErrorCount.Add(1) unauthorizedErrorCount.Add(1)
s.Require().True(time.Since(start) > time.Second) s.Require().True(time.Since(start) > time.Second)
default: default:
+9 -9
View File
@@ -9,10 +9,10 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx" "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"
"github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
) )
func TestCustomizationTestSuite(t *testing.T) { func TestCustomizationTestSuite(t *testing.T) {
@@ -25,7 +25,7 @@ type CustomizationTestSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
grpcCli *client.Client httpCli *httpcli.Client
} }
func (s *CustomizationTestSuite) SetupTest() { func (s *CustomizationTestSuite) SetupTest() {
@@ -44,21 +44,21 @@ func (s *CustomizationTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute) Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err) s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler) server, cli := httpt.TestServer(s.test, cfg.Handler)
s.grpcCli = apiCli s.httpCli = cli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Shutdown() server.Close()
}) })
} }
func (s *CustomizationTestSuite) TestGetDesign() { func (s *CustomizationTestSuite) TestGetDesign() {
response := conf.UIDesign{} response := conf.UIDesign{}
err := s.grpcCli. err := s.httpCli.
Invoke("admin/user/get_design"). Post("admin/user/get_design").
JsonRequestBody(struct{}{}). JsonRequestBody(struct{}{}).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expected := conf.UIDesign{ expected := conf.UIDesign{
Name: "test", Name: "test",
+7 -3
View File
@@ -42,9 +42,13 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
} }
q, args, err := query.New(). q, args, err := query.New().
Insert("roles"). Insert("roles").
Columns("name", "permissions"). Columns("name", "permissions", "application_group").
Values(role.Name, role.Permissions). Values(role.Name, role.Permissions, role.ApplicationGroup).
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id"). Suffix(`ON CONFLICT (name) DO UPDATE SET
name = EXCLUDED.name,
permissions = EXCLUDED.permissions,
application_group = EXCLUDED.application_group
RETURNING id`).
ToSql() ToSql()
if err != nil { if err != nil {
panic(errors.WithMessagef(err, "insert role")) panic(errors.WithMessagef(err, "insert role"))
+243
View File
@@ -0,0 +1,243 @@
// 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() {
resp, err := s.httpCli.Post("role/download").
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)
}
+2 -4
View File
@@ -49,10 +49,8 @@ func TestInactiveWorker(t *testing.T) {
require.True(user.Blocked) require.True(user.Blocked)
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{ list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 10,
Limit: 10, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "created_at", Field: "created_at",
Type: "desc", Type: "desc",
+173
View File
@@ -0,0 +1,173 @@
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
}
+19 -20
View File
@@ -12,11 +12,10 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx" "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/http/httpcli"
"github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
) )
func TestSecureSuite(t *testing.T) { func TestSecureSuite(t *testing.T) {
@@ -30,7 +29,7 @@ type SecureSuite struct {
test *test.Test test *test.Test
require *require.Assertions require *require.Assertions
db *dbt.TestDb db *dbt.TestDb
grpcCli *client.Client httpCli *httpcli.Client
} }
func (s *SecureSuite) SetupTest() { func (s *SecureSuite) SetupTest() {
@@ -44,11 +43,11 @@ func (s *SecureSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute) Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err) s.Require().NoError(err)
server, apiCli := grpct.TestServer(s.test, cfg.Handler) server, apiCli := httpt.TestServer(s.test, cfg.Handler)
s.test.T().Cleanup(func() { s.test.T().Cleanup(func() {
server.Shutdown() server.Close()
}) })
s.grpcCli = apiCli s.httpCli = apiCli
} }
func (s *SecureSuite) Test_Authenticate_HappyPath() { func (s *SecureSuite) Test_Authenticate_HappyPath() {
@@ -61,12 +60,12 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
}) })
result := domain.SecureAuthResponse{} result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate"). err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{ JsonRequestBody(domain.SecureAuthRequest{
Token: "happy_path", Token: "happy_path",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{ s.require.Equal(domain.SecureAuthResponse{
Authenticated: true, Authenticated: true,
@@ -85,12 +84,12 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
}) })
result := domain.SecureAuthResponse{} result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate"). err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{ JsonRequestBody(domain.SecureAuthRequest{
Token: "revoked", Token: "revoked",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{ s.require.Equal(domain.SecureAuthResponse{
Authenticated: false, Authenticated: false,
@@ -109,12 +108,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
}) })
result := domain.SecureAuthResponse{} result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate"). err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{ JsonRequestBody(domain.SecureAuthRequest{
Token: "expired", Token: "expired",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{ s.require.Equal(domain.SecureAuthResponse{
Authenticated: false, Authenticated: false,
@@ -125,12 +124,12 @@ func (s *SecureSuite) Test_Authenticate_Expired() {
func (s *SecureSuite) Test_Authenticate_NotFound() { func (s *SecureSuite) Test_Authenticate_NotFound() {
result := domain.SecureAuthResponse{} result := domain.SecureAuthResponse{}
err := s.grpcCli.Invoke("admin/secure/authenticate"). err := s.httpCli.Post("admin/secure/authenticate").
JsonRequestBody(domain.SecureAuthRequest{ JsonRequestBody(domain.SecureAuthRequest{
Token: "not_found", Token: "not_found",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.Equal(domain.SecureAuthResponse{ s.require.Equal(domain.SecureAuthResponse{
Authenticated: false, Authenticated: false,
@@ -165,35 +164,35 @@ func (s *SecureSuite) Test_Authorize_HappyPath() {
}) })
result := domain.SecureAuthzResponse{} result := domain.SecureAuthzResponse{}
err := s.grpcCli.Invoke("admin/secure/authorize"). err := s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{ JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId), AdminId: int(userId),
Permission: "perm1", Permission: "perm1",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.True(result.Authorized) s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{} result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize"). err = s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{ JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId), AdminId: int(userId),
Permission: "perm2", Permission: "perm2",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.True(result.Authorized) s.require.True(result.Authorized)
result = domain.SecureAuthzResponse{} result = domain.SecureAuthzResponse{}
err = s.grpcCli.Invoke("admin/secure/authorize"). err = s.httpCli.Post("admin/secure/authorize").
JsonRequestBody(domain.SecureAuthzRequest{ JsonRequestBody(domain.SecureAuthzRequest{
AdminId: int(userId), AdminId: int(userId),
Permission: "perm3", Permission: "perm3",
}). }).
JsonResponseBody(&result). JsonResponseBody(&result).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.require.NoError(err) s.require.NoError(err)
s.require.False(result.Authorized) s.require.False(result.Authorized)
} }
+24 -29
View File
@@ -14,11 +14,10 @@ import (
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/bgjobx" "github.com/txix-open/isp-kit/bgjobx"
"github.com/txix-open/isp-kit/dbx" "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/http/httpcli"
"github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
) )
func TestSessionSuite(t *testing.T) { func TestSessionSuite(t *testing.T) {
@@ -32,7 +31,7 @@ type SessionSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
config assembly.Config config assembly.Config
grpcCli *client.Client httpCli *httpcli.Client
} }
func (s *SessionSuite) SetupTest() { func (s *SessionSuite) SetupTest() {
@@ -77,11 +76,11 @@ func (s *SessionSuite) SetupTest() {
s.config = config s.config = config
server, apiCli := grpct.TestServer(testInstance, s.config.Handler) server, cli := httpt.TestServer(s.test, config.Handler)
s.grpcCli = apiCli s.httpCli = cli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Shutdown() server.Close()
}) })
} }
@@ -117,18 +116,16 @@ func (s *SessionSuite) Test_All_Session() {
// Дефолт сортировка, лимит и оффсет // Дефолт сортировка, лимит и оффсет
request := domain.SessionPageRequest{ request := domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 5,
Limit: 5, Offset: 1,
Offset: 1,
},
} }
var response *domain.SessionResponse var response *domain.SessionResponse
err := s.grpcCli. err := s.httpCli.
Invoke("admin/session/all"). Post("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 2) s.Require().Len(response.Items, 2)
@@ -144,11 +141,11 @@ func (s *SessionSuite) Test_All_Session() {
To: timeNow.Add(24 * time.Hour), To: timeNow.Add(24 * time.Hour),
}, },
} }
err = s.grpcCli. err = s.httpCli.
Invoke("admin/session/all"). Post("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 2) s.Require().Len(response.Items, 2)
@@ -163,11 +160,11 @@ func (s *SessionSuite) Test_All_Session() {
Type: "asc", Type: "asc",
} }
err = s.grpcCli. err = s.httpCli.
Invoke("admin/session/all"). Post("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 3) s.Require().Len(response.Items, 3)
@@ -183,11 +180,11 @@ func (s *SessionSuite) Test_All_Session() {
Status: []string{entity.TokenStatusExpired}, Status: []string{entity.TokenStatusExpired},
} }
err = s.grpcCli. err = s.httpCli.
Invoke("admin/session/all"). Post("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 1) s.Require().Len(response.Items, 1)
@@ -208,10 +205,8 @@ func (s *SessionSuite) Test_All_Session() {
} }
request = domain.SessionPageRequest{ request = domain.SessionPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 5,
Limit: 5, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "id", Field: "id",
Type: "desc", Type: "desc",
@@ -220,11 +215,11 @@ func (s *SessionSuite) Test_All_Session() {
Id: new(2), Id: new(2),
}, },
} }
err = s.grpcCli. err = s.httpCli.
Invoke("admin/session/all"). Post("admin/session/all").
JsonRequestBody(request). JsonRequestBody(request).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 5) s.Require().Len(response.Items, 5)
+14 -13
View File
@@ -4,23 +4,22 @@ import (
"isp-admin-service/assembly" "isp-admin-service/assembly"
"isp-admin-service/conf" "isp-admin-service/conf"
"isp-admin-service/domain" "isp-admin-service/domain"
"net/http"
"net/url" "net/url"
"testing" "testing"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"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"
"github.com/txix-open/isp-kit/test/fake" "github.com/txix-open/isp-kit/test/fake"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type UiSettingsSuite struct { type UiSettingsSuite struct {
suite.Suite suite.Suite
test *test.Test test *test.Test
apiCli *client.Client apiCli *httpcli.Client
oauthClientSetting conf.OauthClientConfig oauthClientSetting conf.OauthClientConfig
baseOauthUrl string baseOauthUrl string
} }
@@ -54,18 +53,18 @@ func (s *UiSettingsSuite) SetupTest() {
Config(s.T().Context(), remote, 0) Config(s.T().Context(), remote, 0)
s.Require().NoError(err) s.Require().NoError(err)
_, s.apiCli = grpct.TestServer(s.test, cfg.Handler) _, s.apiCli = httpt.TestServer(s.test, cfg.Handler)
} }
func (s *UiSettingsSuite) Test_HappyPath() { func (s *UiSettingsSuite) Test_HappyPath() {
var resp domain.UiOauthSetting var resp domain.UiOauthSetting
err := s.apiCli.Invoke("admin/ui_settings/oauth"). err := s.apiCli.Post("admin/ui_settings/oauth").
JsonRequestBody(domain.ClientNameRequest{ JsonRequestBody(domain.ClientNameRequest{
ClientName: s.oauthClientSetting.ClientName, ClientName: s.oauthClientSetting.ClientName,
}). }).
JsonResponseBody(&resp). JsonResponseBody(&resp).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
loginURL, err := url.Parse(resp.LoginUrl) loginURL, err := url.Parse(resp.LoginUrl)
@@ -93,13 +92,15 @@ func (s *UiSettingsSuite) Test_HappyPath() {
} }
func (s *UiSettingsSuite) Test_UnknownClient() { func (s *UiSettingsSuite) Test_UnknownClient() {
err := s.apiCli.Invoke("admin/ui_settings/oauth"). err := s.apiCli.Post("admin/ui_settings/oauth").
JsonRequestBody(domain.ClientNameRequest{ JsonRequestBody(domain.ClientNameRequest{
ClientName: s.oauthClientSetting.ClientName + fake.It[string](), ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.Unauthenticated, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusUnauthorized, httpErr.StatusCode)
} }
+107 -99
View File
@@ -2,11 +2,12 @@ package tests_test
import ( import (
"context" "context"
"encoding/json"
"net/http"
"strconv" "strconv"
"testing" "testing"
"time" "time"
"github.com/txix-open/isp-kit/grpc/apierrors"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"isp-admin-service/assembly" "isp-admin-service/assembly"
@@ -19,13 +20,10 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/suite" "github.com/stretchr/testify/suite"
"github.com/txix-open/isp-kit/dbx" "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/http/httpcli"
"github.com/txix-open/isp-kit/test" "github.com/txix-open/isp-kit/test"
"github.com/txix-open/isp-kit/test/dbt" "github.com/txix-open/isp-kit/test/dbt"
"github.com/txix-open/isp-kit/test/grpct" "github.com/txix-open/isp-kit/test/httpt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
) )
type tokenService interface { type tokenService interface {
@@ -42,7 +40,7 @@ type UserTestSuite struct {
test *test.Test test *test.Test
db *dbt.TestDb db *dbt.TestDb
grpcCli *client.Client apiCli *httpcli.Client
httpCli *httpcli.Client httpCli *httpcli.Client
tokenService tokenService tokenService tokenService
} }
@@ -60,11 +58,11 @@ func (s *UserTestSuite) SetupTest() {
Config(s.T().Context(), remote, time.Minute) Config(s.T().Context(), remote, time.Minute)
s.Require().NoError(err) s.Require().NoError(err)
server, apiCli := grpct.TestServer(testInstance, cfg.Handler) server, apiCli := httpt.TestServer(testInstance, cfg.Handler)
s.grpcCli = apiCli s.apiCli = apiCli
testInstance.T().Cleanup(func() { testInstance.T().Cleanup(func() {
server.Shutdown() server.Close()
}) })
tokenRep := repository.NewToken(s.db) tokenRep := repository.NewToken(s.db)
@@ -90,10 +88,10 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
}) })
response := domain.AdminUserShort{} response := domain.AdminUserShort{}
err := s.grpcCli.Invoke("admin/user/get_profile"). err := s.apiCli.Post("admin/user/get_profile").
JsonResponseBody(&response). JsonResponseBody(&response).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expected := domain.AdminUserShort{ expected := domain.AdminUserShort{
FirstName: "name", FirstName: "name",
@@ -117,13 +115,14 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
Password: "password", Password: "password",
}) })
err := s.grpcCli.Invoke("admin/user/get_profile"). err := s.apiCli.Post("admin/user/get_profile").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err) var httpErr httpcli.ErrorResponse
s.Require().True(ok) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(codes.NotFound, st.Code()) s.Require().Equal(http.StatusNotFound, httpErr.StatusCode)
} }
func (s *UserTestSuite) TestGetProfileOauth() { func (s *UserTestSuite) TestGetProfileOauth() {
@@ -145,11 +144,11 @@ func (s *UserTestSuite) TestGetProfileOauth() {
}) })
response := domain.AdminUserShort{} response := domain.AdminUserShort{}
err := s.grpcCli. err := s.apiCli.
Invoke("admin/user/get_profile"). Post("admin/user/get_profile").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expected := domain.AdminUserShort{ expected := domain.AdminUserShort{
FirstName: "name", FirstName: "name",
@@ -184,12 +183,10 @@ func (s *UserTestSuite) TestGetUsers() {
email := "a1@" email := "a1@"
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users"). err := s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 5,
Limit: 5, Offset: 1,
Offset: 1,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "email", Field: "email",
Type: "asc", Type: "asc",
@@ -200,7 +197,7 @@ func (s *UserTestSuite) TestGetUsers() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
roles := []int{int(roleId1), int(roleId2)} roles := []int{int(roleId1), int(roleId2)}
@@ -212,12 +209,10 @@ func (s *UserTestSuite) TestGetUsers() {
s.Require().EqualValues(roles, response.Items[1].Roles) s.Require().EqualValues(roles, response.Items[1].Roles)
email = "test@mail.ru" email = "test@mail.ru"
err = s.grpcCli.Invoke("admin/user/get_users"). err = s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 10,
Limit: 10, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "id", Field: "id",
Type: "asc", Type: "asc",
@@ -228,7 +223,7 @@ func (s *UserTestSuite) TestGetUsers() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Empty(response.Items) s.Require().Empty(response.Items)
} }
@@ -251,7 +246,10 @@ func (s *UserTestSuite) TestAllGetUsers() {
InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)}) InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)})
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context()) err := s.apiCli.Post("admin/user/get_all_users").
JsonResponseBody(&response).
StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 7) s.Require().Len(response.Items, 7)
@@ -296,12 +294,10 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
}) })
response := domain.UsersResponse{} response := domain.UsersResponse{}
err = s.grpcCli.Invoke("admin/user/get_users"). err = s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 5,
Limit: 5, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "lastSessionCreatedAt", Field: "lastSessionCreatedAt",
Type: "desc", Type: "desc",
@@ -314,7 +310,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 2) s.Require().Len(response.Items, 2)
@@ -332,12 +328,10 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"}) userIdAL := InsertUser(s.db, entity.User{Email: "a1@d.ru", FirstName: "А", LastName: "Л", FullName: "Л А"})
response := domain.UsersResponse{} response := domain.UsersResponse{}
err := s.grpcCli.Invoke("admin/user/get_users"). err := s.apiCli.Post("admin/user/get_users").
JsonRequestBody(domain.UsersPageRequest{ JsonRequestBody(domain.UsersPageRequest{
LimitOffestParams: domain.LimitOffestParams{ //nolint:modernize Limit: 10,
Limit: 10, Offset: 0,
Offset: 0,
},
Order: &domain.OrderParams{ Order: &domain.OrderParams{
Field: "userId", Field: "userId",
Type: "asc", Type: "asc",
@@ -347,7 +341,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
}, },
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Len(response.Items, 4) s.Require().Len(response.Items, 4)
@@ -364,9 +358,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
s.db.Must().SelectRow(&preCount, "select count(*) from users") s.db.Must().SelectRow(&preCount, "select count(*) from users")
response := entity.User{} response := entity.User{}
err := s.grpcCli. err := s.apiCli.
Invoke("admin/user/create_user"). Post("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.CreateUserRequest{ JsonRequestBody(domain.CreateUserRequest{
FirstName: "name", FirstName: "name",
LastName: "surname", LastName: "surname",
@@ -374,7 +368,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
Password: "password", Password: "password",
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
postCount := 0 postCount := 0
@@ -392,9 +386,9 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
s.db.Must().SelectRow(&preCount, "select count(*) from users") s.db.Must().SelectRow(&preCount, "select count(*) from users")
response := entity.User{} response := entity.User{}
err := s.grpcCli. err := s.apiCli.
Invoke("admin/user/create_user"). Post("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.CreateUserRequest{ JsonRequestBody(domain.CreateUserRequest{
FirstName: "name", FirstName: "name",
LastName: "surname", LastName: "surname",
@@ -402,7 +396,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
Password: "password", Password: "password",
}). }).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
postCount := 0 postCount := 0
@@ -415,20 +409,22 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
func (s *UserTestSuite) TestCreateUserAlreadyExist() { func (s *UserTestSuite) TestCreateUserAlreadyExist() {
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"}) id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
err := s.grpcCli. err := s.apiCli.
Invoke("admin/user/create_user"). Post("admin/user/create_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(domain.CreateUserRequest{ JsonRequestBody(domain.CreateUserRequest{
FirstName: "name", FirstName: "name",
LastName: "surname", LastName: "surname",
Email: "exists@a.ru", Email: "exists@a.ru",
Password: "password", Password: "password",
}). }).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.AlreadyExists, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
} }
func (s *AuthTestSuite) TestUpdateUserHappyPath() { func (s *AuthTestSuite) TestUpdateUserHappyPath() {
@@ -440,12 +436,11 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
Email: "update@a.ru", Email: "update@a.ru",
} }
response := domain.User{} response := domain.User{}
err := s.grpcCli. err := s.httpCli.Post("admin/user/update_user").
Invoke("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(req). JsonRequestBody(req).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expected := domain.UpdateUserRequest{ expected := domain.UpdateUserRequest{
Id: response.Id, Id: response.Id,
@@ -467,12 +462,11 @@ func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
Email: "oauth@a.ru", Email: "oauth@a.ru",
} }
response := domain.User{} response := domain.User{}
err := s.grpcCli. err := s.httpCli.Post("admin/user/update_user").
Invoke("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
JsonRequestBody(req). JsonRequestBody(req).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
expected := domain.UpdateUserRequest{ expected := domain.UpdateUserRequest{
Id: response.Id, Id: response.Id,
@@ -495,15 +489,16 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
LastName: "surname", LastName: "surname",
Email: "a_exists@a.ru", Email: "a_exists@a.ru",
} }
err := s.grpcCli. err := s.httpCli.Post("admin/user/update_user").
Invoke("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(req). JsonRequestBody(req).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.AlreadyExists, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
} }
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() { func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
@@ -518,15 +513,16 @@ func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
LastName: "surname", LastName: "surname",
Email: "a_exists@a.ru", Email: "a_exists@a.ru",
} }
err := s.grpcCli. err := s.httpCli.Post("admin/user/update_user").
Invoke("admin/user/update_user"). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(req). JsonRequestBody(req).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
st, ok := status.FromError(err)
s.Require().True(ok) var httpErr httpcli.ErrorResponse
s.Require().Equal(codes.AlreadyExists, st.Code()) s.Require().ErrorAs(err, &httpErr)
s.Require().Equal(http.StatusConflict, httpErr.StatusCode)
} }
func (s *UserTestSuite) TestDeleteUsers() { func (s *UserTestSuite) TestDeleteUsers() {
@@ -536,12 +532,12 @@ func (s *UserTestSuite) TestDeleteUsers() {
InsertUser(s.db, entity.User{Email: "a_del@c.ru"}) InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
response := domain.DeleteResponse{} response := domain.DeleteResponse{}
err := s.grpcCli. err := s.apiCli.
Invoke("admin/user/delete_user"). Post("admin/user/delete_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}). JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}).
JsonResponseBody(&response). JsonResponseBody(&response).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
s.Require().Equal(2, response.Deleted) s.Require().Equal(2, response.Deleted)
@@ -567,10 +563,11 @@ func (s *UserTestSuite) TestBlockUser() {
UpdatedAt: time.Now(), UpdatedAt: time.Now(),
}) })
err := s.grpcCli.Invoke("admin/user/block_user"). err := s.apiCli.Post("admin/user/block_user").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(id))).
StatusCodeToError().
JsonRequestBody(domain.IdRequest{UserId: int(id)}). JsonRequestBody(domain.IdRequest{UserId: int(id)}).
Do(s.T().Context()) DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id) user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id)
@@ -598,20 +595,31 @@ func (s *UserTestSuite) TestChangePasswordUser() {
// check for err when invalid data // check for err when invalid data
invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"} invalidReq := domain.ChangePasswordRequest{OldPassword: "invalid", NewPassword: "new_password"}
err := s.grpcCli.Invoke("admin/user/change_password"). err := s.apiCli.Post("admin/user/change_password").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
JsonRequestBody(invalidReq). JsonRequestBody(invalidReq).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().Error(err) s.Require().Error(err)
err = apierrors.FromError(err)
s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword)) 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)
// change password // change password
changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"} changePswReq := domain.ChangePasswordRequest{OldPassword: "password", NewPassword: "new_password"}
err = s.grpcCli.Invoke("admin/user/change_password"). err = s.apiCli.Post("admin/user/change_password").
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). Header(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))).
JsonRequestBody(changePswReq). JsonRequestBody(changePswReq).
Do(s.T().Context()) StatusCodeToError().
DoWithoutResponse(s.T().Context())
s.Require().NoError(err) s.Require().NoError(err)
+3
View File
@@ -13,6 +13,9 @@
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype"> <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"> <img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
</a> </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"> <a href="https://codecov.io/gh/gabriel-vasile/mimetype">
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg"> <img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
</a> </a>
+142 -29
View File
@@ -46,12 +46,14 @@ type cdf struct {
satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input
satEntries int // number of valid SAT entries reachable through satSecs satEntries int // number of valid SAT entries reachable through satSecs
firstSSAT int32 firstSSAT int32
ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain
dirRaw []byte // directory stream bytes (entries are decoded on demand) dirRaw []byte // directory stream bytes (entries are decoded on demand)
sst []byte // short-stream pool (root storage's stream) sst []byte // short-stream pool (root storage's stream)
sstBuilt bool // whether sst was already loaded (it is loaded lazily) sstBuilt bool // whether sst was already loaded (it is loaded lazily)
rootStreamFirst int32 // first sector of the root storage short-stream pool rootStreamFirst int32 // first sector of the root storage short-stream pool
rootStreamSize uint32 // size of the root storage short-stream pool rootStreamSize uint32 // size of the root storage short-stream pool
rootStorageUUID []byte rootChild int32 // directory id of the root storage's child tree
rootStorageUUID [16]byte
} }
// parse reads the entire on-disk structure required for type detection. It // parse reads the entire on-disk structure required for type detection. It
@@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool {
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]} masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
c.buildSAT(masterSAT, firstMSAT, nMSAT) c.buildSAT(masterSAT, firstMSAT, nMSAT)
c.buildSSAT()
c.dirRaw = c.readLong(firstDirSec, 0) c.dirRaw = c.readLong(firstDirSec, 0)
c.rootStreamFirst = -1 c.rootStreamFirst = -1
c.rootChild = -1
var d dirEntry var d dirEntry
for i, n := 0, c.dirLen(); i < n; i++ { for i, n := 0, c.dirLen(); i < n; i++ {
c.dirAt(i, &d) c.dirAt(i, &d)
if d.typ != dirTypeRootStorage || d.streamFirst < 0 { if d.typ != dirTypeRootStorage {
continue continue
} }
c.rootStorageUUID = d.storageUUID[:] copy(c.rootStorageUUID[:], d.storageUUID[:])
c.rootChild = d.child
// Record where the short-stream pool lives; it is loaded lazily by // Record where the short-stream pool lives; it is loaded lazily by
// shortStream the first time a short stream is actually read. // shortStream the first time a short stream is actually read.
c.rootStreamFirst = d.streamFirst if d.streamFirst >= 0 {
c.rootStreamSize = d.size c.rootStreamFirst = d.streamFirst
c.rootStreamSize = d.size
}
break break
} }
return true 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 { func (c *cdf) detect() CDFType {
for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} { for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} {
if t, ok := c.detectFromSummary(name); ok { if t, ok := c.detectFromSummary(name); ok {
return t return t
} }
} }
var d dirEntry for it := c.rootChildren(); it.next(); {
for i, n := 0, c.dirLen(); i < n; i++ { if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok {
c.dirAt(i, &d)
if t, ok := lookupSection(d.nameBytes(), d.typ); ok {
return t return t
} }
} }
@@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType {
// derive a CDFType from the root-storage CLSID, the property NameOfApplication, // derive a CDFType from the root-storage CLSID, the property NameOfApplication,
// and finally the names of sibling user streams. // and finally the names of sibling user streams.
func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) { if bytes.Equal(c.rootStorageUUID[:], msiCLSID) {
return CDFTypeInstaller, true return CDFTypeInstaller, true
} }
raw, ok := c.userStream(streamName) raw, ok := c.userStream(streamName)
@@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
return t, true return t, true
} }
} }
for i, n := 0, c.dirLen(); i < n; i++ { for it := c.rootChildren(); it.next(); {
var d dirEntry if it.d.nameLen == 0 {
c.dirAt(i, &d)
if d.nameLen == 0 {
continue continue
} }
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok { if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok {
return t, true return t, true
} }
} }
@@ -164,6 +237,9 @@ type dirEntry struct {
name [32]byte name [32]byte
nameLen uint8 nameLen uint8
typ 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 streamFirst int32
size uint32 size uint32
storageUUID [16]byte storageUUID [16]byte
@@ -172,23 +248,56 @@ type dirEntry struct {
// nameBytes returns the decoded ASCII name without copying. // nameBytes returns the decoded ASCII name without copying.
func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] } func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] }
func (c *cdf) ssatAt(i int32) int32 { // 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
for sid := c.firstSSAT; sid >= 0; { for sid := c.firstSSAT; sid >= 0; {
if int(sid) >= c.satLen() { if int(sid) >= c.satLen() {
break // SAT is truncated; stop collecting break // SAT is truncated; stop collecting
} }
buf, ok := c.sector(sid) if _, ok := c.sector(sid); !ok {
if !ok {
break break
} }
lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32 binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id
if i < lbuf { buf = append(buf, tmp[:]...)
return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id if len(buf)/4 > maxIDs {
break // cyclic SAT chain; stop allocating
} }
i -= lbuf
sid = c.satAt(sid) sid = c.satAt(sid)
} }
return -1 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:]))
} }
// shortStream returns the root storage short-stream pool, loading it on first // shortStream returns the root storage short-stream pool, loading it on first
@@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte {
} }
off := int(off64) off := int(off64)
out = append(out, sst[off:off+c.shortSecSize]...) 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) { if len(out) >= len(sst) {
break // chain longer than the pool: cyclic SSAT, stop break // chain longer than the pool: cyclic SSAT, stop
} }
@@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) {
} }
out.nameLen = k out.nameLen = k
out.typ = raw[66] 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.streamFirst = readSecID(raw[116:120])
out.size = binary.LittleEndian.Uint32(raw[120:]) out.size = binary.LittleEndian.Uint32(raw[120:])
copy(out.storageUUID[:], raw[80:96]) copy(out.storageUUID[:], raw[80:96])
} }
// userStream finds a user stream by name and returns its bytes. // userStream finds a root-level user stream by name and returns its bytes.
func (c *cdf) userStream(name string) ([]byte, bool) { func (c *cdf) userStream(name string) ([]byte, bool) {
var d dirEntry for it := c.rootChildren(); it.next(); {
for i, n := 0, c.dirLen(); i < n; i++ { if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name {
c.dirAt(i, &d) buf := c.readChain(it.d.streamFirst, it.d.size)
if d.typ == dirTypeUserStream && string(d.nameBytes()) == name {
buf := c.readChain(d.streamFirst, d.size)
if buf == nil { if buf == nil {
return nil, false return nil, false
} }
+15 -12
View File
@@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool {
// AAC matches an Advanced Audio Coding file. // AAC matches an Advanced Audio Coding file.
func AAC(raw []byte, _ uint32) bool { func AAC(raw []byte, _ uint32) bool {
return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9)) return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9)
} }
// MP3 matches a .mp3 file. // MP3 matches a .mp3 file.
@@ -128,27 +128,30 @@ func id3v2(raw []byte) bool {
} }
size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9]) size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9])
// Disallow too big frames, let's say 10MB. // The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB
return size > 0 && size < 10*1024*1024 // 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)
} }
// Wav matches a Waveform Audio File Format file. // Wav matches a Waveform Audio File Format file.
func Wav(raw []byte, limit uint32) bool { func Wav(raw []byte, limit uint32) bool {
return len(raw) > 12 && return iff(raw, []byte("RIFF"), []byte("WAVE"))
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45})
} }
// Aiff matches Audio Interchange File Format file. // Aiff matches Audio Interchange File Format file.
func Aiff(raw []byte, limit uint32) bool { func Aiff(raw []byte, limit uint32) bool {
return len(raw) > 12 && return iff(raw, []byte("FORM"), []byte("AIFF"))
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. // Qcp matches a Qualcomm Pure Voice file.
func Qcp(raw []byte, limit uint32) bool { func Qcp(raw []byte, limit uint32) bool {
return len(raw) > 12 && return iff(raw, []byte("RIFF"), []byte("QLCM"))
bytes.Equal(raw[:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte("QLCM"))
} }
+9 -16
View File
@@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool {
return slices.Contains(dbfTypes, raw[0]) return slices.Contains(dbfTypes, raw[0])
} }
// ElfObj matches an object file. func elfType(raw []byte, t byte) bool {
func ElfObj(raw []byte, limit uint32) bool { return len(raw) > 17 &&
return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) || ((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t))
(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. // ElfExe matches an executable file.
func ElfExe(raw []byte, limit uint32) bool { func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 0x02) }
return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x02))
}
// ElfLib matches a shared library file. // ElfLib matches a shared library file.
func ElfLib(raw []byte, limit uint32) bool { func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 0x03) }
return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x03))
}
// ElfDump matches a core dump file. // ElfDump matches a core dump file.
func ElfDump(raw []byte, limit uint32) bool { func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) }
return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) ||
(raw[16] == 0x00 && raw[17] == 0x04))
}
// Dcm matches a DICOM medical format file. // Dcm matches a DICOM medical format file.
func Dcm(raw []byte, limit uint32) bool { func Dcm(raw []byte, limit uint32) bool {
+1 -3
View File
@@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool {
// Webp matches a WebP file. // Webp matches a WebP file.
func Webp(raw []byte, _ uint32) bool { func Webp(raw []byte, _ uint32) bool {
return len(raw) > 12 && return iff(raw, []byte("RIFF"), []byte("WEBP"))
bytes.Equal(raw[0:4], []byte("RIFF")) &&
bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50})
} }
// Dwg matches a CAD drawing file. // Dwg matches a CAD drawing file.
+1 -13
View File
@@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool {
return false return false
} }
func markupCheck(sig, raw []byte) bool { func markupCheck(sig, raw []byte) bool {
if len(raw) < len(sig)+1 { if !ciCheck(sig, raw) {
return false 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. // Next byte must be space or right angle bracket.
if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' { if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' {
return false return false
} }
return true return true
} }
+31 -59
View File
@@ -46,26 +46,16 @@ func Ole(raw []byte, limit uint32) bool {
return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1})
} }
// Doc matches a Microsoft Word 97-2003 file. // cdfOrClsid checks if the raw input is detected as the given CDF type, and if
// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py // the CDF parser returns a generic result, falls back to matching root storage CLSIDs.
func Doc(raw []byte, _ uint32) bool { func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
fromParsing := cdf.Detect(raw) fromParsing := cdf.Detect(raw)
if fromParsing == cdf.CDFTypeDoc { if fromParsing == want {
return true return true
} }
if fromParsing != cdf.CDFTypeGeneric { if fromParsing != cdf.CDFTypeGeneric {
return false 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 { for _, clsid := range clsids {
if matchOleClsid(raw, clsid) { if matchOleClsid(raw, clsid) {
return true return true
@@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool {
return false 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. // Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation.
func Ppt(raw []byte, limit uint32) bool { func Ppt(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw) if cdfOrClsid(raw, cdf.CDFTypePpt,
if fromParsing == cdf.CDFTypePpt { []byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
return true 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8},
} []byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
if fromParsing != cdf.CDFTypeGeneric { 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3},
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 return true
} }
@@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool {
// Xls matches a Microsoft Excel 97-2003 file. // Xls matches a Microsoft Excel 97-2003 file.
func Xls(raw []byte, limit uint32) bool { func Xls(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw) if cdfOrClsid(raw, cdf.CDFTypeXls,
if fromParsing == cdf.CDFTypeXls { []byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
return true []byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
} ) {
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 return true
} }
@@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool {
// Msg matches a Microsoft Outlook email file. // Msg matches a Microsoft Outlook email file.
func Msg(raw []byte, limit uint32) bool { func Msg(raw []byte, limit uint32) bool {
fromParsing := cdf.Detect(raw) return cdfOrClsid(raw, cdf.CDFTypeMsg,
if fromParsing == cdf.CDFTypeMsg { []byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
return true 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
} )
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. // Msi matches a Microsoft Windows Installer file.
+3
View File
@@ -15,6 +15,9 @@ targets:
- name: github - name: github
tagPrefix: otel/otlp/v tagPrefix: otel/otlp/v
tagOnly: true tagOnly: true
- name: github
tagPrefix: cron/v
tagOnly: true
- name: github - name: github
tagPrefix: echo/v tagPrefix: echo/v
tagOnly: true tagOnly: true
+35
View File
@@ -1,5 +1,40 @@
# Changelog # 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 ## 0.49.0
### Breaking Changes 🛠 ### Breaking Changes 🛠
+6 -4
View File
@@ -305,6 +305,8 @@ func (t Type) String() string {
return "invalid" return "invalid"
} }
const arrayType = "array"
// mapTypesToStr is a map from attribute.Type to the primitive types the server understands. // 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 // https://develop.sentry.dev/sdk/foundations/data-model/attributes/#primitive-types
var mapTypesToStr = map[Type]string{ var mapTypesToStr = map[Type]string{
@@ -313,9 +315,9 @@ var mapTypesToStr = map[Type]string{
INT64: "integer", INT64: "integer",
FLOAT64: "double", FLOAT64: "double",
STRING: "string", STRING: "string",
BOOLSLICE: "array", BOOLSLICE: arrayType,
INT64SLICE: "array", INT64SLICE: arrayType,
FLOAT64SLICE: "array", FLOAT64SLICE: arrayType,
STRINGSLICE: "array", STRINGSLICE: arrayType,
UINT64: "integer", // wire format: same "integer" type UINT64: "integer", // wire format: same "integer" type
} }
+85 -9
View File
@@ -133,8 +133,8 @@ type ClientOptions struct {
// The DSN to use. If the DSN is not set, the client is effectively // The DSN to use. If the DSN is not set, the client is effectively
// disabled. // disabled.
Dsn string Dsn string
// In debug mode, the debug information is printed to stdout to help you // In debug mode, diagnostic information is written to DebugWriter, which
// understand what sentry is doing. // defaults to stderr.
Debug bool Debug bool
// Configures whether SDK should generate and attach stacktraces to pure // Configures whether SDK should generate and attach stacktraces to pure
// capture message calls. // capture message calls.
@@ -298,6 +298,7 @@ type ClientOptions struct {
// instances. It must be created with NewClient. // instances. It must be created with NewClient.
type Client struct { type Client struct {
mu sync.RWMutex mu sync.RWMutex
disabled bool
options ClientOptions options ClientOptions
dsn *protocol.Dsn dsn *protocol.Dsn
eventProcessors []EventProcessor eventProcessors []EventProcessor
@@ -450,6 +451,45 @@ func NewClient(options ClientOptions) (*Client, error) {
return &client, nil 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() { func (client *Client) setupTransport() {
opts := client.options opts := client.options
transport := opts.Transport transport := opts.Transport
@@ -555,6 +595,9 @@ func (client *Client) setupIntegrations() {
// client is shared among multiple hubs, one per goroutine, such that adding an // 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. // event processor to the client affects all hubs that share the client.
func (client *Client) AddEventProcessor(processor EventProcessor) { func (client *Client) AddEventProcessor(processor EventProcessor) {
if !client.IsEnabled() {
return
}
client.eventProcessors = append(client.eventProcessors, processor) client.eventProcessors = append(client.eventProcessors, processor)
} }
@@ -563,6 +606,9 @@ func (client *Client) AddEventProcessor(processor EventProcessor) {
// //
// This is intended for integrations such as OpenTelemetry. // This is intended for integrations such as OpenTelemetry.
func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) { func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) {
if !client.IsEnabled() {
return
}
client.mu.Lock() client.mu.Lock()
defer client.mu.Unlock() defer client.mu.Unlock()
@@ -596,7 +642,7 @@ func (client *Client) Options() ClientOptions {
// GetDataCollection returns a copy of the resolved data collection // GetDataCollection returns a copy of the resolved data collection
// configuration used by the client. // configuration used by the client.
func (client *Client) GetDataCollection() DataCollection { func (client *Client) GetDataCollection() DataCollection {
if client == nil || client.options.DataCollection == nil { if !client.IsEnabled() || client.options.DataCollection == nil {
return DataCollection{} return DataCollection{}
} }
return *cloneDataCollection(client.options.DataCollection) return *cloneDataCollection(client.options.DataCollection)
@@ -604,22 +650,32 @@ func (client *Client) GetDataCollection() DataCollection {
// CaptureMessage captures an arbitrary message. // CaptureMessage captures an arbitrary message.
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID { func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromMessage(message, LevelInfo) event := client.EventFromMessage(message, LevelInfo)
return client.CaptureEvent(event, hint, scope) return client.CaptureEvent(event, hint, scope)
} }
// CaptureException captures an error. // CaptureException captures an error.
func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID { func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromException(exception, LevelError) event := client.EventFromException(exception, LevelError)
return client.CaptureEvent(event, hint, scope) return client.CaptureEvent(event, hint, scope)
} }
// CaptureCheckIn captures a check in. // CaptureCheckIn captures a check in.
func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID { func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
event := client.EventFromCheckIn(checkIn, monitorConfig) event := client.EventFromCheckIn(checkIn, monitorConfig)
if event != nil && event.CheckIn != nil { if event != nil && event.CheckIn != nil {
client.CaptureEvent(event, nil, scope) if client.CaptureEvent(event, nil, scope) != nil {
return &event.CheckIn.ID return &event.CheckIn.ID
}
} }
return nil return nil
} }
@@ -630,6 +686,9 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon
// the utility methods like CaptureException. The return value is the // 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. // 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 { func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
if !client.IsEnabled() {
return nil
}
return client.processEvent(event, hint, scope) return client.processEvent(event, hint, scope)
} }
@@ -727,6 +786,9 @@ func (client *Client) RecoverWithContext(
if err == nil { if err == nil {
return nil return nil
} }
if !client.IsEnabled() {
return nil
}
if ctx != nil { if ctx != nil {
if hint == nil { if hint == nil {
@@ -751,7 +813,8 @@ func (client *Client) RecoverWithContext(
// Flush waits until the underlying Transport sends any buffered events to the // 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 // Sentry server, blocking for at most the given timeout. It returns false if
// the timeout was reached. In that case, some events may not have been sent. // the client is disabled or the timeout was reached. In the latter case, some
// events may not have been sent.
// //
// Flush should be called before terminating the program to avoid // Flush should be called before terminating the program to avoid
// unintentionally dropping events. // unintentionally dropping events.
@@ -761,6 +824,9 @@ func (client *Client) RecoverWithContext(
// the network synchronously, configure it to use the HTTPSyncTransport in the // the network synchronously, configure it to use the HTTPSyncTransport in the
// call to Init. // call to Init.
func (client *Client) Flush(timeout time.Duration) bool { func (client *Client) Flush(timeout time.Duration) bool {
if !client.IsEnabled() {
return false
}
if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil { if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil {
ctx, cancel := context.WithTimeout(context.Background(), timeout) ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel() defer cancel()
@@ -770,9 +836,10 @@ func (client *Client) Flush(timeout time.Duration) bool {
} }
// FlushWithContext waits until the underlying Transport sends any buffered events // FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context. // to the Sentry server, blocking for at most the duration specified by the
// It returns false if the context is canceled before the events are sent. In such a case, // context. It returns false if the client is disabled or the context is
// some events may not be delivered. // canceled before the events are sent. In the latter case, some events may not
// be delivered.
// //
// FlushWithContext should be called before terminating the program to ensure no // FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped. // events are unintentionally dropped.
@@ -782,6 +849,9 @@ func (client *Client) Flush(timeout time.Duration) bool {
// configure the SDK to use HTTPSyncTransport during initialization with Init. // configure the SDK to use HTTPSyncTransport during initialization with Init.
func (client *Client) FlushWithContext(ctx context.Context) bool { func (client *Client) FlushWithContext(ctx context.Context) bool {
if !client.IsEnabled() {
return false
}
if client.batchLogger != nil { if client.batchLogger != nil {
client.batchLogger.Flush(ctx.Done()) client.batchLogger.Flush(ctx.Done())
} }
@@ -799,6 +869,9 @@ func (client *Client) FlushWithContext(ctx context.Context) bool {
// Close should be called after Flush and before terminating the program // Close should be called after Flush and before terminating the program
// otherwise some events may be lost. // otherwise some events may be lost.
func (client *Client) Close() { func (client *Client) Close() {
if !client.IsEnabled() {
return
}
if client.telemetryProcessor != nil { if client.telemetryProcessor != nil {
client.telemetryProcessor.Close(5 * time.Second) client.telemetryProcessor.Close(5 * time.Second)
} }
@@ -875,6 +948,9 @@ func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorC
} }
func (client *Client) SetSDKIdentifier(identifier string) { func (client *Client) SetSDKIdentifier(identifier string) {
if !client.IsEnabled() {
return
}
client.mu.Lock() client.mu.Lock()
defer client.mu.Unlock() defer client.mu.Unlock()
+4 -4
View File
@@ -43,7 +43,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
scope := hub.Scope() scope := hub.Scope()
client := hub.Client() client := hub.Client()
if client == nil || scope == nil { if !client.IsEnabled() || scope == nil {
return DynamicSamplingContext{ return DynamicSamplingContext{
Entries: map[string]string{}, Entries: map[string]string{},
Frozen: false, Frozen: false,
@@ -53,7 +53,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
entries := make(map[string]string) entries := make(map[string]string)
if traceID := span.TraceID.String(); traceID != "" { if traceID := span.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID entries[traceIDContextKey] = traceID
} }
if sampleRate := span.sampleRate; sampleRate != 0 { if sampleRate := span.sampleRate; sampleRate != 0 {
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) 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 { func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
entries := map[string]string{} entries := map[string]string{}
if client == nil || scope == nil { if !client.IsEnabled() || scope == nil {
return DynamicSamplingContext{ return DynamicSamplingContext{
Entries: entries, Entries: entries,
Frozen: false, Frozen: false,
@@ -132,7 +132,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli
propagationContext := scope.propagationContext propagationContext := scope.propagationContext
if traceID := propagationContext.TraceID.String(); traceID != "" { if traceID := propagationContext.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID entries[traceIDContextKey] = traceID
} }
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 { if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
+1 -1
View File
@@ -20,7 +20,7 @@ type visited struct {
func (v *visited) seenError(err error) bool { func (v *visited) seenError(err error) bool {
t := reflect.ValueOf(err) t := reflect.ValueOf(err)
if t.Kind() == reflect.Ptr && !t.IsNil() { if t.Kind() == reflect.Pointer && !t.IsNil() {
ptr := t.Pointer() ptr := t.Pointer()
if _, ok := v.ptrs[ptr]; ok { if _, ok := v.ptrs[ptr]; ok {
return true return true
+1
View File
@@ -2,6 +2,7 @@ go 1.25.0
use ( use (
. .
./cron
./crosstest ./crosstest
./echo ./echo
./fasthttp ./fasthttp
+18
View File
@@ -1,5 +1,7 @@
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= 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.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 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
@@ -14,6 +16,7 @@ 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 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.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.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 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM= github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
@@ -60,6 +63,7 @@ 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 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA= 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/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 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.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
@@ -85,6 +89,9 @@ 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.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0/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/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 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= 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= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
@@ -138,6 +145,7 @@ 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/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 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo=
github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= 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/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY=
github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502 h1:34icjjmqJ2HPjrSuJYEkdZ+0ItmGQAQ75cRHIiftIyE= 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= github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090 h1:ok0U1tNDp9ICD93bMrZuFtHLwDoW+5nfSfF8e/x36Y0=
@@ -161,9 +169,13 @@ 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 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.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.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 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= 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.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 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs= golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
@@ -172,10 +184,12 @@ 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 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU= 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.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.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8= 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.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs= 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.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ= golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
@@ -184,6 +198,7 @@ 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 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= 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.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.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.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
@@ -199,6 +214,7 @@ 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 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= 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.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.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= 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= golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
@@ -212,11 +228,13 @@ 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 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI= 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.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= 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 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg= 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 h1:cJWOvXtcaFSGXz2F4z2AMM0VV7edDDGrxb5GLQH7ayQ=
gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM= 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/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-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+52 -36
View File
@@ -20,7 +20,7 @@ const (
RequestContextKey = contextKey(2) RequestContextKey = contextKey(2)
) )
// currentHub is the initial Hub with no Client bound and an empty Scope. // currentHub is the initial Hub with a no-op Client and an empty Scope.
var currentHub = NewHub(nil, NewScope()) var currentHub = NewHub(nil, NewScope())
// Hub is the central object that manages scopes and clients. // 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) { func (l *layer) SetClient(c *Client) {
l.mu.Lock() l.mu.Lock()
defer l.mu.Unlock() defer l.mu.Unlock()
l.client = c l.client = normalizeClient(c)
} }
type stack []*layer type stack []*layer
@@ -67,7 +67,7 @@ type stack []*layer
func NewHub(client *Client, scope *Scope) *Hub { func NewHub(client *Client, scope *Scope) *Hub {
hub := Hub{ hub := Hub{
stack: &stack{{ stack: &stack{{
client: client, client: normalizeClient(client),
scope: scope, scope: scope,
}}, }},
} }
@@ -218,12 +218,12 @@ func (hub *Hub) CaptureEvent(event *Event) *EventID {
// CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint. // CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint.
func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID { func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil { if scope == nil {
return nil return nil
} }
eventID := client.CaptureEvent(event, hint, scope) eventID := client.CaptureEvent(event, hint, scope)
if event.Type != transactionType && eventID != nil { if event != nil && event.Type != transactionType && eventID != nil {
hub.mu.Lock() hub.mu.Lock()
hub.lastEventID = *eventID hub.lastEventID = *eventID
hub.mu.Unlock() 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. // Returns EventID if successfully, or nil if there's no Scope or Client available.
func (hub *Hub) CaptureMessage(message string) *EventID { func (hub *Hub) CaptureMessage(message string) *EventID {
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil { if scope == nil {
return nil return nil
} }
eventID := client.CaptureMessage(message, nil, scope) 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. // Returns EventID if successfully, or nil if there's no Scope or Client available.
func (hub *Hub) CaptureException(exception error) *EventID { func (hub *Hub) CaptureException(exception error) *EventID {
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil { if scope == nil {
return nil return nil
} }
eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope) eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope)
@@ -272,13 +272,46 @@ func (hub *Hub) CaptureException(exception error) *EventID {
// Returns CheckInID if the check-in was captured successfully, or nil otherwise. // Returns CheckInID if the check-in was captured successfully, or nil otherwise.
func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil {
return nil
}
return client.CaptureCheckIn(checkIn, monitorConfig, 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
}
return err
}
// AddBreadcrumb records a new breadcrumb. // AddBreadcrumb records a new breadcrumb.
// //
// The total number of breadcrumbs that can be recorded are limited by the // The total number of breadcrumbs that can be recorded are limited by the
@@ -286,12 +319,6 @@ func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *
func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
client := hub.Client() 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 limit := client.options.MaxBreadcrumbs
switch { switch {
case limit < 0: case limit < 0:
@@ -321,7 +348,7 @@ func (hub *Hub) Recover(err interface{}) *EventID {
err = recover() err = recover()
} }
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil { if scope == nil {
return nil return nil
} }
return client.Recover(err, &EventHint{RecoveredException: err}, scope) return client.Recover(err, &EventHint{RecoveredException: err}, scope)
@@ -335,7 +362,7 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
err = recover() err = recover()
} }
client, scope := hub.Client(), hub.Scope() client, scope := hub.Client(), hub.Scope()
if client == nil || scope == nil { if scope == nil {
return nil return nil
} }
return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope) return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope)
@@ -353,19 +380,14 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
// the network synchronously, configure it to use the HTTPSyncTransport in the // the network synchronously, configure it to use the HTTPSyncTransport in the
// call to Init. // call to Init.
func (hub *Hub) Flush(timeout time.Duration) bool { func (hub *Hub) Flush(timeout time.Duration) bool {
client := hub.Client() return hub.Client().Flush(timeout)
if client == nil {
return false
}
return client.Flush(timeout)
} }
// FlushWithContext waits until the underlying Transport sends any buffered events // FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context. // to the Sentry server, blocking for at most the duration specified by the
// It returns false if the context is canceled before the events are sent. In such a case, // context. It returns false if capture is disabled or the context is canceled
// some events may not be delivered. // before the events are sent. In the latter case, some events may not be
// delivered.
// //
// FlushWithContext should be called before terminating the program to ensure no // FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped. // events are unintentionally dropped.
@@ -375,13 +397,7 @@ func (hub *Hub) Flush(timeout time.Duration) bool {
// configure the SDK to use HTTPSyncTransport during initialization with Init. // configure the SDK to use HTTPSyncTransport during initialization with Init.
func (hub *Hub) FlushWithContext(ctx context.Context) bool { func (hub *Hub) FlushWithContext(ctx context.Context) bool {
client := hub.Client() return hub.Client().FlushWithContext(ctx)
if client == nil {
return false
}
return client.FlushWithContext(ctx)
} }
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value // GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
@@ -48,6 +48,12 @@ func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWr
if fl && hj && rf { if fl && hj && rf {
return &httpFancyWriter{bw} return &httpFancyWriter{bw}
} }
if fl && hj {
return &flushHijackWriter{bw}
}
if hj {
return &hijackWriter{bw}
}
} }
if fl { if fl {
return &flushWriter{bw} return &flushWriter{bw}
@@ -143,6 +149,36 @@ func (f *flushWriter) Flush() {
var _ http.Flusher = &flushWriter{} 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 // httpFancyWriter is a HTTP writer that additionally satisfies
// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case // 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 // of wrapping the http.ResponseWriter that package http gives you, in order to
+12 -8
View File
@@ -3,6 +3,7 @@ package protocol
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"net"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
@@ -210,17 +211,20 @@ func (dsn *Dsn) SetOrgID(orgID uint64) {
// GetAPIURL returns the URL of the envelope endpoint of the project // GetAPIURL returns the URL of the envelope endpoint of the project
// associated with the DSN. // associated with the DSN.
func (dsn Dsn) GetAPIURL() *url.URL { func (dsn Dsn) GetAPIURL() *url.URL {
var rawURL string host := dsn.host
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) port := ""
if dsn.port != dsn.scheme.defaultPort() { if dsn.port != dsn.scheme.defaultPort() {
rawURL += fmt.Sprintf(":%d", dsn.port) port = strconv.Itoa(dsn.port)
} }
if dsn.path != "" { // JoinHostPort correctly adds brackets for IPv6 hosts. However with an
rawURL += dsn.path // 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/",
} }
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 // RequestHeaders returns all the necessary headers that have to be used in the transport when sending events
+26 -2
View File
@@ -26,6 +26,9 @@ type Scheduler struct {
cancel context.CancelFunc cancel context.CancelFunc
processingWg sync.WaitGroup processingWg sync.WaitGroup
// processing serializes buffer-to-transport handoffs and allows cancelable waits.
processing chan struct{}
mu sync.Mutex mu sync.Mutex
cond *sync.Cond cond *sync.Cond
startOnce sync.Once startOnce sync.Once
@@ -79,6 +82,7 @@ func NewScheduler(
currentCycle: currentCycle, currentCycle: currentCycle,
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
processing: make(chan struct{}, 1),
} }
s.cond = sync.NewCond(&s.mu) s.cond = sync.NewCond(&s.mu)
@@ -145,7 +149,9 @@ func (s *Scheduler) Flush(timeout time.Duration) bool {
} }
func (s *Scheduler) FlushWithContext(ctx context.Context) bool { func (s *Scheduler) FlushWithContext(ctx context.Context) bool {
s.flushBuffers() if !s.flushBuffers(ctx) {
return false
}
return s.transport.FlushWithContext(ctx) return s.transport.FlushWithContext(ctx)
} }
@@ -193,6 +199,13 @@ func (s *Scheduler) hasWork() bool {
} }
func (s *Scheduler) processNextBatch() { func (s *Scheduler) processNextBatch() {
select {
case s.processing <- struct{}{}:
defer func() { <-s.processing }()
case <-s.ctx.Done():
return
}
if len(s.currentCycle) == 0 { if len(s.currentCycle) == 0 {
return return
} }
@@ -290,12 +303,23 @@ func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) {
} }
} }
func (s *Scheduler) flushBuffers() { func (s *Scheduler) flushBuffers(ctx context.Context) bool {
select {
case s.processing <- struct{}{}:
defer func() { <-s.processing }()
case <-ctx.Done():
return false
}
for category, buffer := range s.buffers { for category, buffer := range s.buffers {
if ctx.Err() != nil {
return false
}
if !buffer.IsEmpty() { if !buffer.IsEmpty() {
s.processItems(buffer, category, true) s.processItems(buffer, category, true)
} }
} }
return ctx.Err() == nil
} }
func (s *Scheduler) isRateLimited(category ratelimit.Category) bool { func (s *Scheduler) isRateLimited(category ratelimit.Category) bool {
+2 -2
View File
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
} }
client := hub.Client() client := hub.Client()
if client != nil { if client.IsEnabled() {
// Build default attrs // Build default attrs
serverAddr := client.options.ServerName serverAddr := client.options.ServerName
if serverAddr == "" { if serverAddr == "" {
@@ -111,7 +111,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
hub = l.hub hub = l.hub
} }
client := hub.Client() client := hub.Client()
if client == nil { if !client.IsEnabled() {
return return
} }
+2 -2
View File
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
hub = CurrentHub() hub = CurrentHub()
} }
client := hub.Client() client := hub.Client()
if client != nil { if client.IsEnabled() {
// build default attrs // build default attrs
serverAddr := client.options.ServerName serverAddr := client.options.ServerName
if serverAddr == "" { if serverAddr == "" {
@@ -110,7 +110,7 @@ func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name stri
} }
client := hub.Client() client := hub.Client()
if client == nil { if !client.IsEnabled() {
return return
} }
+7 -2
View File
@@ -4,6 +4,11 @@ import (
"crypto/rand" "crypto/rand"
) )
const (
traceIDContextKey = "trace_id"
spanIDContextKey = "span_id"
)
type PropagationContext struct { type PropagationContext struct {
TraceID TraceID `json:"trace_id"` TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"` SpanID SpanID `json:"span_id"`
@@ -13,8 +18,8 @@ type PropagationContext struct {
func (p PropagationContext) Map() map[string]interface{} { func (p PropagationContext) Map() map[string]interface{} {
m := map[string]interface{}{ m := map[string]interface{}{
"trace_id": p.TraceID, traceIDContextKey: p.TraceID,
"span_id": p.SpanID, spanIDContextKey: p.SpanID,
} }
if p.ParentSpanID != zeroSpanID { if p.ParentSpanID != zeroSpanID {
+33 -13
View File
@@ -30,7 +30,15 @@ import (
// an event for reporting, the current client adds information from the current // an event for reporting, the current client adds information from the current
// scope into the event. // scope into the event.
type Scope struct { type Scope struct {
mu sync.RWMutex 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 {
attributes map[string]attribute.Value attributes map[string]attribute.Value
breadcrumbs []*Breadcrumb breadcrumbs []*Breadcrumb
attachments []*Attachment attachments []*Attachment
@@ -49,7 +57,6 @@ type Scope struct {
// size. // size.
Overflow() bool Overflow() bool
} }
eventProcessors []EventProcessor
propagationContext PropagationContext propagationContext PropagationContext
span *Span span *Span
@@ -57,14 +64,18 @@ type Scope struct {
// NewScope creates a new Scope. // NewScope creates a new Scope.
func NewScope() *Scope { func NewScope() *Scope {
return &Scope{ return &Scope{scopeData: newScopeData(NewPropagationContext())}
}
func newScopeData(propagationContext PropagationContext) scopeData {
return scopeData{
attributes: make(map[string]attribute.Value), attributes: make(map[string]attribute.Value),
breadcrumbs: make([]*Breadcrumb, 0), breadcrumbs: make([]*Breadcrumb, 0),
attachments: make([]*Attachment, 0), attachments: make([]*Attachment, 0),
tags: make(map[string]string), tags: make(map[string]string),
contexts: make(map[string]Context), contexts: make(map[string]Context),
fingerprint: make([]string, 0), fingerprint: make([]string, 0),
propagationContext: NewPropagationContext(), propagationContext: propagationContext,
} }
} }
@@ -282,6 +293,7 @@ func (scope *Scope) Clone() *Scope {
clone := NewScope() clone := NewScope()
clone.user = scope.user clone.user = scope.user
clone.user.Data = maps.Clone(scope.user.Data)
clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs)) clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs))
copy(clone.breadcrumbs, scope.breadcrumbs) copy(clone.breadcrumbs, scope.breadcrumbs)
clone.attachments = make([]*Attachment, len(scope.attachments)) clone.attachments = make([]*Attachment, len(scope.attachments))
@@ -300,9 +312,16 @@ func (scope *Scope) Clone() *Scope {
return clone return clone
} }
// Clear removes the data from the current scope. Not safe for concurrent use. // Clear removes enrichment data while preserving event processors and trace
// correlation. It is safe for concurrent use.
func (scope *Scope) Clear() { func (scope *Scope) Clear() {
*scope = *NewScope() scope.mu.Lock()
defer scope.mu.Unlock()
propagationContext := scope.propagationContext
span := scope.span
scope.scopeData = newScopeData(propagationContext)
scope.span = span
} }
// AddEventProcessor adds an event processor to the current scope. // AddEventProcessor adds an event processor to the current scope.
@@ -375,7 +394,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
event.Contexts["trace"] = scope.propagationContext.Map() event.Contexts["trace"] = scope.propagationContext.Map()
dsc := scope.propagationContext.DynamicSamplingContext dsc := scope.propagationContext.DynamicSamplingContext
if !dsc.HasEntries() && client != nil { if !dsc.HasEntries() && client.IsEnabled() {
dsc = DynamicSamplingContextFromScope(scope, client) dsc = DynamicSamplingContextFromScope(scope, client)
} }
event.sdkMetaData.dsc = dsc event.sdkMetaData.dsc = dsc
@@ -383,7 +402,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
// If an external trace resolver is registered (e.g. OTel), override // If an external trace resolver is registered (e.g. OTel), override
// trace/span IDs from the hint context or the scope's request context. // trace/span IDs from the hint context or the scope's request context.
if client != nil { if client.IsEnabled() {
var ctx context.Context var ctx context.Context
if hint != nil { if hint != nil {
ctx = hint.Context ctx = hint.Context
@@ -393,13 +412,14 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
} }
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok { if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok {
traceCtx := event.Contexts["trace"] traceCtx := event.Contexts["trace"]
traceCtx["trace_id"] = traceID.String() traceCtx[traceIDContextKey] = traceID.String()
traceCtx["span_id"] = spanID.String() traceCtx[spanIDContextKey] = spanID.String()
} }
} }
if event.User.IsEmpty() { if event.User.IsEmpty() {
event.User = scope.user event.User = scope.user
event.User.Data = maps.Clone(scope.user.Data)
} }
if len(event.Fingerprint) == 0 { if len(event.Fingerprint) == 0 {
@@ -434,7 +454,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
event = processor(event, hint) event = processor(event, hint)
if event == nil { if event == nil {
debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
if client != nil { if client.IsEnabled() {
client.reportRecorder.RecordOne(report.ReasonEventProcessor, category) client.reportRecorder.RecordOne(report.ReasonEventProcessor, category)
if category == ratelimit.CategoryTransaction { if category == ratelimit.CategoryTransaction {
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore)) client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore))
@@ -443,7 +463,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
return nil return nil
} }
if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 {
if client != nil { if client.IsEnabled() {
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans)) client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans))
} }
} }
@@ -524,7 +544,7 @@ func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceI
if ctx == nil { if ctx == nil {
continue continue
} }
if client != nil { if client.IsEnabled() {
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok { if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok {
return traceID, spanID return traceID, spanID
} }
+25 -4
View File
@@ -6,7 +6,7 @@ import (
) )
// The version of the SDK. // The version of the SDK.
const SDKVersion = "0.49.0" const SDKVersion = "0.50.0"
// apiVersion is the minimum version of the Sentry API compatible with the // apiVersion is the minimum version of the Sentry API compatible with the
// sentry-go SDK. // sentry-go SDK.
@@ -54,6 +54,26 @@ func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
return hub.CaptureCheckIn(checkIn, monitorConfig) 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. // CaptureEvent captures an event on the currently active client if any.
// //
// The event must already be assembled. Typically code would instead use // The event must already be assembled. Typically code would instead use
@@ -129,9 +149,10 @@ func Flush(timeout time.Duration) bool {
} }
// FlushWithContext waits until the underlying Transport sends any buffered events // FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context. // to the Sentry server, blocking for at most the duration specified by the
// It returns false if the context is canceled before the events are sent. In such a case, // context. It returns false if capture is disabled or the context is canceled
// some events may not be delivered. // before the events are sent. In the latter case, some events may not be
// delivered.
// //
// FlushWithContext should be called before terminating the program to ensure no // FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped. // events are unintentionally dropped.
+1 -1
View File
@@ -18,7 +18,7 @@ type spanRecorder struct {
// span tree. // span tree.
func (r *spanRecorder) record(s *Span) { func (r *spanRecorder) record(s *Span) {
maxSpans := defaultMaxSpans maxSpans := defaultMaxSpans
if client := CurrentHub().Client(); client != nil { if client := CurrentHub().Client(); client.IsEnabled() {
maxSpans = client.options.MaxSpans maxSpans = client.options.MaxSpans
} }
r.mu.Lock() r.mu.Lock()
+4 -4
View File
@@ -551,7 +551,7 @@ func (s *Span) updateFromBaggage(header []byte) {
func (s *Span) clientOptions() *ClientOptions { func (s *Span) clientOptions() *ClientOptions {
client := hubFromContext(s.ctx).Client() client := hubFromContext(s.ctx).Client()
if client != nil { if client.IsEnabled() {
return &client.options return &client.options
} }
return &ClientOptions{} return &ClientOptions{}
@@ -933,8 +933,8 @@ type TraceContext struct {
func (tc TraceContext) Map() map[string]interface{} { func (tc TraceContext) Map() map[string]interface{} {
m := map[string]interface{}{ m := map[string]interface{}{
"trace_id": tc.TraceID, traceIDContextKey: tc.TraceID,
"span_id": tc.SpanID, spanIDContextKey: tc.SpanID,
} }
if tc.ParentSpanID != [8]byte{} { if tc.ParentSpanID != [8]byte{} {
@@ -1202,7 +1202,7 @@ func HTTPtoSpanStatus(code int) SpanStatus {
} }
func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool { func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool {
if client == nil { if !client.IsEnabled() {
return true return true
} }
+4 -1
View File
@@ -63,6 +63,7 @@ const (
ChineseFirstNameTag = "chinese_first_name" ChineseFirstNameTag = "chinese_first_name"
ChineseLastNameTag = "chinese_last_name" ChineseLastNameTag = "chinese_last_name"
ChineseNameTag = "chinese_name" ChineseNameTag = "chinese_name"
ChinesePhoneNumberTag = "chinese_phone_number"
GENDER = "gender" GENDER = "gender"
UnixTimeTag = "unix_time" UnixTimeTag = "unix_time"
DATE = "date" DATE = "date"
@@ -107,7 +108,7 @@ const (
var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag, var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag,
IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber, IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber,
E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag, E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag,
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag, NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, ChinesePhoneNumberTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH, YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH,
CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag, CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag,
UserAgentTag, UserAgentTag,
@@ -169,6 +170,7 @@ func initDefaultTag() {
defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag) defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag)
defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag) defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag)
defaultTag.Store(ChineseNameTag, ChineseNameTag) defaultTag.Store(ChineseNameTag, ChineseNameTag)
defaultTag.Store(ChinesePhoneNumberTag, ChinesePhoneNumberTag)
defaultTag.Store(GENDER, GENDER) defaultTag.Store(GENDER, GENDER)
defaultTag.Store(UnixTimeTag, UnixTimeTag) defaultTag.Store(UnixTimeTag, UnixTimeTag)
defaultTag.Store(DATE, DATE) defaultTag.Store(DATE, DATE)
@@ -220,6 +222,7 @@ func initMapperTagDefault() {
mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName) mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName)
mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName) mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName)
mapperTag.Store(ChineseNameTag, GetPerson().ChineseName) mapperTag.Store(ChineseNameTag, GetPerson().ChineseName)
mapperTag.Store(ChinesePhoneNumberTag, GetPhoner().ChinesePhoneNumber)
mapperTag.Store(GENDER, GetPerson().Gender) mapperTag.Store(GENDER, GetPerson().Gender)
mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime) mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime)
mapperTag.Store(DATE, GetDateTimer().Date) mapperTag.Store(DATE, GetDateTimer().Date)
+34
View File
@@ -9,6 +9,20 @@ import (
"github.com/go-faker/faker/v4/pkg/slice" "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 // GetPhoner serves as a constructor for Phoner interface
func GetPhoner() Phoner { func GetPhoner() Phoner {
phone := &Phone{} phone := &Phone{}
@@ -20,6 +34,7 @@ type Phoner interface {
PhoneNumber(v reflect.Value) (any, error) PhoneNumber(v reflect.Value) (any, error)
TollFreePhoneNumber(v reflect.Value) (any, error) TollFreePhoneNumber(v reflect.Value) (any, error)
E164PhoneNumber(v reflect.Value) (any, error) E164PhoneNumber(v reflect.Value) (any, error)
ChinesePhoneNumber(v reflect.Value) (any, error)
} }
// Phone struct // Phone struct
@@ -95,3 +110,22 @@ func E164PhoneNumber(opts ...options.OptionFunc) string {
return p.e164PhoneNumber() return p.e164PhoneNumber()
}, opts...).(string) }, 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)
}
+7 -5
View File
@@ -139,11 +139,13 @@ func main() {
fmt.Println(l.CardinalPluralRule(1.0, 1)) fmt.Println(l.CardinalPluralRule(1.0, 1))
fmt.Println(l.CardinalPluralRule(3, 0)) fmt.Println(l.CardinalPluralRule(3, 0))
// Ordinal Plural Rules // Ordinal Plural Rules. The method returns the locales/plurals.Rule
fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st // (e.g. One, Two, Few, Other) for the number; converting that rule into
fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd // the actual suffix ("st", "nd", "rd", "th") is left to the caller.
fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st")
fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd")
fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd")
fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th")
// Range Plural Rules // Range Plural Rules
fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1
+12 -16
View File
@@ -498,10 +498,9 @@ func (en *en) FmtTimeShort(t time.Time) string {
b := make([]byte, 0, 32) b := make([]byte, 0, 32)
h := t.Hour() h := t.Hour() % 12
if h == 0 {
if h > 12 { h = 12
h -= 12
} }
b = strconv.AppendInt(b, int64(h), 10) b = strconv.AppendInt(b, int64(h), 10)
@@ -528,10 +527,9 @@ func (en *en) FmtTimeMedium(t time.Time) string {
b := make([]byte, 0, 32) b := make([]byte, 0, 32)
h := t.Hour() h := t.Hour() % 12
if h == 0 {
if h > 12 { h = 12
h -= 12
} }
b = strconv.AppendInt(b, int64(h), 10) b = strconv.AppendInt(b, int64(h), 10)
@@ -565,10 +563,9 @@ func (en *en) FmtTimeLong(t time.Time) string {
b := make([]byte, 0, 32) b := make([]byte, 0, 32)
h := t.Hour() h := t.Hour() % 12
if h == 0 {
if h > 12 { h = 12
h -= 12
} }
b = strconv.AppendInt(b, int64(h), 10) b = strconv.AppendInt(b, int64(h), 10)
@@ -607,10 +604,9 @@ func (en *en) FmtTimeFull(t time.Time) string {
b := make([]byte, 0, 32) b := make([]byte, 0, 32)
h := t.Hour() h := t.Hour() % 12
if h == 0 {
if h > 12 { h = 12
h -= 12
} }
b = strconv.AppendInt(b, int64(h), 10) b = strconv.AppendInt(b, int64(h), 10)
+13 -10
View File
@@ -98,7 +98,7 @@ type Translator interface {
// returns the locales narrow weekday given the 'weekday' provided // returns the locales narrow weekday given the 'weekday' provided
WeekdayNarrow(weekday time.Weekday) string WeekdayNarrow(weekday time.Weekday) string
// WeekdaysNarrowreturns the locales narrow weekdays // WeekdaysNarrow returns the locales narrow weekdays
WeekdaysNarrow() []string WeekdaysNarrow() []string
// returns the locales short weekday given the 'weekday' provided // returns the locales short weekday given the 'weekday' provided
@@ -113,7 +113,7 @@ type Translator interface {
// returns the locales wide weekdays // returns the locales wide weekdays
WeekdaysWide() []string WeekdaysWide() []string
// The following Functions are common Formatting functionsfor the Translator's Locale // The following Functions are common Formatting functions for the Translator's Locale
// returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' // 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 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) s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then w will be zero // will either be '0' or '0.xxxx', so if 1 then w will be zero
// otherwise need to parse // otherwise need to parse
if len(s) != 1 { if len(s) != 1 {
s = s[2:] s = s[2:]
end := len(s) + 1 end := 0
for i := end; i >= 0; i-- { for i := len(s) - 1; i >= 0; i-- {
if s[i] != '0' { if s[i] != '0' {
end = i + 1 end = i + 1
break break
@@ -253,7 +253,7 @@ func F(n float64, v uint64) (f int64) {
s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then f will be zero // will either be '0' or '0.xxxx', so if 1 then f will be zero
// otherwise need to parse // otherwise need to parse
if len(s) != 1 { 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) s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64)
// with either be '0' or '0.xxxx', so if 1 then t will be zero // will either be '0' or '0.xxxx', so if 1 then t will be zero
// otherwise need to parse // otherwise need to parse
if len(s) != 1 { if len(s) != 1 {
s = s[2:] s = s[2:]
end := len(s) + 1 end := 0
for i := end; i >= 0; i-- { for i := len(s) - 1; i >= 0; i-- {
if s[i] != '0' { if s[i] != '0' {
end = i + 1 end = i + 1
break break
@@ -286,8 +286,11 @@ func T(n float64, v uint64) (t int64) {
// ignoring error, because it can't fail as we generated // ignoring error, because it can't fail as we generated
// the string internally from a real number // the string internally from a real number
t, _ = strconv.ParseInt(s[:end], 10, 64) if end > 0 {
t, _ = strconv.ParseInt(s[:end], 10, 64)
}
} }
return return
} }
+42
View File
@@ -0,0 +1,42 @@
# 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
View File
@@ -0,0 +1,9 @@
## 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
View File
@@ -82,6 +82,17 @@ Help With Tests
To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. 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. 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 License
------ ------
Distributed under MIT License, please see license file in code for more details. Distributed under MIT License, please see license file in code for more details.
+5 -2
View File
@@ -8,8 +8,11 @@ import (
) )
var ( var (
// ErrUnknowTranslation indicates the translation could not be found // ErrUnknownTranslation indicates the translation could not be found
ErrUnknowTranslation = errors.New("Unknown Translation") ErrUnknownTranslation = errors.New("unknown translation")
// Deprecated: Use ErrUnknownTranslation instead.
ErrUnknowTranslation = ErrUnknownTranslation
) )
var _ error = new(ErrConflictingTranslation) var _ error = new(ErrConflictingTranslation)
+1 -1
View File
@@ -163,7 +163,7 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam
if err != nil { if err != nil {
return err return err
} }
defer f.Close() defer func() { _ = f.Close() }()
return t.ImportByReader(format, f) return t.ImportByReader(format, f)
} }
+83 -33
View File
@@ -101,35 +101,87 @@ func (t *translator) Add(key interface{}, text string, override bool) error {
return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text} return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text}
} }
lb := strings.Count(text, "{") indexes, err := parseParamPlaceholders(text, t.Locale(), key)
rb := strings.Count(text, "}") if err != nil {
return err
if lb != rb {
return &ErrMissingBracket{locale: t.Locale(), key: key, text: text}
} }
trans := &transText{ t.translations[key] = &transText{text: text, indexes: indexes}
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 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 // 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 // {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; // multiple cannot be used for a plural rule determination, unless it is a range;
@@ -298,20 +350,18 @@ func (t *translator) T(key interface{}, params ...string) (string, error) {
trans, ok := t.translations[key] trans, ok := t.translations[key]
if !ok { if !ok {
return unknownTranslation, ErrUnknowTranslation return unknownTranslation, ErrUnknownTranslation
} }
b := make([]byte, 0, 64) b := make([]byte, 0, 64)
var start, end, count int var start, end int
for i := 0; i < len(trans.indexes); i++ { for i := 0; i < len(trans.indexes); i += 3 {
end = trans.indexes[i] end = trans.indexes[i]
b = append(b, trans.text[start:end]...) b = append(b, trans.text[start:end]...)
b = append(b, params[count]...) b = append(b, params[trans.indexes[i+2]]...)
i++ start = trans.indexes[i+1]
start = trans.indexes[i]
count++
} }
b = append(b, trans.text[start:]...) b = append(b, trans.text[start:]...)
@@ -324,7 +374,7 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string
tarr, ok := t.cardinalTanslations[key] tarr, ok := t.cardinalTanslations[key]
if !ok { if !ok {
return unknownTranslation, ErrUnknowTranslation return unknownTranslation, ErrUnknownTranslation
} }
rule := t.CardinalPluralRule(num, digits) rule := t.CardinalPluralRule(num, digits)
@@ -344,7 +394,7 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string
tarr, ok := t.ordinalTanslations[key] tarr, ok := t.ordinalTanslations[key]
if !ok { if !ok {
return unknownTranslation, ErrUnknowTranslation return unknownTranslation, ErrUnknownTranslation
} }
rule := t.OrdinalPluralRule(num, digits) rule := t.OrdinalPluralRule(num, digits)
@@ -365,7 +415,7 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float
tarr, ok := t.rangeTanslations[key] tarr, ok := t.rangeTanslations[key]
if !ok { if !ok {
return unknownTranslation, ErrUnknowTranslation return unknownTranslation, ErrUnknownTranslation
} }
rule := t.RangePluralRule(num1, digits1, num2, digits2) rule := t.RangePluralRule(num1, digits1, num2, digits2)
@@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string {
// Parse parses the string representation of path template // Parse parses the string representation of path template
func Parse(tmpl string) (Compiler, error) { 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, "/") { if !strings.HasPrefix(tmpl, "/") {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
} }
@@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) {
if err != nil { if err != nil {
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} 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{ return template{
segments: segs, segments: segs,
+6
View File
@@ -38,6 +38,7 @@ go_library(
"@org_golang_google_protobuf//reflect/protoreflect", "@org_golang_google_protobuf//reflect/protoreflect",
"@org_golang_google_protobuf//reflect/protoregistry", "@org_golang_google_protobuf//reflect/protoregistry",
"@org_golang_google_protobuf//types/known/durationpb", "@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/fieldmaskpb",
"@org_golang_google_protobuf//types/known/structpb", "@org_golang_google_protobuf//types/known/structpb",
"@org_golang_google_protobuf//types/known/timestamppb", "@org_golang_google_protobuf//types/known/timestamppb",
@@ -49,13 +50,16 @@ go_test(
name = "runtime_test", name = "runtime_test",
size = "small", size = "small",
srcs = [ srcs = [
"context_internal_test.go",
"context_test.go", "context_test.go",
"convert_test.go", "convert_test.go",
"errors_test.go", "errors_test.go",
"fieldmask_empty_object_test.go",
"fieldmask_test.go", "fieldmask_test.go",
"handler_test.go", "handler_test.go",
"marshal_httpbodyproto_test.go", "marshal_httpbodyproto_test.go",
"marshal_json_test.go", "marshal_json_test.go",
"marshal_jsonpb_bench_test.go",
"marshal_jsonpb_test.go", "marshal_jsonpb_test.go",
"marshal_proto_test.go", "marshal_proto_test.go",
"marshaler_registry_test.go", "marshaler_registry_test.go",
@@ -63,6 +67,7 @@ go_test(
"mux_test.go", "mux_test.go",
"pattern_test.go", "pattern_test.go",
"query_fuzz_test.go", "query_fuzz_test.go",
"query_internal_test.go",
"query_test.go", "query_test.go",
], ],
embed = [":runtime"], embed = [":runtime"],
@@ -76,6 +81,7 @@ go_test(
"@org_golang_google_genproto_googleapis_rpc//status", "@org_golang_google_genproto_googleapis_rpc//status",
"@org_golang_google_grpc//:grpc", "@org_golang_google_grpc//:grpc",
"@org_golang_google_grpc//codes", "@org_golang_google_grpc//codes",
"@org_golang_google_grpc//credentials/insecure",
"@org_golang_google_grpc//health/grpc_health_v1", "@org_golang_google_grpc//health/grpc_health_v1",
"@org_golang_google_grpc//metadata", "@org_golang_google_grpc//metadata",
"@org_golang_google_grpc//status", "@org_golang_google_grpc//status",
+76 -14
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"math"
"net" "net"
"net/http" "net/http"
"net/textproto" "net/textproto"
@@ -36,6 +37,13 @@ const metadataHeaderBinarySuffix = "-Bin"
const xForwardedFor = "X-Forwarded-For" const xForwardedFor = "X-Forwarded-For"
const xForwardedHost = "X-Forwarded-Host" 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 // 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. // header isn't present. If the value is 0 the sent `context` will not have a timeout.
var DefaultContextTimeout = 0 * time.Second var DefaultContextTimeout = 0 * time.Second
@@ -107,6 +115,10 @@ func isValidGRPCMetadataKey(key string) bool {
// This means 0-9 a-z _ - . // This means 0-9 a-z _ - .
// Only lowercase letters are valid in the wire protocol, but the client library will normalize // 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. // 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. bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode.
for _, ch := range bytes { for _, ch := range bytes {
validLowercaseLetter := ch >= 'a' && ch <= 'z' validLowercaseLetter := ch >= 'a' && ch <= 'z'
@@ -146,7 +158,21 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
} }
} }
var pairs []string // 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)
}
}
for key, vals := range req.Header { for key, vals := range req.Header {
key = textproto.CanonicalMIMEHeaderKey(key) key = textproto.CanonicalMIMEHeaderKey(key)
switch key { switch key {
@@ -156,11 +182,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
} }
for _, val := range vals { 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 { 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) { if !isValidGRPCMetadataKey(h) {
grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h) grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h)
continue continue
@@ -182,28 +214,52 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
} }
} }
} }
if host := req.Header.Get(xForwardedHost); host != "" { if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) {
pairs = append(pairs, strings.ToLower(xForwardedHost), host) pairs = append(pairs, xForwardedHostKey, host)
} else if req.Host != "" { } else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) {
pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) pairs = append(pairs, xForwardedHostKey, req.Host)
} }
xff := req.Header.Values(xForwardedFor) // 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)
}
}
if addr := req.RemoteAddr; addr != "" { if addr := req.RemoteAddr; addr != "" {
if remoteIP, _, err := net.SplitHostPort(addr); err == nil { if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) {
xff = append(xff, remoteIP) xff = append(xff, remoteIP)
} }
} }
if len(xff) > 0 { if len(xff) > 0 {
pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", ")) pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", "))
} }
if timeout != 0 { if timeout != 0 {
ctx, _ = context.WithTimeout(ctx, timeout) ctx, _ = context.WithTimeout(ctx, timeout)
} }
md := metadata.Pairs(pairs...) md := metadata.Pairs(pairs...)
var annotated metadata.MD
for _, mda := range mux.metadataAnnotators { for _, mda := range mux.metadataAnnotators {
md = metadata.Join(md, mda(ctx, req)) 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)
} }
if len(md) == 0 { if len(md) == 0 {
return ctx, nil, nil return ctx, nil, nil
@@ -302,10 +358,16 @@ func timeoutDecode(s string) (time.Duration, error) {
if !ok { if !ok {
return 0, fmt.Errorf("timeout unit is not recognized: %q", s) return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
} }
t, err := strconv.ParseInt(s[:size-1], 10, 64) t, err := strconv.ParseUint(s[:size-1], 10, 64)
if err != nil { if err != nil {
return 0, err 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 return d * time.Duration(t), nil
} }
+50 -17
View File
@@ -3,6 +3,7 @@ package runtime
import ( import (
"encoding/base64" "encoding/base64"
"fmt" "fmt"
"math"
"strconv" "strconv"
"strings" "strings"
@@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) {
return values, nil 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. // Float64 converts the given string representation into representation of a floating point number into float64.
func Float64(val string) (float64, error) { func Float64(val string) (float64, error) {
return strconv.ParseFloat(val, 64) return parseFloat(val, 64)
} }
// Float64Slice converts 'val' where individual floating point numbers are separated by // Float64Slice converts 'val' where individual floating point numbers are separated by
@@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) {
// Float32 converts the given string representation of a floating point number into float32. // Float32 converts the given string representation of a floating point number into float32.
func Float32(val string) (float32, error) { func Float32(val string) (float32, error) {
f, err := strconv.ParseFloat(val, 32) f, err := parseFloat(val, 32)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) {
// Int64 converts the given string representation of an integer into int64. // Int64 converts the given string representation of an integer into int64.
func Int64(val string) (int64, error) { func Int64(val string) (int64, error) {
return strconv.ParseInt(val, 0, 64) return strconv.ParseInt(val, 10, 64)
} }
// Int64Slice converts 'val' where individual integers are separated by // Int64Slice converts 'val' where individual integers are separated by
@@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) {
// Int32 converts the given string representation of an integer into int32. // Int32 converts the given string representation of an integer into int32.
func Int32(val string) (int32, error) { func Int32(val string) (int32, error) {
i, err := strconv.ParseInt(val, 0, 32) i, err := strconv.ParseInt(val, 10, 32)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) {
// Uint64 converts the given string representation of an integer into uint64. // Uint64 converts the given string representation of an integer into uint64.
func Uint64(val string) (uint64, error) { func Uint64(val string) (uint64, error) {
return strconv.ParseUint(val, 0, 64) return strconv.ParseUint(val, 10, 64)
} }
// Uint64Slice converts 'val' where individual integers are separated by // Uint64Slice converts 'val' where individual integers are separated by
@@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) {
// Uint32 converts the given string representation of an integer into uint32. // Uint32 converts the given string representation of an integer into uint32.
func Uint32(val string) (uint32, error) { func Uint32(val string) (uint32, error) {
i, err := strconv.ParseUint(val, 0, 32) i, err := strconv.ParseUint(val, 10, 32)
if err != nil { if err != nil {
return 0, err return 0, err
} }
@@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) {
return values, nil return values, nil
} }
// Bytes converts the given string representation of a byte sequence into a slice of bytes // 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 // Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or
// without padding.
func Bytes(val string) ([]byte, error) { func Bytes(val string) ([]byte, error) {
b, err := base64.StdEncoding.DecodeString(val) enc := base64.StdEncoding
if err != nil { if strings.ContainsAny(val, "-_") {
b, err = base64.URLEncoding.DecodeString(val) enc = base64.URLEncoding
if err != nil {
return nil, err
}
} }
return b, nil if len(val)%4 != 0 {
enc = enc.WithPadding(base64.NoPadding)
}
return enc.DecodeString(val)
} }
// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe // BytesSlice converts 'val' where individual bytes sequences, encoded in standard or
// base64 without padding, are separated by 'sep' into a slice of byte slices. // URL-safe base64, are separated by 'sep' into a slice of byte slices.
func BytesSlice(val, sep string) ([][]byte, error) { func BytesSlice(val, sep string) ([][]byte, error) {
s := strings.Split(val, sep) s := strings.Split(val, sep)
values := make([][]byte, len(s)) values := make([][]byte, len(s))
+2 -1
View File
@@ -134,7 +134,8 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh
w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Type", contentType)
if s.Code() == codes.Unauthenticated { if s.Code() == codes.Unauthenticated {
w.Header().Set("WWW-Authenticate", s.Message()) // Canonical spelling, so Header.Set does not have to build one.
w.Header().Set("Www-Authenticate", s.Message())
} }
buf, merr := marshaler.Marshal(respRw) buf, merr := marshaler.Marshal(respRw)
+52 -24
View File
@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"io" "io"
"sort" "sort"
"strings"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoreflect"
@@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
} }
if isProtobufAnyMessage(fd.Message()) && !fd.IsList() { if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
_, hasTypeField := v.(map[string]interface{})["@type"] vm, _ := v.(map[string]interface{})
if hasTypeField { if _, hasTypeField := vm["@type"]; !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()) 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{ child := fieldMaskPathItem{
@@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
queue = append(queue, child) queue = append(queue, child)
} }
} }
case ok && len(m) == 0:
fallthrough
case len(item.path) > 0: case len(item.path) > 0:
// otherwise, it's a leaf node so print its path // 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.
fm.Paths = append(fm.Paths, item.path) fm.Paths = append(fm.Paths, item.path)
} }
} }
@@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool {
// passed in name and json value. // passed in name and json value.
func buildPathsBlindly(name string, in interface{}) []string { func buildPathsBlindly(name string, in interface{}) []string {
m, ok := in.(map[string]interface{}) m, ok := in.(map[string]interface{})
if !ok { if !ok || len(m) == 0 {
return []string{name} 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 var paths []string
queue := []fieldMaskPathItem{{path: name, node: m}} queue := []queueItem{{path: &pathNode{segment: name}, node: m}}
for len(queue) > 0 { for len(queue) > 0 {
cur := queue[0] cur := queue[0]
queue = queue[1:] queue = queue[1:]
m, ok := cur.node.(map[string]interface{}) for k, v := range cur.node {
if !ok { child := &pathNode{parent: cur.path, segment: k}
// This should never happen since we should always check that we only add if mi, ok := v.(map[string]any); ok && len(mi) > 0 {
// nodes of type map[string]interface{} to the queue. queue = append(queue, queueItem{path: child, node: mi})
continue 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 return paths
+4 -1
View File
@@ -210,7 +210,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
} }
func requestAcceptsTrailers(req *http.Request) bool { func requestAcceptsTrailers(req *http.Request) bool {
te := req.Header.Get("TE") // "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")
return strings.Contains(strings.ToLower(te), "trailers") return strings.Contains(strings.ToLower(te), "trailers")
} }
+99 -3
View File
@@ -5,11 +5,13 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"math"
"reflect" "reflect"
"strconv" "strconv"
"google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
) )
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON // JSONPb is a Marshaler which marshals/unmarshals into/from JSON
@@ -30,6 +32,21 @@ func (*JSONPb) ContentType(_ interface{}) string {
// Marshal marshals "v" into JSON. // Marshal marshals "v" into JSON.
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { 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 var buf bytes.Buffer
if err := j.marshalTo(&buf, v); err != nil { if err := j.marshalTo(&buf, v); err != nil {
return nil, err return nil, err
@@ -251,18 +268,36 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key())
} }
m := make(map[string]*json.RawMessage) var raw json.RawMessage
if err := d.Decode(&m); err != nil { if err := d.Decode(&raw); err != nil {
return err return err
} }
m := make(map[string]*json.RawMessage)
if err := json.Unmarshal(raw, &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 { for k, v := range m {
result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) result := conv.Call([]reflect.Value{reflect.ValueOf(k)})
if err := result[1].Interface(); err != nil { if err := result[1].Interface(); err != nil {
return err.(error) return err.(error)
} }
bk := result[0] 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()) bv := reflect.New(rv.Type().Elem())
if v == nil { if v == nil {
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
return err
}
null := json.RawMessage("null") null := json.RawMessage("null")
v = &null v = &null
} }
@@ -293,6 +328,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
} }
for _, item := range sl { for _, item := range sl {
if string(item) == "null" {
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
return err
}
}
bv := reflect.New(rv.Type().Elem()) bv := reflect.New(rv.Type().Elem())
if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil { if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
return err return err
@@ -308,11 +348,30 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
} }
switch v := repr.(type) { switch v := repr.(type) {
case string: case string:
// TODO(yugui) Should use proto.StructProperties? // 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())
}
return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
case float64: 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())) rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
return nil return nil
case nil:
// protojson leaves a null enum field unset.
return nil
default: default:
return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
} }
@@ -320,6 +379,43 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
return d.Decode(v) 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 { type protoEnum interface {
fmt.Stringer fmt.Stringer
EnumDescriptor() ([]byte, []int) EnumDescriptor() ([]byte, []int)
@@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
if err != nil { if err != nil {
return err 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) return marshaller.Unmarshal(buffer, value)
}) })
} }
@@ -44,6 +44,18 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out
} }
for _, contentTypeVal := range r.Header[contentTypeHeader] { 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) contentType, _, err := mime.ParseMediaType(contentTypeVal)
if err != nil { if err != nil {
grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err) grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err)
Loaded 100 of 724 files, more files were not shown because too many files have changed in this diff. Show more