Compare commits

...
8 Commits
Author SHA1 Message Date
txix 66643980af 2026-12-01 11:31:14: merge [main:346c374e6d92145eef4cdd3c17ce94a46719e998];
Create and publish a Docker image / build-and-push-image (push) Waiting to run
2026-12-01 11:31:14 +03:00
txix c4d1760780 2026-11-20 13:47:56: merge [main:f7a141d25eda408fcfc42a718ae39527040ae012];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-11-20 13:47:56 +03:00
txix 749f0c7886 2026-11-20 12:19:20: merge [main:d45f814d6a0e2ab19da55393dc4f9cce9fb3a36c];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-11-20 12:19:20 +03:00
txix 1c94fc6cbb 2026-11-20 10:50:34: merge [main:b481c2a45ef9260735766fb5dea5b62ce5285a54];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-11-20 10:50:34 +03:00
txix cf59e61916 2026-10-28 11:42:14: merge [main:780c2232fbac671ac83e2dff49114323f66f8e1b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-10-28 11:42:14 +03:00
txix 373a5cd921 2026-09-25 14:17:44: merge [main:5c8a554d4ffba92695a752c19539ee54ac6a125f];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-09-25 14:17:44 +03:00
txix 0be5d9006a 2026-08-09 12:55:12: merge [main:2a846c67e4464370c1f5c9969133147e1d793e8e];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-08-09 12:55:12 +03:00
txix fdeffe36da 2026-07-27 16:36:28: merge [main:481f06bfecc9137eeb40afcdf359f671eca15fb8];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-27 16:36:28 +03:00
87 changed files with 5352 additions and 580 deletions

No files matched your search

+6
View File
@@ -8,6 +8,9 @@ linters:
- depguard # не всегда имеет смысл
- dupword # не имеет смысла
- exhaustruct # не имеет смысла
- exhaustruct_v5 # не имеет смысла
- goconst # не всегда имеет смысл
- gomodguard # deprecated
- godot # не актуально для swagger
- godox # не позволяет оставлять todo
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
@@ -61,6 +64,9 @@ linters:
- unqueryvet
- prealloc
path: ".*_test\\.go$"
- linters:
- testpackage
path: service/module # юниты обходов и аудита требуют доступа к неэкспортированным функциям
paths:
- third_party$
- builtin$
+1 -1
View File
@@ -1 +1 @@
3.9.2
3.13.0
+1 -1
View File
@@ -1,4 +1,4 @@
FROM golang:1.26-alpine AS builder
FROM golang:1.27-alpine AS builder
WORKDIR /build
ARG version
ENV version_env=$version
+1 -1
View File
@@ -1,5 +1,5 @@
FROM dockerhub.mos.ru/mosos/arbat:15.5 as builder
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.26 git
RUN zypper --no-gpg-checks update -y && zypper --no-gpg-checks install -y go1.27 git
WORKDIR /build
ARG version
ENV version_env=$version
+4 -1
View File
@@ -96,7 +96,7 @@ func (l Locator) Config() *Config {
configHistoryRepo := repository.NewConfigHistory(l.db)
variableRepo := repository.NewVariable(l.db)
variableService := variable.NewService(variableRepo, configRepo, eventRepo)
variableService := variable.NewService(variableRepo, configRepo, eventRepo, configSchemaRepo, l.logger)
variableController := api.NewVariable(variableService)
etpSrv := etp.NewServer(
@@ -134,6 +134,8 @@ func (l Locator) Config() *Config {
subscriptionService,
emitter,
variableService,
variableRepo,
l.cfg.Local.ConfigWriteDeny,
l.logger,
)
moduleController := controller.NewModule(moduleService, l.logger)
@@ -148,6 +150,7 @@ func (l Locator) Config() *Config {
configApiService := apisvs.NewConfig(
configRepo,
moduleRepo,
moduleService,
configSchemaRepo,
eventRepo,
configHistoryApiService,
+22
View File
@@ -1,3 +1,25 @@
### v3.13.0
* Добавлена обработка новых тегов конфигурации модулей: теги для UI экспонируемых полей и полей требующих ссылки на переменные с типом SECRET
* Добавлен эндпоинт `/config/audit` для получения информации о нарушении политики UI экспонируемых полей и полей требующих ссылки на переменные с типом SECRET
### v3.12.1
* Обновление ограничений конфигурации: в параметре `KeepConfigVersions` допустимо значение `0`
### v3.12.0
* Обновлен isp-kit до v1.76.0: подтянуты транзитивные зависимости (grpc v1.85.0, otel v1.47.0, goose v3.30.1, prometheus/client_golang v1.25.0), сервис собирается на Go 1.27
* Добавлена колонка `module_leader_mode` в таблицу `isp_config_service__backend` — режим выбора лидера, объявленный инстансом в `MODULE:READY`. Любое значение, кроме `REQUEST_ELECTION` (в том числе зарезервированные `IM_LEADER` и `IM_FOLLOWER`), нормализуется в пустое значение с логом уровня `warn`, рукопожатие при этом не отклоняется
* Для модулей, объявивших `REQUEST_ELECTION`, список адресов в событии `{module}_MODULE_CONNECTED` и карта маршрутов в `CONFIG:SEND_ROUTES_*` сузены до одного инстанса — лидера, а когда инстансов не осталось — до пустого списка. Модули без election не затронуты
* Лидер выводится из подключённых инстансов (минимум по `created_at`, тай-брейк по `ws_connection_id`) и нигде не хранится: ни новой таблицы, ни колонки «лидер/не лидер» нет
* Расширен ответ по `/module/get_modules_info` и `/routing/get_routes`: поле `isModuleLeader` в `domain.Connection`. `/routing/get_routes` остался полным — все инстансы всех модулей; сужение касается только событий, уходящих модулям
* Сужение видно в логах: публикация списка адресов модуля с election пишет `info` с адресом лидера, пересборка карты маршрутов — одной строкой список опубликованных лидеров (`модуль=адрес` через запятую). Модули без election по-прежнему не шумят
### v3.11.1
* Исправлено: при сохранении конфига с многократным использованием одной переменной через `_Var()` терялись все связи переменной с конфигами (конфликт PK в транзакции ссылок)
* Ошибки statement в rqlite-транзакциях больше не игнорируются молча, возвращаются как ошибка запроса
* Отключены линтеры `exhaustruct_v5`, `goconst`
### v3.11.0
* Добавлены `admin` permission к endpoint'ам
### v3.10.0
* событие `MODULE_READY` теперь может быть обработано несколько раз, обновляя полученные данные об инстансе модуля
### v3.9.3
* обновлены зависимости
### v3.9.2
* Обновлен isp-kit
### v3.9.1
+39 -37
View File
@@ -1,6 +1,6 @@
module isp-config-service/migrate
go 1.26
go 1.27
replace isp-config-service => ../..
@@ -8,8 +8,8 @@ require (
github.com/jmoiron/sqlx v1.4.0
github.com/mattn/go-sqlite3 v1.14.47
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.27.2
github.com/txix-open/isp-kit v1.71.1
github.com/pressly/goose/v3 v3.30.1
github.com/txix-open/isp-kit v1.76.0
isp-config-service v0.0.0-00010101000000-000000000000
)
@@ -19,59 +19,61 @@ require (
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.10.0 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/jackc/pgx/v5 v5.13.0 // indirect
github.com/jackc/puddle/v2 v2.2.4 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.19.0 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mfridman/interpolate v0.0.2 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mfridman/interpolate v0.2.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/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/prometheus/client_golang v1.23.2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.69.0 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/etp/v4 v4.1.1 // indirect
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect
github.com/txix-open/etp/v4 v4.1.3 // indirect
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sync v0.21.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.38.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 // indirect
google.golang.org/grpc v1.82.0 // indirect
google.golang.org/protobuf v1.36.11 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/net v0.63.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/grpc v1.85.0 // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+111 -77
View File
@@ -19,28 +19,37 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8=
github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
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/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-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.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
github.com/go-sql-driver/mysql v1.10.1/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
@@ -50,16 +59,19 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
@@ -68,6 +80,9 @@ github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4d
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
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/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
@@ -78,17 +93,17 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mattn/go-sqlite3 v1.14.47 h1:jOBI62gS7nKeZv+as1oGEy0+1qISgXwH/QBlR6KbfIo=
github.com/mattn/go-sqlite3 v1.14.47/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
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/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -98,29 +113,46 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
github.com/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.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8=
github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM=
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk=
github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y=
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -132,8 +164,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
@@ -144,64 +176,66 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU=
github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/isp-kit v1.71.1 h1:MNSuHy/HEvy7dKPQXkM+dgQpShDhcv1Sq1kLgep2LaA=
github.com/txix-open/isp-kit v1.71.1/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 h1:eM/YSd5bBFagF51o1E745Ta7RwzpW0h+z+QDNZOgmQ8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
@@ -210,11 +244,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
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/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
+1 -1
View File
@@ -18,9 +18,9 @@ import (
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/migrate/migration"
+1 -1
View File
@@ -9,8 +9,8 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"github.com/pressly/goose/v3"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
+2
View File
@@ -9,6 +9,8 @@ grpcInnerAddress:
port: 9002
moduleName: isp-config-service
configWriteDeny: true
infraServerPort: 9006
logLevel: debug
+2 -1
View File
@@ -11,10 +11,11 @@ type Local struct {
ConfigServiceAddress bootstrap.ConfigServiceAddr
MaintenanceMode bool
Credentials []auth.Credential
KeepConfigVersions int `validate:"required"`
KeepConfigVersions int
InternalClientCredential string `validate:"required"`
Rqlite Rqlite
Backup rqlite.Backup
ConfigWriteDeny bool
}
type Rqlite struct {
+54 -5
View File
@@ -5,12 +5,13 @@ import (
"context"
"strconv"
"github.com/pkg/errors"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/metadata"
"isp-config-service/domain"
"isp-config-service/entity"
)
type ConfigService interface {
@@ -22,6 +23,7 @@ type ConfigService interface {
DeleteConfig(ctx context.Context, id string) error
UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error
SyncConfig(ctx context.Context, moduleName string) error
Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error)
}
type Config struct {
@@ -184,12 +186,24 @@ func (c Config) GetConfigById(ctx context.Context, req domain.IdRequest) (*domai
// @Produce json
// @Param body body domain.IdRequest true "id конфигурации для изменения"
// @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - конфигурация нарушает политику секретных переменных (детали по путям в `details`)<br/>"
// @Failure 500 {object} apierrors.Error
// @Router /config/mark_config_as_active [POST]
func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.IdRequest) error {
err := c.service.MarkConfigAsActive(ctx, identity.Id)
var validationError domain.ConfigValidationError
switch {
case errors.As(err, &validationError):
details := map[string]any{}
for key, value := range validationError.Details {
details[key] = value
}
return apierrors.NewBusinessError(
domain.ErrorCodeInvalidConfig,
"invalid config",
err,
).WithDetails(details)
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
@@ -272,21 +286,56 @@ func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNam
// @Produce json
// @Param body body domain.SyncConfigRequest true "название модуля"
// @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден"
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - в UI-экспонируемых полях активная конфигурация ссылается на секретную переменную"
// @Failure 500 {object} apierrors.Error
// @Router /config/sync_config [POST]
func (c Config) SyncConfig(ctx context.Context, req domain.SyncConfigRequest) error {
err := c.service.SyncConfig(ctx, req.ModuleName)
var validationError domain.ConfigValidationError
switch {
case errors.As(err, &validationError):
details := map[string]any{}
for key, value := range validationError.Details {
details[key] = value
}
return apierrors.NewBusinessError(
domain.ErrorCodeInvalidConfig,
"invalid config",
err,
).WithDetails(details)
case errors.Is(err, entity.ErrModuleNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil:
return apierrors.NewInternalServiceError(err)
default:
return nil
}
}
// @Summary Метод получения отчёта о нарушениях секретной политики
// @Description Возвращает нарушения секретной политики в активных конфигурациях: ссылки на SECRET в UI-экспонируемых полях и не-SECRET значения в sensitive-полях
// @Tags Конфигурация
// @Accept json
// @Produce json
// @Param body body domain.AuditRequest true "имя модуля, пустое значение — все модули"
// @Success 200 {array} domain.AuditViolation
// @Failure 500 {object} apierrors.Error
// @Router /config/audit [POST]
func (c Config) Audit(ctx context.Context, req domain.AuditRequest) ([]domain.AuditViolation, error) {
violations, err := c.service.Audit(ctx, req.ModuleName)
if err != nil {
return nil, apierrors.NewInternalServiceError(err)
}
return violations, nil
}
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
)
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
)
+1 -1
View File
@@ -4,7 +4,7 @@ package api
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/apierrors"
_ "github.com/txix-open/isp-kit/grpc/apierrors"
"isp-config-service/domain"
+1 -1
View File
@@ -3,7 +3,7 @@ package controller
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/apierrors"
"isp-config-service/domain"
)
+29 -2
View File
@@ -2,14 +2,18 @@ package controller
import (
"context"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/helpers"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
var (
@@ -35,6 +39,7 @@ type ModuleService interface {
conn *etp.Conn,
data cluster.ConfigData,
) error
Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error)
}
type Module struct {
@@ -49,6 +54,28 @@ func NewModule(service ModuleService, logger log.Logger) Module {
}
}
func (m Module) Audit(ctx context.Context, req domain.GetByModuleNameRequest) ([]domain.AuditViolation, error) {
violations, err := m.service.Audit(ctx, req.ModuleName)
switch {
case errors.Is(err, entity.ErrModuleNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound,
"module not found",
err,
)
case errors.Is(err, entity.ErrConfigNotFound):
return nil, apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"active config not found",
err,
)
case err != nil:
return nil, apierrors.NewInternalServiceError(err)
default:
return violations, nil
}
}
func (m Module) OnConnect(conn *etp.Conn) {
ctx := conn.HttpRequest().Context()
err := conn.HttpRequest().ParseForm()
+54 -2
View File
@@ -7,6 +7,24 @@ definitions:
port:
type: string
type: object
domain.AuditRequest:
properties:
moduleName:
type: string
type: object
domain.AuditViolation:
properties:
module:
type: string
path:
type: string
reason:
type: string
variables:
items:
type: string
type: array
type: object
domain.Config:
properties:
active:
@@ -68,6 +86,8 @@ definitions:
type: string
id:
type: string
isModuleLeader:
type: boolean
libVersion:
type: string
moduleName:
@@ -352,6 +372,35 @@ info:
title: isp-config-service
version: 3.0.0
paths:
/config/audit:
post:
consumes:
- application/json
description: 'Возвращает нарушения секретной политики в активных конфигурациях:
ссылки на SECRET в UI-экспонируемых полях и не-SECRET значения в sensitive-полях'
parameters:
- description: имя модуля, пустое значение — все модули
in: body
name: body
required: true
schema:
$ref: '#/definitions/domain.AuditRequest'
produces:
- application/json
responses:
"200":
description: OK
schema:
items:
$ref: '#/definitions/domain.AuditViolation'
type: array
"500":
description: Internal Server Error
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
summary: Метод получения отчёта о нарушениях секретной политики
tags:
- Конфигурация
/config/create_update_config:
post:
consumes:
@@ -591,7 +640,9 @@ paths:
"200":
description: OK
"400":
description: '`errorCode: 2002` - конфиг не найден<br/>'
description: '`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003`
- конфигурация нарушает политику секретных переменных (детали по путям
в `details`)<br/>'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
@@ -655,7 +706,8 @@ paths:
$ref: '#/definitions/domain.Config'
"400":
description: '`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002`
- конфиг не найден'
- конфиг не найден<br/>`errorCode: 2003` - в UI-экспонируемых полях активная
конфигурация ссылается на секретную переменную'
schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500":
+4
View File
@@ -21,6 +21,10 @@ type GetByModuleNameRequest struct {
ModuleName string `validate:"required"`
}
type AuditRequest struct {
ModuleName string
}
type UpdateSchemaRequest struct {
ModuleName string `validate:"required"`
Schema json.RawMessage `validate:"required" swaggertype:"object"`
+16 -8
View File
@@ -10,6 +10,13 @@ type DeleteResponse struct {
Deleted int
}
type AuditViolation struct {
Module string
Path string
Variables []string
Reason string
}
type CreateUpdateConfigResponse struct {
Config
@@ -28,14 +35,15 @@ type ModuleInfo struct {
}
type Connection struct {
Id string
ModuleName string
LibVersion string
Version string
Address Address
Transport string
Endpoints []EndpointDescriptor
EstablishedAt time.Time
Id string
ModuleName string
LibVersion string
Version string
Address Address
IsModuleLeader bool
Transport string
Endpoints []EndpointDescriptor
EstablishedAt time.Time
}
type Address struct {
+1
View File
@@ -14,6 +14,7 @@ type Backend struct {
LibVersion string `json:"lib_version"`
ModuleName string `json:"module_name"`
Transport string `json:"transport"`
ModuleLeaderMode string `json:"module_leader_mode"`
ConfigServiceNodeId string `json:"config_service_node_id"`
Endpoints xtypes.Json[[]cluster.EndpointDescriptor] `json:"endpoints"`
RequiredModules xtypes.Json[[]cluster.ModuleDependency] `json:"required_modules"`
+1 -1
View File
@@ -1,7 +1,7 @@
package entity
import (
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
var (
+13 -6
View File
@@ -5,13 +5,20 @@ import (
"isp-config-service/entity/xtypes"
)
type VariableType = string
const (
SecretType VariableType = "SECRET"
TextType VariableType = "TEXT"
)
type Variable struct {
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Value string `json:"value"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
Name string `json:"name"`
Description string `json:"description"`
Type VariableType `json:"type"`
Value string `json:"value"`
CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"`
}
type ConfigHasVariable struct {
+1 -1
View File
@@ -3,7 +3,7 @@ package xtypes
import (
"strconv"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"strconv"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
type Time time.Time
+44 -45
View File
@@ -1,30 +1,29 @@
module isp-config-service
go 1.26
go 1.27
replace (
github.com/armon/go-metrics => github.com/hashicorp/go-metrics v0.5.1
github.com/mattn/go-sqlite3 => github.com/rqlite/go-sqlite3 v1.48.0
golang.org/x/text => golang.org/x/text v0.3.8
)
require (
github.com/Masterminds/squirrel v1.5.4
github.com/google/uuid v1.6.0
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.27.2
github.com/prometheus/client_golang v1.23.2
github.com/pressly/goose/v3 v3.30.1
github.com/prometheus/client_golang v1.25.0
github.com/rqlite/gorqlite v0.0.0-20250609141355-ac86a4a1c9a8
github.com/rqlite/rqlite-disco-clients v0.0.0-20250205044118-8ada2b350099
github.com/rqlite/rqlite/v10 v10.2.7
github.com/stretchr/testify v1.11.1
github.com/stretchr/testify v1.12.1
github.com/tidwall/gjson v1.18.0
github.com/txix-open/etp/v4 v4.1.1
github.com/txix-open/bellows v1.2.0
github.com/txix-open/etp/v4 v4.1.3
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60
github.com/txix-open/isp-kit v1.71.1
github.com/txix-open/isp-kit v1.77.1
github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/sync v0.21.0
google.golang.org/grpc v1.82.0
golang.org/x/sync v0.25.0
google.golang.org/grpc v1.85.0
)
require (
@@ -50,20 +49,19 @@ require (
github.com/aws/smithy-go v1.27.2 // indirect
github.com/bahlo/generic-list-go v0.2.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/buger/jsonparser v1.2.0 // indirect
github.com/buger/jsonparser v1.6.1 // indirect
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fatih/color v1.19.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/getsentry/sentry-go v0.47.0 // indirect
github.com/go-faker/faker/v4 v4.9.0 // indirect
github.com/go-logr/logr v1.4.3 // indirect
github.com/gabriel-vasile/mimetype v1.4.16 // indirect
github.com/getsentry/sentry-go v0.50.0 // indirect
github.com/go-faker/faker/v4 v4.12.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/go-playground/locales v0.14.2 // indirect
github.com/go-playground/universal-translator v0.18.2 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect
github.com/hashicorp/go-hclog v1.6.3 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-metrics v0.6.0 // indirect
@@ -73,53 +71,54 @@ require (
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/hashicorp/raft v1.7.3 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.19.0 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/mailru/easyjson v0.9.2 // indirect
github.com/mattn/go-colorable v0.1.15 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
github.com/mattn/go-isatty v0.0.24 // indirect
github.com/mattn/go-sqlite3 v1.14.47 // 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/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_model v0.6.2 // indirect
github.com/prometheus/common v0.69.0 // indirect
github.com/prometheus/procfs v0.21.1 // indirect
github.com/pandatix/go-abnf v0.5.5 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.74.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/rqlite/raft-boltdb/v2 v2.0.0-20230523104317-c08e70f4de48 // indirect
github.com/rqlite/sql v0.0.0-20260224021119-1b2524a41372 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
github.com/txix-open/bellows v1.2.0 // indirect
github.com/txix-open/jsonschema v1.3.0 // 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/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
go.etcd.io/bbolt v1.5.0 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 // indirect
go.opentelemetry.io/otel v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
go.opentelemetry.io/otel/metric v1.44.0 // indirect
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
go.opentelemetry.io/otel/trace v1.44.0 // indirect
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
go.opentelemetry.io/otel v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
go.opentelemetry.io/otel/log v1.47.0 // indirect
go.opentelemetry.io/otel/metric v1.47.0 // indirect
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
go.opentelemetry.io/otel/trace v1.47.0 // indirect
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
golang.org/x/crypto v0.53.0 // indirect
golang.org/x/net v0.56.0 // indirect
golang.org/x/sys v0.46.0 // indirect
golang.org/x/text v0.38.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 // indirect
google.golang.org/protobuf v1.36.11 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/crypto v0.59.0 // indirect
golang.org/x/net v0.63.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/text v0.44.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
google.golang.org/protobuf v1.36.12 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
+105 -122
View File
@@ -52,8 +52,8 @@ github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+Ce
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps=
github.com/buger/jsonparser v1.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g=
github.com/buger/jsonparser v1.2.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
@@ -65,40 +65,36 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8=
github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
github.com/go-faker/faker/v4 v4.9.0 h1:a4HXLwueuTCtgF93VpUsl8Zd2nG1VH2SgNWDPVEBg5U=
github.com/go-faker/faker/v4 v4.9.0/go.mod h1:u1dIRP5neLB6kTzgyVjdBOV5R1uP7BdxkcWk7tiKQXk=
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
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/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/go-test/deep v1.0.8 h1:TDsG77qcSprGbC6vTN8OuXp5g+J+b5Pcguhf7Zt61VM=
github.com/go-test/deep v1.0.8/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
@@ -115,8 +111,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-hclog v0.9.1/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=
@@ -151,8 +147,8 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@@ -168,8 +164,8 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk=
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0=
github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE=
github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M=
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
@@ -178,11 +174,11 @@ github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
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/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -195,8 +191,10 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjY
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/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g=
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY=
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
@@ -206,31 +204,29 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/pressly/goose/v3 v3.27.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8=
github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM=
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU=
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4=
github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk=
github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y=
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
github.com/rabbitmq/amqp091-go v1.12.0 h1:V0v14Iqfs+MwHWihJt/nGS5Ulu0vw572b2Co3mwunkI=
github.com/rabbitmq/amqp091-go v1.12.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -247,8 +243,8 @@ github.com/rqlite/rqlite/v10 v10.2.7 h1:fUsbbgoELw+MrKfQ9EkVrm8tA0rdVUe/bYYdtOOs
github.com/rqlite/rqlite/v10 v10.2.7/go.mod h1:iTG1rLhR0zBBWTHiN33b9o/HXVwaC71xrcdoFaUJecE=
github.com/rqlite/sql v0.0.0-20260224021119-1b2524a41372 h1:2V0y6mzmPj7vQKad76nTL7sZ/lFLj5VKvNjpa6IRxYE=
github.com/rqlite/sql v0.0.0-20260224021119-1b2524a41372/go.mod h1:ib9zVtNgRKiGuoMyUqqL5aNpk+r+++YlyiVIkclVqPg=
github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=
github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas=
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
@@ -264,8 +260,8 @@ github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1F
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
@@ -277,18 +273,18 @@ github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhso
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU=
github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo=
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60 h1:7SZ72lNU69g8eiT5rcRh1ubATZPs/J05NEIN7E47TYM=
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60/go.mod h1:jzpq0uwcdGq0OSNXZ6vv6UJkCOU/fLPgeoz+KkGDYgo=
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.71.1 h1:MNSuHy/HEvy7dKPQXkM+dgQpShDhcv1Sq1kLgep2LaA=
github.com/txix-open/isp-kit v1.71.1/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74=
github.com/txix-open/isp-kit v1.77.1 h1:D8g2iXjN9CsGEBuPCskHSy/jV6uUbQrpExiVarkQDrM=
github.com/txix-open/isp-kit v1.77.1/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
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 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
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/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
@@ -298,63 +294,58 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ=
go.etcd.io/bbolt v1.5.0 h1:S7GAl7Fxv12yohbwFfIbQCGDWbQbtDGPET4P/bD4lxU=
go.etcd.io/bbolt v1.5.0/go.mod h1:mkltfYE5aUHQxUct9N9V+Kp7aSjFqjgrhcXIS70Lrdk=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw=
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw=
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
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/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
go.yaml.in/yaml/v2 v2.4.5/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -363,34 +354,26 @@ golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220503163025-988cb79eb6c6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/tools v0.0.0-20190424220101-1e8e1cfdf96b/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU=
google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7 h1:eM/YSd5bBFagF51o1E745Ta7RwzpW0h+z+QDNZOgmQ8=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260630182238-925bb5da69e7/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.82.0 h1:vguDnZUPjE26w09A63VoxZPnvPjB5Riyc0mkXPFmAIU=
google.golang.org/grpc v1.82.0/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
@@ -405,11 +388,11 @@ gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA=
modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8=
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
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/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M=
modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s=
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
modernc.org/memory v1.12.1/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
modernc.org/sqlite v1.62.0/go.mod h1:Jzjh1mt4s0HuQ0KvtB1LIuHiGRmU2D5pgj8dUhW7/SE=
+1 -1
View File
@@ -3,9 +3,9 @@ package helpers
import (
"net"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
)
+6 -1
View File
@@ -26,7 +26,12 @@ var (
//go:generate swag init --parseDependency
//go:generate rm -f docs/swagger.json docs/docs.go
func main() {
boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport)
boot := bootstrap.New(
version,
conf.Remote{},
cluster.Endpoints(routes.EndpointDescriptors()),
cluster.GrpcTransport,
)
app := boot.App
logger := app.Logger()
+2 -1
View File
@@ -2,6 +2,7 @@ package middlewares
import (
"context"
"slices"
"github.com/txix-open/etp/v4"
@@ -27,7 +28,7 @@ func EtpLogger(logger log.Logger) EtpMiddleware {
//nolint:ireturn
func EtpChain(root etp.Handler, middlewares ...EtpMiddleware) etp.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
for i := range slices.Backward(middlewares) {
root = middlewares[i](root)
}
return root
@@ -0,0 +1,6 @@
-- +goose Up
-- +goose NO TRANSACTION
alter table isp_config_service__backend add column module_leader_mode text;
-- +goose Down
alter table isp_config_service__backend drop column module_leader_mode;
+40 -8
View File
@@ -4,11 +4,12 @@ import (
"context"
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/errors"
)
type Backend struct {
@@ -21,19 +22,27 @@ func NewBackend(db db.DB) Backend {
}
}
func (r Backend) Insert(ctx context.Context, backend entity.Backend) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Insert")
func (r Backend) Upsert(ctx context.Context, backend entity.Backend) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.Upsert")
query, args, err := squirrel.Insert(Table("backend")).
Columns("ws_connection_id", "module_id", "address",
"version", "lib_version", "module_name", "transport",
"config_service_node_id", "endpoints", "required_modules",
"metrics_autodiscovery").
"module_leader_mode", "config_service_node_id", "endpoints",
"required_modules", "metrics_autodiscovery").
Values(backend.WsConnectionId, backend.ModuleId, backend.Address,
backend.Version, backend.LibVersion, backend.ModuleName, backend.Transport,
backend.ConfigServiceNodeId, backend.Endpoints, backend.RequiredModules,
backend.MetricsAutodiscovery,
backend.ModuleLeaderMode, backend.ConfigServiceNodeId, backend.Endpoints,
backend.RequiredModules, backend.MetricsAutodiscovery,
).
Suffix(`on conflict (ws_connection_id) do update
set module_id = excluded.module_id, address = excluded.address,
version = excluded.version, lib_version = excluded.lib_version,
module_name = excluded.module_name, transport = excluded.transport,
module_leader_mode = excluded.module_leader_mode,
config_service_node_id = excluded.config_service_node_id,
endpoints = excluded.endpoints, required_modules = excluded.required_modules,
metrics_autodiscovery = excluded.metrics_autodiscovery`).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
@@ -157,6 +166,29 @@ func (r Backend) GetByModuleId(ctx context.Context, moduleId string) ([]entity.B
return result, nil
}
func (r Backend) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.GetForLeaderElection")
// nolint:unqueryvet
query, args, err := squirrel.Select("*").
From(Table("backend")).
Where(squirrel.Eq{
"module_id": moduleId,
}).OrderBy("created_at asc", "ws_connection_id asc").
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Backend, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Backend) AllMetricsAutodiscovery(ctx context.Context) ([]entity.MetricsAdWrapper, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Backend.AllMetricsAutodiscovery")
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"database/sql"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/middlewares/sql_metrics"
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
+36 -10
View File
@@ -5,11 +5,12 @@ import (
"database/sql"
"strings"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors"
"isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/errors"
)
type Variable struct {
@@ -66,6 +67,35 @@ func (r Variable) GetByName(ctx context.Context, name string) (*entity.Variable,
return &result, nil
}
func (r Variable) GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variables.GetObjectsByName")
ns := make([]string, 0, len(names))
for n := range names {
ns = append(ns, n)
}
if len(ns) == 0 {
return []entity.Variable{}, nil
}
query, args, err := squirrel.Select("name", "type").
From(Table("variable")).
Where(squirrel.Eq{"name": ns}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
result := make([]entity.Variable, 0)
err = r.db.Select(ctx, &result, query, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select: %s", query)
}
return result, nil
}
func (r Variable) Insert(ctx context.Context, variable entity.Variable) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert")
@@ -157,14 +187,10 @@ func (r Variable) UpsertLinks(ctx context.Context, configId string, links []enti
}
for _, variable := range links {
query, args, err := squirrel.Insert(Table("config_has_variable")).
Columns("config_id", "variable_name").
Values(variable.ConfigId, variable.VariableName).
ToSql()
if err != nil {
return errors.WithMessage(err, "build query")
}
requests = append(requests, db.Request(query, args...))
requests = append(requests, db.Request(
`insert or ignore into `+Table("config_has_variable")+` (config_id, variable_name) values (?, ?)`,
variable.ConfigId, variable.VariableName,
))
}
_, err = r.db.ExecTransaction(ctx, requests)
+60 -7
View File
@@ -27,12 +27,23 @@ type Controllers struct {
}
func EndpointDescriptors() []cluster.EndpointDescriptor {
return endpointDescriptors(Controllers{})
c := Controllers{}
return concatEndpoints(
modulesDescriptors(c),
configsDescriptors(c),
variablesDescriptors(c),
)
}
func GrpcHandler(wrapper endpoint.Wrapper, c Controllers) *grpc.Mux {
muxer := grpc.NewMux()
for _, descriptor := range endpointDescriptors(c) {
for _, descriptor := range modulesDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
for _, descriptor := range configsDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
for _, descriptor := range variablesDescriptors(c) {
muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler))
}
return muxer
@@ -67,106 +78,148 @@ func HttpHandler(etpSrv *etp.Server, conf conf.Local, rqliteProxy, rqliteBackupP
return httpMux
}
// nolint:funlen
func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
func modulesDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
// modules
{
Path: "config/module/get_modules_info",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ModuleApi.Status,
}, {
Path: "config/module/delete_module",
Inner: true,
Extra: cluster.RequireAdminPermission("module_delete"),
Handler: c.ModuleApi.DeleteModule,
}, {
Path: "config/routing/get_routes",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ModuleApi.Connections,
}, {
Path: "config/module/get_required_modules",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ModuleApi.RequiredModules,
},
// configs
}
}
func configsDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "config/config/get_active_config_by_module_name",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigApi.GetActiveConfigByModuleName,
}, {
Path: "config/config/get_configs_by_module_id",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigApi.GetConfigsByModuleId,
}, {
Path: "config/config/audit",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigApi.Audit,
}, {
Path: "config/config/create_update_config",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_edit"),
Handler: c.ConfigApi.CreateUpdateConfig,
}, {
Path: "config/config/get_config_by_id",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigApi.GetConfigById,
}, {
Path: "config/config/mark_config_as_active",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_set_active"),
Handler: c.ConfigApi.MarkConfigAsActive,
}, {
Path: "config/config/update_config_name",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_edit"),
Handler: c.ConfigApi.UpdateConfigName,
}, {
Path: "config/config/delete_config",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_edit"),
Handler: c.ConfigApi.DeleteConfigs,
}, {
Path: "config/config/sync",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_edit"),
Handler: c.ConfigApi.SyncConfig,
}, {
Path: "config/config/get_all_version",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigHistoryApi.GetAllVersion,
}, {
Path: "config/config/delete_version",
Inner: true,
Extra: cluster.RequireAdminPermission("module_history_delete_version"),
Handler: c.ConfigHistoryApi.DeleteConfigVersion,
}, {
Path: "config/config/purge_versions",
Inner: true,
Extra: cluster.RequireAdminPermission("module_history_delete_version"),
Handler: c.ConfigHistoryApi.PurgeConfigVersions,
}, {
Path: "config/schema/get_by_module_id",
Inner: true,
Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigSchemaApi.SchemaByModuleId,
}, {
Path: "config/schema/update_by_module_name",
Inner: true,
Extra: cluster.RequireAdminPermission("module_configuration_edit"),
Handler: c.ConfigSchemaApi.UpdateSchemaByModuleName,
},
// variables
}
}
func variablesDescriptors(c Controllers) []cluster.EndpointDescriptor {
return []cluster.EndpointDescriptor{
{
Path: "config/variable/all",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_view"),
Handler: c.VariableApi.All,
}, {
Path: "config/variable/get_by_name",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_view"),
Handler: c.VariableApi.GetByName,
}, {
Path: "config/variable/create",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_add"),
Handler: c.VariableApi.Create,
}, {
Path: "config/variable/update",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_edit"),
Handler: c.VariableApi.Update,
}, {
Path: "config/variable/upsert",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_edit"),
Handler: c.VariableApi.Upsert,
}, {
Path: "config/variable/delete",
Inner: true,
Extra: cluster.RequireAdminPermission("variable_delete"),
Handler: c.VariableApi.Delete,
},
}
}
func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor {
var result []cluster.EndpointDescriptor
for _, c := range endpoints {
result = append(result, c...)
}
return result
}
+147 -97
View File
@@ -4,15 +4,16 @@ import (
"context"
"time"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/txix-open/go-cmp/cmp"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
"github.com/xeipuuv/gojsonschema"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"github.com/google/uuid"
"github.com/txix-open/go-cmp/cmp"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
"github.com/xeipuuv/gojsonschema"
)
type ConfigRepo interface {
@@ -39,9 +40,15 @@ type VariableService interface {
SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error
}
type ModuleService interface {
FilterSecretParams(ctx context.Context, config json.RawMessage, moduleId string) error
Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error)
}
type Config struct {
configRepo ConfigRepo
moduleRepo ModuleRepo
moduleService ModuleService
schemaRepo SchemaRepo
eventRepo EventRepo
configHistoryService ConfigHistoryService
@@ -52,6 +59,7 @@ type Config struct {
func NewConfig(
configRepo ConfigRepo,
moduleRepo ModuleRepo,
moduleService ModuleService,
schemaRepo SchemaRepo,
eventRepo EventRepo,
configHistoryService ConfigHistoryService,
@@ -61,6 +69,7 @@ func NewConfig(
return Config{
configRepo: configRepo,
moduleRepo: moduleRepo,
moduleService: moduleService,
schemaRepo: schemaRepo,
eventRepo: eventRepo,
configHistoryService: configHistoryService,
@@ -121,8 +130,13 @@ func (c Config) CreateUpdateConfig(
adminId int,
req domain.CreateUpdateConfigRequest,
) (*domain.CreateUpdateConfigResponse, error) {
err := c.moduleService.FilterSecretParams(ctx, req.Data, req.ModuleId)
if err != nil {
return nil, errors.WithMessage(err, "filter secret params")
}
if !req.Unsafe {
err := c.validateConfigUpdate(ctx, req.ModuleId, req.Data)
err = c.validateConfigUpdate(ctx, req.ModuleId, req.Data)
if err != nil {
return nil, errors.WithMessage(err, "validate config")
}
@@ -134,6 +148,123 @@ func (c Config) CreateUpdateConfig(
Config: newConfig, IsChanged: true}, err
}
return c.updateConfig(ctx, adminId, req)
}
func (c Config) GetConfigById(ctx context.Context, configId string) (*domain.Config, error) {
config, err := c.configRepo.GetById(ctx, configId)
if err != nil {
return nil, errors.WithMessage(err, "get config by id")
}
if config == nil {
return nil, entity.ErrConfigNotFound
}
return new(configToDto(*config, nil)), nil
}
func (c Config) MarkConfigAsActive(ctx context.Context, configId string) error {
cfg, err := c.configRepo.GetById(ctx, configId)
if err != nil {
return errors.WithMessage(err, "get config by id")
}
if cfg == nil {
return entity.ErrConfigNotFound
}
err = c.moduleService.FilterSecretParams(ctx, cfg.Data, cfg.ModuleId)
if err != nil {
return errors.WithMessage(err, "filter secret params")
}
currentActiveConfig, err := c.configRepo.GetActive(ctx, cfg.ModuleId)
if err != nil {
return errors.WithMessage(err, "get active config")
}
if currentActiveConfig != nil {
err := c.configRepo.SetActive(ctx, currentActiveConfig.Id, false)
if err != nil {
return errors.WithMessage(err, "deactivate config")
}
}
err = c.configRepo.SetActive(ctx, configId, true)
if err != nil {
return errors.WithMessage(err, "set active config")
}
err = c.emitChangeActiveConfigEvent(ctx, cfg.ModuleId)
if err != nil {
return errors.WithMessage(err, "emit change active config event")
}
return nil
}
func (c Config) DeleteConfig(ctx context.Context, configId string) error {
deleted, err := c.configRepo.DeleteNonActiveById(ctx, configId)
if err != nil {
return errors.WithMessage(err, "delete config")
}
if !deleted {
return entity.ErrConfigNotFoundOrActive
}
return nil
}
func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error {
exist, err := c.configRepo.UpdateConfigName(ctx, req)
if err != nil {
return errors.WithMessage(err, "update config name")
}
if !exist {
return entity.ErrConfigNotFound
}
return nil
}
func (c Config) SyncConfig(ctx context.Context, moduleName string) error {
modules, err := c.moduleRepo.GetByNames(ctx, []string{moduleName})
if err != nil {
return errors.WithMessage(err, "get config by module name")
}
if len(modules) == 0 {
return entity.ErrModuleNotFound
}
moduleId := modules[0].Id
activeConfig, err := c.configRepo.GetActive(ctx, moduleId)
if err != nil {
return errors.WithMessage(err, "get active config")
}
if activeConfig == nil {
return entity.ErrConfigNotFound
}
err = c.moduleService.FilterSecretParams(ctx, activeConfig.Data, moduleId)
if err != nil {
return errors.WithMessage(err, "filter secret params")
}
err = c.emitChangeActiveConfigEvent(ctx, moduleId)
if err != nil {
return errors.WithMessage(err, "emit change active config event")
}
return nil
}
func (c Config) Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error) {
violations, err := c.moduleService.Audit(ctx, moduleName)
if err != nil {
return nil, errors.WithMessage(err, "audit module configs")
}
return violations, nil
}
func (c Config) updateConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (*domain.CreateUpdateConfigResponse, error) {
variableExtractionResult, err := c.extractAndCheckVariables(ctx, req.Id, req.Data)
if err != nil {
return nil, errors.WithMessage(err, "extract variables")
@@ -199,92 +330,6 @@ func (c Config) CreateUpdateConfig(
Config: configToDto(newConfig, nil), IsChanged: true}, nil
}
func (c Config) GetConfigById(ctx context.Context, configId string) (*domain.Config, error) {
config, err := c.configRepo.GetById(ctx, configId)
if err != nil {
return nil, errors.WithMessage(err, "get config by id")
}
if config == nil {
return nil, entity.ErrConfigNotFound
}
return new(configToDto(*config, nil)), nil
}
func (c Config) MarkConfigAsActive(ctx context.Context, configId string) error {
cfg, err := c.configRepo.GetById(ctx, configId)
if err != nil {
return errors.WithMessage(err, "get config by id")
}
if cfg == nil {
return entity.ErrConfigNotFound
}
currentActiveConfig, err := c.configRepo.GetActive(ctx, cfg.ModuleId)
if err != nil {
return errors.WithMessage(err, "get active config")
}
if currentActiveConfig != nil {
err := c.configRepo.SetActive(ctx, currentActiveConfig.Id, false)
if err != nil {
return errors.WithMessage(err, "deactivate config")
}
}
err = c.configRepo.SetActive(ctx, configId, true)
if err != nil {
return errors.WithMessage(err, "set active config")
}
err = c.emitChangeActiveConfigEvent(ctx, cfg.ModuleId)
if err != nil {
return errors.WithMessage(err, "emit change active config event")
}
return nil
}
func (c Config) DeleteConfig(ctx context.Context, configId string) error {
deleted, err := c.configRepo.DeleteNonActiveById(ctx, configId)
if err != nil {
return errors.WithMessage(err, "delete config")
}
if !deleted {
return entity.ErrConfigNotFoundOrActive
}
return nil
}
func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error {
exist, err := c.configRepo.UpdateConfigName(ctx, req)
if err != nil {
return errors.WithMessage(err, "update config name")
}
if !exist {
return entity.ErrConfigNotFound
}
return nil
}
func (c Config) SyncConfig(ctx context.Context, moduleName string) error {
modules, err := c.moduleRepo.GetByNames(ctx, []string{moduleName})
if err != nil {
return errors.WithMessage(err, "get config by module name")
}
if len(modules) == 0 {
return entity.ErrModuleNotFound
}
moduleId := modules[0].Id
err = c.emitChangeActiveConfigEvent(ctx, moduleId)
if err != nil {
return errors.WithMessage(err, "emit change active config event")
}
return nil
}
func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (domain.Config, error) {
config := entity.Config{
Id: uuid.NewString(),
@@ -295,15 +340,20 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre
Active: false,
AdminId: adminId,
}
err := c.configRepo.Insert(ctx, config)
err := c.moduleService.FilterSecretParams(ctx, req.Data, req.ModuleId)
if err != nil {
return domain.Config{}, errors.WithMessage(err, "insert new config")
return domain.Config{}, errors.WithMessage(err, "filter secret params")
}
extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data)
if err != nil {
return domain.Config{}, err
}
err = c.configRepo.Insert(ctx, config)
if err != nil {
return domain.Config{}, errors.WithMessage(err, "insert new config")
}
err = c.variableService.SaveVariableLinks(ctx, config.Id, extractResult.VariableLinks)
if err != nil {
return domain.Config{}, errors.WithMessage(err, "save variable links")
@@ -323,7 +373,7 @@ func (c Config) extractAndCheckVariables(ctx context.Context, configId string, i
for _, variable := range variableExtractionResult.AbsentVariables {
details[variable] = "variable is not defined"
}
return nil, domain.NewConfigValidationError(details)
return nil, errors.WithMessage(domain.NewConfigValidationError(details), "config validation")
}
return variableExtractionResult, nil
}
@@ -345,7 +395,7 @@ func (c Config) validateConfigUpdate(ctx context.Context, moduleId string, confi
return nil
}
return domain.NewConfigValidationError(details)
return errors.WithMessage(domain.NewConfigValidationError(details), "config validation")
}
func (c Config) emitChangeActiveConfigEvent(ctx context.Context, moduleId string) error {
+1 -1
View File
@@ -11,7 +11,7 @@ import (
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
type ConfigHistoryRepo interface {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
type ConfigSchema struct {
+38 -11
View File
@@ -6,12 +6,13 @@ import (
"slices"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"golang.org/x/sync/errgroup"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/helpers"
"isp-config-service/service/module/leader"
)
type ModuleRepo interface {
@@ -58,26 +59,37 @@ func (s Module) Status(ctx context.Context) ([]domain.ModuleInfo, error) {
group.Go(func() error {
var err error
modules, err = s.moduleRepo.All(ctx)
return errors.WithMessage(err, "get all modules")
if err != nil {
return errors.WithMessage(err, "get all modules")
}
return nil
})
group.Go(func() error {
var err error
backends, err = s.backendsRepo.All(ctx)
return errors.WithMessage(err, "get all backends")
if err != nil {
return errors.WithMessage(err, "get all backends")
}
return nil
})
group.Go(func() error {
var err error
schemas, err = s.schemaRepo.All(ctx)
return errors.WithMessage(err, "get all schemas")
if err != nil {
return errors.WithMessage(err, "get all schemas")
}
return nil
})
err := group.Wait()
if err != nil {
return nil, errors.WithMessage(err, "wait")
}
elections := leader.DeriveByModule(backends)
connections := make(map[string][]domain.Connection, len(modules))
for _, backend := range backends {
conn, err := s.backendToDto(backend)
conn, err := s.backendToDto(backend, isModuleLeader(elections, backend))
if err != nil {
return nil, errors.WithMessage(err, "backend to dto")
}
@@ -116,12 +128,18 @@ func (s Module) RequiredModules(ctx context.Context) ([]domain.ModuleRelation, e
group.Go(func() error {
var err error
modules, err = s.moduleRepo.All(groupCtx)
return errors.WithMessage(err, "get all modules")
if err != nil {
return errors.WithMessage(err, "get all modules")
}
return nil
})
group.Go(func() error {
var err error
backends, err = s.backendsRepo.All(groupCtx)
return errors.WithMessage(err, "get all backends")
if err != nil {
return errors.WithMessage(err, "get all backends")
}
return nil
})
err := group.Wait()
if err != nil {
@@ -161,9 +179,11 @@ func (s Module) Connections(ctx context.Context) ([]domain.Connection, error) {
return nil, errors.WithMessage(err, "get all backends")
}
elections := leader.DeriveByModule(backends)
connections := make([]domain.Connection, 0, len(backends))
for _, backend := range backends {
conn, err := s.backendToDto(backend)
conn, err := s.backendToDto(backend, isModuleLeader(elections, backend))
if err != nil {
return nil, errors.WithMessage(err, "backend to dto")
}
@@ -173,7 +193,7 @@ func (s Module) Connections(ctx context.Context) ([]domain.Connection, error) {
return connections, nil
}
func (s Module) backendToDto(backend entity.Backend) (domain.Connection, error) {
func (s Module) backendToDto(backend entity.Backend, moduleLeader bool) (domain.Connection, error) {
addr, err := helpers.SplitAddress(backend)
if err != nil {
return domain.Connection{}, errors.WithMessage(err, "split address")
@@ -205,13 +225,20 @@ func (s Module) backendToDto(backend entity.Backend) (domain.Connection, error)
Ip: addr.IP,
Port: addr.Port,
},
Endpoints: endpointsDescriptors,
EstablishedAt: time.Time(backend.CreatedAt),
IsModuleLeader: moduleLeader,
Endpoints: endpointsDescriptors,
EstablishedAt: time.Time(backend.CreatedAt),
}
return conn, nil
}
func isModuleLeader(elections map[string]leader.Result, backend entity.Backend) bool {
election := elections[backend.ModuleId]
return election.Found && election.Leader.WsConnectionId == backend.WsConnectionId
}
func requiredModuleNamesByModuleId(backends []entity.Backend) map[string]map[string]struct{} {
result := make(map[string]map[string]struct{})
for _, backend := range backends {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"fmt"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity/xtypes"
)
+1 -2
View File
@@ -16,8 +16,7 @@ func NewCompactor() Compactor {
func (c Compactor) Compact(events []entity.Event) []entity.Event {
uniqueEvents := make([]entity.Event, 0, len(events))
uniqueEventKeys := make(map[string]bool, len(events))
for i := len(events) - 1; i >= 0; i-- {
event := events[i]
for _, event := range slices.Backward(events) {
key := event.Key()
if uniqueEventKeys[key] {
continue
+4 -2
View File
@@ -3,7 +3,7 @@ package event
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
)
@@ -33,7 +33,9 @@ func (h Handler) Handle(ctx context.Context, events []entity.Event) {
routingChanged := false
for _, event := range events {
payload := event.Payload.Value
routingChanged = routingChanged || payload.ModuleReady != nil || payload.ModuleDisconnected != nil
routingChanged = routingChanged ||
payload.ModuleReady != nil ||
payload.ModuleDisconnected != nil
err := h.handleEvent(ctx, event)
if err != nil {
h.logger.Error(ctx, errors.WithMessagef(err, "handle event: %s", event.Key()))
+1 -1
View File
@@ -3,7 +3,7 @@ package event
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
+1 -1
View File
@@ -3,7 +3,7 @@ package metrics
import (
"context"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/domain"
"isp-config-service/entity"
)
+175
View File
@@ -0,0 +1,175 @@
package module
import (
"context"
"fmt"
"sort"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/errors"
)
func (s Service) Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error) {
modules, err := s.moduleRepo.All(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get modules")
}
violations := make([]domain.AuditViolation, 0)
for _, module := range modules {
if moduleName != "" && module.Name != moduleName {
continue
}
config, err := s.configRepo.GetActive(ctx, module.Id)
if err != nil {
return nil, errors.WithMessage(err, "get active config")
}
if config == nil {
continue
}
schema, err := s.configSchemaRepo.GetByModuleId(ctx, module.Id)
if err != nil {
return nil, errors.WithMessage(err, "find module schema")
}
schemaData := []byte{}
if schema != nil {
schemaData = schema.Data
}
leaves, err := configLeaves(config.Data)
if err != nil {
return nil, errors.WithMessagef(err, "module [%s]", module.Name)
}
variableTypes, err := s.referencedVariableTypes(ctx, leafVariableNames(leaves))
if err != nil {
return nil, err
}
moduleViolations, err := auditModule(module.Name, schemaData, leaves, variableTypes)
if err != nil {
return nil, errors.WithMessagef(err, "module [%s]", module.Name)
}
violations = append(violations, moduleViolations...)
}
sort.Slice(violations, func(i, j int) bool {
if violations[i].Module != violations[j].Module {
return violations[i].Module < violations[j].Module
}
return violations[i].Path < violations[j].Path
})
return violations, nil
}
func leafVariableNames(leaves map[string][]configLeaf) map[string]struct{} {
names := make(map[string]struct{})
for _, leafs := range leaves {
for _, leaf := range leafs {
for _, name := range leaf.Refs {
names[name] = struct{}{}
}
}
}
return names
}
func auditModule(
moduleName string,
schemaData []byte,
leaves map[string][]configLeaf,
variableTypes map[string]entity.VariableType,
) ([]domain.AuditViolation, error) {
var uiPaths, sensitivePaths []string
if len(schemaData) > 0 {
var err error
uiPaths, err = UIExposedPaths(schemaData)
if err != nil {
return nil, err
}
sensitivePaths, err = SensitivePaths(schemaData)
if err != nil {
return nil, err
}
}
violations := auditUiExposed(moduleName, uiPaths, leaves, variableTypes)
violations = append(violations, auditSensitive(moduleName, sensitivePaths, leaves, variableTypes)...)
return violations, nil
}
func auditUiExposed(
moduleName string,
uiPaths []string,
leaves map[string][]configLeaf,
variableTypes map[string]entity.VariableType,
) []domain.AuditViolation {
violations := make([]domain.AuditViolation, 0)
for _, path := range uiPaths {
seen := make(map[string]struct{})
secretNames := make([]string, 0)
for _, leaf := range leaves[path] {
for _, name := range leaf.Refs {
if variableTypes[name] != entity.SecretType {
continue
}
if _, dup := seen[name]; dup {
continue
}
seen[name] = struct{}{}
secretNames = append(secretNames, name)
}
}
if len(secretNames) == 0 {
continue
}
sort.Strings(secretNames)
violations = append(violations, domain.AuditViolation{
Module: moduleName,
Path: path,
Variables: secretNames,
Reason: "secret variable in ui-exposed field",
})
}
return violations
}
func auditSensitive(
moduleName string,
sensitivePaths []string,
leaves map[string][]configLeaf,
variableTypes map[string]entity.VariableType,
) []domain.AuditViolation {
violations := make([]domain.AuditViolation, 0)
for _, path := range sensitivePaths {
for _, leaf := range leaves[path] {
if leaf.Value == "" {
continue
}
if name, isRef := singleVariableRef(leaf.Value); isRef {
if variableTypes[name] == entity.SecretType {
continue
}
violations = append(violations, domain.AuditViolation{
Module: moduleName,
Path: path,
Variables: []string{name},
Reason: fmt.Sprintf("references non-SECRET variable %s", name),
})
break
}
violations = append(violations, domain.AuditViolation{
Module: moduleName,
Path: path,
Variables: []string{},
Reason: "plain value in sensitive field",
})
break
}
}
return violations
}
+320
View File
@@ -0,0 +1,320 @@
package module
import (
"context"
"encoding/json"
"reflect"
"testing"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/errors"
)
func auditVariables() map[string]entity.VariableType {
return map[string]entity.VariableType{
"s1": entity.SecretType,
"t1": entity.TextType,
}
}
func auditObjectSchema(t *testing.T, properties map[string]any) []byte {
t.Helper()
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": properties,
})
if err != nil {
t.Fatal(err)
}
return schema
}
func auditModuleFixture(t *testing.T, schemaData []byte, configData []byte) []domain.AuditViolation {
t.Helper()
leaves, err := configLeaves(configData)
if err != nil {
t.Fatalf("configLeaves: %v", err)
}
violations, err := auditModule("m1", schemaData, leaves, auditVariables())
if err != nil {
t.Fatalf("auditModule: %v", err)
}
return violations
}
func requireAuditViolations(t *testing.T, got, want []domain.AuditViolation) {
t.Helper()
if !reflect.DeepEqual(got, want) {
t.Fatalf("violations = %v, want %v", got, want)
}
}
func TestAuditModuleIntersection(t *testing.T) {
t.Parallel()
schema := auditObjectSchema(t, map[string]any{
"ui": map[string]any{"type": "string", "x-ui-exposed": true},
"plain": map[string]any{"type": "string"},
})
configData := []byte(`{"ui":"_Var(s1) _Var(t1)","plain":"_Var(s1)"}`)
violations := auditModuleFixture(t, schema, configData)
want := []domain.AuditViolation{{
Module: "m1",
Path: "ui",
Variables: []string{"s1"},
Reason: "secret variable in ui-exposed field",
}}
requireAuditViolations(t, violations, want)
}
func TestAuditModuleSecretOutsideUI(t *testing.T) {
t.Parallel()
schema := auditObjectSchema(t, map[string]any{
"plain": map[string]any{"type": "string"},
})
violations := auditModuleFixture(t, schema, []byte(`{"plain":"_Var(s1)"}`))
if len(violations) != 0 {
t.Fatalf("violations = %v, want none: a secret outside ui-exposed fields is not a violation", violations)
}
}
func TestAuditModuleArrayPath(t *testing.T) {
t.Parallel()
schema := auditObjectSchema(t, map[string]any{
"clients": map[string]any{
"type": "array",
"items": map[string]any{"type": "string", "x-ui-exposed": true},
},
})
configData := []byte(`{"clients":["_Var(s1)","nope"]}`)
violations := auditModuleFixture(t, schema, configData)
want := []domain.AuditViolation{{Module: "m1", Path: "clients.0", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"}}
requireAuditViolations(t, violations, want)
}
func TestAuditModuleCompositeReported(t *testing.T) {
t.Parallel()
schema := auditObjectSchema(t, map[string]any{
"secrets": map[string]any{"type": "string", "x-ui-exposed": true},
})
composite, err := json.Marshal(map[string]any{"a": "_Var(s1)"})
if err != nil {
t.Fatal(err)
}
configData, err := json.Marshal(map[string]any{"secrets": string(composite)})
if err != nil {
t.Fatal(err)
}
violations := auditModuleFixture(t, schema, configData)
want := []domain.AuditViolation{{Module: "m1", Path: "secrets", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"}}
requireAuditViolations(t, violations, want)
}
func TestAuditModuleEmptySchema(t *testing.T) {
t.Parallel()
violations := auditModuleFixture(t, nil, []byte(`{"a":"_Var(s1)"}`))
if len(violations) != 0 {
t.Fatalf("violations = %v, want none: an empty schema exposes no fields", violations)
}
}
func auditSensitiveSchema(t *testing.T) []byte {
t.Helper()
return auditObjectSchema(t, map[string]any{
"token": map[string]any{"type": "string", "x-sensitive": true},
})
}
func TestAuditModuleSensitiveLiteral(t *testing.T) {
t.Parallel()
violations := auditModuleFixture(t, auditSensitiveSchema(t), []byte(`{"token":"legacy-pass-123"}`))
want := []domain.AuditViolation{{
Module: "m1",
Path: "token",
Variables: []string{},
Reason: "plain value in sensitive field",
}}
requireAuditViolations(t, violations, want)
}
func TestAuditModuleSensitiveNonSecretRef(t *testing.T) {
t.Parallel()
violations := auditModuleFixture(t, auditSensitiveSchema(t), []byte(`{"token":"_Var(t1)"}`))
want := []domain.AuditViolation{{
Module: "m1",
Path: "token",
Variables: []string{"t1"},
Reason: "references non-SECRET variable t1",
}}
requireAuditViolations(t, violations, want)
}
func TestAuditModuleSensitiveCompliant(t *testing.T) {
t.Parallel()
for name, config := range map[string]string{
"s1 reference": `{"token":"_Var(s1)"}`,
"empty value": `{"token":""}`,
"absent field": `{}`,
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
violations := auditModuleFixture(t, auditSensitiveSchema(t), []byte(config))
if len(violations) != 0 {
t.Fatalf("violations = %v, want none", violations)
}
})
}
}
func TestAuditModuleBothClasses(t *testing.T) {
t.Parallel()
schema := auditObjectSchema(t, map[string]any{
"secrets": map[string]any{"type": "string", "x-ui-exposed": true},
"token": map[string]any{"type": "string", "x-sensitive": true},
})
configData := []byte(`{"secrets":"_Var(s1)","token":"plain-pass"}`)
violations := auditModuleFixture(t, schema, configData)
want := []domain.AuditViolation{
{Module: "m1", Path: "secrets", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"},
{Module: "m1", Path: "token", Variables: []string{}, Reason: "plain value in sensitive field"},
}
requireAuditViolations(t, violations, want)
}
type auditFakeModuleRepo struct {
modules []entity.Module
}
func (r auditFakeModuleRepo) Upsert(ctx context.Context, module entity.Module) (string, error) {
return "", errors.New("not used in tests")
}
func (r auditFakeModuleRepo) SetDisconnectedAtNow(ctx context.Context, moduleId string) error {
return errors.New("not used in tests")
}
func (r auditFakeModuleRepo) All(ctx context.Context) ([]entity.Module, error) {
return r.modules, nil
}
type auditFakeConfigRepo struct {
active map[string]*entity.Config
}
func (r auditFakeConfigRepo) Insert(ctx context.Context, cfg entity.Config) error {
return errors.New("not used in tests")
}
func (r auditFakeConfigRepo) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
return r.active[moduleId], nil
}
type auditFakeSchemaRepo struct {
schemas map[string]*entity.ConfigSchema
}
func (r auditFakeSchemaRepo) Upsert(ctx context.Context, schema entity.ConfigSchema) error {
return errors.New("not used in tests")
}
func (r auditFakeSchemaRepo) GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) {
return r.schemas[moduleId], nil
}
type auditFakeVariableRepo struct {
variables []entity.Variable
}
func (r auditFakeVariableRepo) GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) {
var result []entity.Variable
for _, variable := range r.variables {
if _, ok := names[variable.Name]; ok {
result = append(result, variable)
}
}
return result, nil
}
func newAuditTestService(
moduleRepo auditFakeModuleRepo,
configRepo auditFakeConfigRepo,
schemaRepo auditFakeSchemaRepo,
variableRepo auditFakeVariableRepo,
) Service {
return NewService(moduleRepo, nil, configRepo, schemaRepo, nil, NewEmitter(nil), nil, variableRepo, false, nil)
}
func TestAuditSkipsModuleWithoutActiveConfig(t *testing.T) {
t.Parallel()
service := newAuditTestService(
auditFakeModuleRepo{modules: []entity.Module{{Id: "id-1", Name: "m1"}}},
auditFakeConfigRepo{active: map[string]*entity.Config{}},
auditFakeSchemaRepo{schemas: map[string]*entity.ConfigSchema{
"id-1": {Id: "schema-1", ModuleId: "id-1", Data: auditSensitiveSchema(t)},
}},
auditFakeVariableRepo{variables: []entity.Variable{{Name: "s1", Type: entity.SecretType}}},
)
violations, err := service.Audit(context.Background(), "")
if err != nil {
t.Fatalf("Audit: %v", err)
}
if len(violations) != 0 {
t.Fatalf("violations = %v, want none: a module without an active config is skipped", violations)
}
}
func TestAuditModuleNameFilter(t *testing.T) {
t.Parallel()
uiSchema := auditObjectSchema(t, map[string]any{
"secrets": map[string]any{"type": "string", "x-ui-exposed": true},
})
service := newAuditTestService(
auditFakeModuleRepo{modules: []entity.Module{
{Id: "id-1", Name: "m1"},
{Id: "id-2", Name: "m2"},
}},
auditFakeConfigRepo{active: map[string]*entity.Config{
"id-1": {Id: "c1", ModuleId: "id-1", Data: []byte(`{"secrets":"_Var(s1)"}`)},
"id-2": {Id: "c2", ModuleId: "id-2", Data: []byte(`{"secrets":"_Var(s1)"}`)},
}},
auditFakeSchemaRepo{schemas: map[string]*entity.ConfigSchema{
"id-1": {Id: "schema-1", ModuleId: "id-1", Data: uiSchema},
"id-2": {Id: "schema-2", ModuleId: "id-2", Data: uiSchema},
}},
auditFakeVariableRepo{variables: []entity.Variable{{Name: "s1", Type: entity.SecretType}}},
)
all, err := service.Audit(context.Background(), "")
if err != nil {
t.Fatalf("Audit: %v", err)
}
if len(all) != 2 {
t.Fatalf("violations = %v, want 2 (one per module)", all)
}
filtered, err := service.Audit(context.Background(), "m1")
if err != nil {
t.Fatalf("Audit: %v", err)
}
if len(filtered) != 1 || filtered[0].Module != "m1" {
t.Fatalf("violations = %v, want the single m1 violation", filtered)
}
absent, err := service.Audit(context.Background(), "m3")
if err != nil {
t.Fatalf("Audit: %v", err)
}
if len(absent) != 0 {
t.Fatalf("violations = %v, want none: unknown module name matches nothing", absent)
}
}
+32 -10
View File
@@ -8,14 +8,14 @@ import (
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type Repo interface {
Insert(ctx context.Context, backend entity.Backend) error
Upsert(ctx context.Context, backend entity.Backend) error
DeleteByWsConnectionIds(ctx context.Context, wsConnIds []string) error
GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error)
DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error)
@@ -79,6 +79,7 @@ func (s Backend) Connect(
LibVersion: declaration.LibVersion,
ModuleName: declaration.ModuleName,
Transport: declaration.Transport,
ModuleLeaderMode: s.normalizeModuleLeaderMode(ctx, declaration.ModuleName, declaration.ModuleLeaderMode),
ConfigServiceNodeId: s.nodeId,
Endpoints: xtypes.Json[[]cluster.EndpointDescriptor]{Value: declaration.Endpoints},
RequiredModules: xtypes.Json[[]cluster.ModuleDependency]{Value: declaration.RequiredModules},
@@ -86,7 +87,7 @@ func (s Backend) Connect(
MetricsAutodiscovery: metricsAd,
}
err := s.backendRepo.Insert(ctx, backend)
err := s.backendRepo.Upsert(ctx, backend)
if err != nil {
return nil, errors.WithMessage(err, "upsert backend in store")
}
@@ -110,7 +111,7 @@ func (s Backend) Disconnect(ctx context.Context, backend entity.Backend) error {
return errors.WithMessage(err, "delete backend in store")
}
err = s.insertDisconnectEvent(ctx, backend.ModuleId)
err = s.insertDisconnectEvent(ctx, backend)
if err != nil {
return errors.WithMessage(err, "insert disconnect event")
}
@@ -125,7 +126,7 @@ func (s Backend) ClearPhantomBackends(ctx context.Context) (int, error) {
}
toDelete := make([]string, 0)
modulesToDisconnect := make(map[string]bool)
phantoms := make(map[string]entity.Backend, len(backends))
for _, backend := range backends {
_, ok := s.rooms.Get(backend.WsConnectionId)
if ok {
@@ -133,7 +134,7 @@ func (s Backend) ClearPhantomBackends(ctx context.Context) (int, error) {
}
toDelete = append(toDelete, backend.WsConnectionId)
modulesToDisconnect[backend.ModuleId] = true
phantoms[backend.ModuleId] = backend
}
if len(toDelete) == 0 {
@@ -145,8 +146,8 @@ func (s Backend) ClearPhantomBackends(ctx context.Context) (int, error) {
return 0, errors.WithMessage(err, "delete backends by ws connection ids")
}
for moduleId := range modulesToDisconnect {
err := s.insertDisconnectEvent(ctx, moduleId)
for _, phantom := range phantoms {
err = s.insertDisconnectEvent(ctx, phantom)
if err != nil {
return 0, errors.WithMessage(err, "insert disconnect event")
}
@@ -164,15 +165,36 @@ func (s Backend) DeleteOwnBackends(ctx context.Context) {
s.logger.Info(ctx, fmt.Sprintf("delete %d own backends", deleted))
}
func (s Backend) insertDisconnectEvent(ctx context.Context, moduleId string) error {
func (s Backend) insertDisconnectEvent(ctx context.Context, backend entity.Backend) error {
event := entity.NewEvent(entity.EventPayload{
ModuleDisconnected: &entity.PayloadModuleDisconnected{
ModuleId: moduleId,
ModuleId: backend.ModuleId,
},
})
err := s.eventRepo.Insert(ctx, event)
if err != nil {
return errors.WithMessage(err, "insert event in store")
}
return nil
}
func (s Backend) normalizeModuleLeaderMode(
ctx context.Context,
moduleName string,
moduleLeaderMode string,
) string {
switch moduleLeaderMode {
case cluster.ModuleLeaderModeNone, cluster.ModuleLeaderModeRequestElection:
return moduleLeaderMode
}
s.logger.Warn(
ctx,
"unsupported module leader mode, stored as none",
log.String("moduleName", moduleName),
log.String("moduleLeaderMode", moduleLeaderMode),
)
return cluster.ModuleLeaderModeNone
}
+1 -1
View File
@@ -4,7 +4,7 @@ import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
+1 -1
View File
@@ -7,8 +7,8 @@ import (
"github.com/txix-open/etp/v4"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
)
+66
View File
@@ -0,0 +1,66 @@
package leader
import (
"slices"
"strings"
"time"
"github.com/txix-open/isp-kit/cluster"
"isp-config-service/entity"
)
type Result struct {
HasElection bool
Found bool
Leader entity.Backend
}
func Derive(backends []entity.Backend) Result {
result := Result{
HasElection: hasElection(backends),
}
if !result.HasElection {
return result
}
candidates := slices.Clone(backends)
slices.SortFunc(candidates, compare)
result.Found = true
result.Leader = candidates[0]
return result
}
func DeriveByModule(backends []entity.Backend) map[string]Result {
byModule := make(map[string][]entity.Backend, len(backends))
for _, backend := range backends {
byModule[backend.ModuleId] = append(byModule[backend.ModuleId], backend)
}
elections := make(map[string]Result, len(byModule))
for moduleId, moduleBackends := range byModule {
elections[moduleId] = Derive(moduleBackends)
}
return elections
}
func hasElection(backends []entity.Backend) bool {
for _, backend := range backends {
if backend.ModuleLeaderMode == cluster.ModuleLeaderModeRequestElection {
return true
}
}
return false
}
func compare(a, b entity.Backend) int {
byCreatedAt := time.Time(a.CreatedAt).Compare(time.Time(b.CreatedAt))
if byCreatedAt != 0 {
return byCreatedAt
}
return strings.Compare(a.WsConnectionId, b.WsConnectionId)
}
+68
View File
@@ -0,0 +1,68 @@
package module
import (
"encoding/json"
"regexp"
"github.com/txix-open/bellows"
"github.com/txix-open/isp-kit/errors"
)
var (
variableRefPattern = regexp.MustCompile(`_Var\((.*?)\)`)
arrayIndexPattern = regexp.MustCompile(`\.\[\d+\]`)
)
type configLeaf struct {
Value string
Refs []string
}
func configLeaves(data []byte) (map[string][]configLeaf, error) {
var root any
err := json.Unmarshal(data, &root)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal config value")
}
leaves := make(map[string][]configLeaf)
for key, value := range bellows.Flatten(root) {
value, ok := value.(string)
if !ok {
continue
}
path := arrayIndexPattern.ReplaceAllString(key, ".0")
leaves[path] = append(leaves[path], configLeaf{
Value: value,
Refs: variableRefs(value),
})
}
return leaves, nil
}
func variableRefs(value string) []string {
matches := variableRefPattern.FindAllStringSubmatch(value, -1)
if len(matches) == 0 {
return nil
}
seen := make(map[string]struct{}, len(matches))
names := make([]string, 0, len(matches))
for _, match := range matches {
name := match[1]
if _, dup := seen[name]; dup {
continue
}
seen[name] = struct{}{}
names = append(names, name)
}
return names
}
func singleVariableRef(value string) (string, bool) {
match := variableRefPattern.FindStringSubmatch(value)
if match == nil || match[0] != value {
return "", false
}
return match[1], true
}
+160
View File
@@ -0,0 +1,160 @@
package module
import (
"encoding/json"
"reflect"
"testing"
)
func singleLeaf(t *testing.T, leaves map[string][]configLeaf, path string) configLeaf {
t.Helper()
atPath := leaves[path]
if len(atPath) != 1 {
t.Fatalf("path %q has %d leaves, want exactly one: %v", path, len(atPath), atPath)
}
return atPath[0]
}
func leafWithValue(t *testing.T, leaves map[string][]configLeaf, path, value string) configLeaf {
t.Helper()
for _, leaf := range leaves[path] {
if leaf.Value == value {
return leaf
}
}
t.Fatalf("no leaf with value %q at path %q: %v", value, path, leaves[path])
return configLeaf{}
}
func TestConfigLeaves(t *testing.T) {
t.Parallel()
data := []byte(`{
"secrets": "_Var(secret_token)",
"plain": "no references here",
"mixed": "prefix/_Var(a) middle _Var(b) _Var(a)",
"list": ["_Var(c)", "nope"],
"nested": {"arr": [{"e": "_Var(d)"}, {"e": "x"}]}
}`)
leaves, err := configLeaves(data)
if err != nil {
t.Fatalf("configLeaves: %v", err)
}
if got := singleLeaf(t, leaves, "secrets").Refs; !reflect.DeepEqual(got, []string{"secret_token"}) {
t.Fatalf("secrets.Refs = %v, want [secret_token]", got)
}
if got := singleLeaf(t, leaves, "mixed").Refs; !reflect.DeepEqual(got, []string{"a", "b"}) {
t.Fatalf("mixed.Refs = %v, want [a b]", got)
}
if got := leafWithValue(t, leaves, "list.0", "_Var(c)").Refs; !reflect.DeepEqual(got, []string{"c"}) {
t.Fatalf("list[c].Refs = %v, want [c]", got)
}
if got := leafWithValue(t, leaves, "list.0", "nope").Refs; got != nil {
t.Fatalf("list[nope].Refs = %v, want nil", got)
}
if got := leafWithValue(t, leaves, "nested.arr.0.e", "_Var(d)").Refs; !reflect.DeepEqual(got, []string{"d"}) {
t.Fatalf("nested.arr.e.Refs = %v, want [d]", got)
}
if len(leaves["nested.arr.0.e"]) != 2 {
t.Fatalf("nested.arr.e = %v, want 2 leaves", leaves["nested.arr.0.e"])
}
if got := singleLeaf(t, leaves, "plain").Refs; got != nil {
t.Fatalf("plain.Refs = %v, want nil", got)
}
if len(leaves) != 5 {
t.Fatalf("expected 5 paths, got %d: %v", len(leaves), leaves)
}
}
func TestConfigLeavesNonStringLeaves(t *testing.T) {
t.Parallel()
leaves, err := configLeaves([]byte(`{"a": 1, "b": null, "c": {"d": []}, "e": "x"}`))
if err != nil {
t.Fatalf("configLeaves: %v", err)
}
if len(leaves) != 1 {
t.Fatalf("leaves = %v, want a single string leaf", leaves)
}
}
func TestConfigLeavesCompositeStrings(t *testing.T) {
t.Parallel()
compositeObj, err := json.Marshal(map[string]any{"a": "_Var(secret_token)"})
if err != nil {
t.Fatalf("marshal composite object: %v", err)
}
compositeArr, err := json.Marshal([]any{"_Var(secret_token)"})
if err != nil {
t.Fatalf("marshal composite array: %v", err)
}
data, err := json.Marshal(map[string]any{
"composite": string(compositeObj),
"compositeList": string(compositeArr),
"plain": "_Var(secret_token)",
"jsonScalar": "42",
})
if err != nil {
t.Fatalf("marshal test data: %v", err)
}
leaves, err := configLeaves(data)
if err != nil {
t.Fatalf("configLeaves: %v", err)
}
for _, path := range []string{"composite", "compositeList", "plain"} {
leaf := singleLeaf(t, leaves, path)
if got := leaf.Refs; !reflect.DeepEqual(got, []string{"secret_token"}) {
t.Fatalf("%s.Refs = %v, want [secret_token]", path, got)
}
if isCompositeJSONString(leaf.Value) != (path != "plain") {
t.Fatalf("%s isComposite = %v, want %v", path, isCompositeJSONString(leaf.Value), path != "plain")
}
}
if leaf := singleLeaf(t, leaves, "jsonScalar"); isCompositeJSONString(leaf.Value) || leaf.Refs != nil {
t.Fatalf("jsonScalar = %+v, want a plain non-composite leaf", leaf)
}
if len(leaves) != 4 {
t.Fatalf("expected 4 paths, got %d: %v", len(leaves), leaves)
}
}
func TestSingleVariableRef(t *testing.T) {
t.Parallel()
tests := map[string]struct {
value string
name string
isRef bool
}{
"single ref": {"_Var(a)", "a", true},
"ref with space": {"_Var(a) ", "", false},
"ref with prefix": {"x_Var(a)", "", false},
"two refs": {"_Var(a) _Var(b)", "", false},
"two refs adjacent": {"_Var(a)_Var(b)", "", false},
"no ref": {"plain value", "", false},
"empty": {"", "", false},
"nested parens": {"_Var(a(b))", "", false},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
t.Parallel()
gotName, gotRef := singleVariableRef(test.value)
if gotRef != test.isRef || gotName != test.name {
t.Fatalf("singleVariableRef(%q) = (%q, %v), want (%q, %v)",
test.value, gotName, gotRef, test.name, test.isRef)
}
})
}
}
+73
View File
@@ -0,0 +1,73 @@
package module
import (
"encoding/json"
"sort"
"github.com/txix-open/isp-kit/errors"
)
const (
uiExposedKeyword = "x-ui-exposed"
sensitiveKeyword = "x-sensitive"
)
func UIExposedPaths(data []byte) ([]string, error) {
return keywordPaths(data, uiExposedKeyword)
}
func SensitivePaths(data []byte) ([]string, error) {
return keywordPaths(data, sensitiveKeyword)
}
func keywordPaths(data []byte, keyword string) ([]string, error) {
var root any
err := json.Unmarshal(data, &root)
if err != nil {
return nil, errors.WithMessage(err, "unmarshal schema")
}
paths := make([]string, 0)
collectTagged(root, "", &paths, keyword)
sort.Strings(paths)
return paths, nil
}
func collectTagged(node any, path string, paths *[]string, keyword string) {
obj, ok := node.(map[string]any)
if !ok {
return
}
if _, marked := obj[keyword]; marked {
p := path
if _, isArray := obj["items"]; isArray {
p = joinPath(path, "0")
}
*paths = append(*paths, p)
return
}
if props, ok := obj["properties"].(map[string]any); ok {
for name, child := range props {
collectTagged(child, joinPath(path, name), paths, keyword)
}
}
switch items := obj["items"].(type) {
case map[string]any:
collectTagged(items, joinPath(path, "0"), paths, keyword)
case []any:
for _, item := range items {
collectTagged(item, joinPath(path, "0"), paths, keyword)
}
}
}
func joinPath(path, name string) string {
if path == "" {
return name
}
return path + "." + name
}
+213
View File
@@ -0,0 +1,213 @@
package module
import (
"encoding/json"
"reflect"
"testing"
)
func rawSchema(t *testing.T, document map[string]any) []byte {
t.Helper()
data, err := json.Marshal(document)
if err != nil {
t.Fatalf("marshal schema: %v", err)
}
return data
}
func stringLeaf(xUiExposed bool) map[string]any {
leaf := map[string]any{"type": "string"}
if xUiExposed {
leaf["x-ui-exposed"] = true
}
return leaf
}
func TestUIExposedPaths(t *testing.T) {
t.Parallel()
schema := rawSchema(t, map[string]any{
"type": "object",
"properties": map[string]any{
"secrets": stringLeaf(true),
"plain": stringLeaf(false),
"extras": stringLeaf(true),
"oauth": map[string]any{
"type": "object",
"properties": map[string]any{
"host": stringLeaf(false),
"clients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"clientId": stringLeaf(true),
"clientSecret": stringLeaf(false),
"setting": map[string]any{
"type": "object",
"properties": map[string]any{
"loginEndpoint": stringLeaf(true),
"logoutEndpoint": stringLeaf(false),
},
},
},
},
},
},
},
},
})
paths, err := UIExposedPaths(schema)
if err != nil {
t.Fatalf("UIExposedPaths: %v", err)
}
want := []string{
"extras",
"oauth.clients.0.clientId",
"oauth.clients.0.setting.loginEndpoint",
"secrets",
}
if !reflect.DeepEqual(paths, want) {
t.Fatalf("paths = %v, want %v", paths, want)
}
}
func TestUIExposedPathsUnmarked(t *testing.T) {
t.Parallel()
schema := rawSchema(t, map[string]any{
"type": "object",
"properties": map[string]any{"value": stringLeaf(false)},
})
paths, err := UIExposedPaths(schema)
if err != nil {
t.Fatalf("UIExposedPaths: %v", err)
}
if len(paths) != 0 {
t.Fatalf("paths = %v, want empty", paths)
}
}
func TestUIExposedPathsStringArray(t *testing.T) {
t.Parallel()
schema := rawSchema(t, map[string]any{
"type": "object",
"properties": map[string]any{
"tags": map[string]any{
"type": "array",
"items": map[string]any{"type": "string"},
"x-ui-exposed": true,
},
},
})
paths, err := UIExposedPaths(schema)
if err != nil {
t.Fatalf("UIExposedPaths: %v", err)
}
want := []string{"tags.0"}
if !reflect.DeepEqual(paths, want) {
t.Fatalf("paths = %v, want %v", paths, want)
}
}
func TestSensitivePaths(t *testing.T) {
t.Parallel()
schema := rawSchema(t, map[string]any{
"type": "object",
"properties": map[string]any{
"token": map[string]any{"type": "string", "x-sensitive": true},
"login": stringLeaf(true),
"tokens": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "x-sensitive": true},
"plain": stringLeaf(false),
"oauth": map[string]any{
"type": "object",
"properties": map[string]any{
"clients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"secret": map[string]any{"type": "string", "x-sensitive": true},
"host": stringLeaf(true),
},
},
},
},
},
},
})
paths, err := SensitivePaths(schema)
if err != nil {
t.Fatalf("SensitivePaths: %v", err)
}
want := []string{
"oauth.clients.0.secret",
"token",
"tokens.0",
}
if !reflect.DeepEqual(paths, want) {
t.Fatalf("paths = %v, want %v", paths, want)
}
}
func TestPathsKeywordIsolation(t *testing.T) {
t.Parallel()
schema := rawSchema(t, map[string]any{
"type": "object",
"properties": map[string]any{
"token": map[string]any{"type": "string", "x-sensitive": true},
"login": stringLeaf(true),
"tokens": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "x-sensitive": true},
"plain": stringLeaf(false),
"oauth": map[string]any{
"type": "object",
"properties": map[string]any{
"clients": map[string]any{
"type": "array",
"items": map[string]any{
"type": "object",
"properties": map[string]any{
"secret": map[string]any{"type": "string", "x-sensitive": true},
"host": stringLeaf(true),
},
},
},
},
},
},
})
uiPaths, err := UIExposedPaths(schema)
if err != nil {
t.Fatalf("UIExposedPaths: %v", err)
}
wantUI := []string{
"login",
"oauth.clients.0.host",
}
if !reflect.DeepEqual(uiPaths, wantUI) {
t.Fatalf("ui-exposed paths = %v, want %v", uiPaths, wantUI)
}
sensitivePaths, err := SensitivePaths(schema)
if err != nil {
t.Fatalf("SensitivePaths: %v", err)
}
wantSensitive := []string{
"oauth.clients.0.secret",
"token",
"tokens.0",
}
if !reflect.DeepEqual(sensitivePaths, wantSensitive) {
t.Fatalf("sensitive paths = %v, want %v", sensitivePaths, wantSensitive)
}
}
+231 -45
View File
@@ -4,18 +4,23 @@ import (
"context"
"crypto/sha256"
"encoding/hex"
"strings"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/store"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
"fmt"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/helpers"
"maps"
"sort"
"strings"
"github.com/txix-open/isp-kit/json"
"github.com/google/uuid"
"github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/store"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
const (
@@ -29,6 +34,7 @@ type Repo interface {
ctx context.Context,
moduleId string,
) error
All(ctx context.Context) ([]entity.Module, error)
}
type BackendService interface {
@@ -38,6 +44,7 @@ type BackendService interface {
type ConfigSchemaRepo interface {
Upsert(ctx context.Context, schema entity.ConfigSchema) error
GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error)
}
type ConfigRepo interface {
@@ -45,8 +52,12 @@ type ConfigRepo interface {
GetActive(ctx context.Context, moduleId string) (*entity.Config, error)
}
type VariableRepo interface {
GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error)
}
type VariableService interface {
RenderConfig(ctx context.Context, input []byte) ([]byte, error)
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error)
ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error)
SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error
}
@@ -65,6 +76,8 @@ type Service struct {
subscriptionService SubscriptionService
emitter Emitter
variableService VariableService
variableRepo VariableRepo
configWriteDeny bool
logger log.Logger
}
@@ -76,6 +89,8 @@ func NewService(
subscriptionService SubscriptionService,
emitter Emitter,
variableService VariableService,
variableRepo VariableRepo,
configWriteDeny bool,
logger log.Logger,
) Service {
return Service{
@@ -86,6 +101,8 @@ func NewService(
subscriptionService: subscriptionService,
emitter: emitter,
variableService: variableService,
variableRepo: variableRepo,
configWriteDeny: configWriteDeny,
logger: logger,
}
}
@@ -212,42 +229,6 @@ func (s Service) OnModuleConfigSchema(
if err != nil {
return errors.WithMessage(err, "get active config")
}
if config == nil {
initialConfig := entity.Config{
Id: idByKey(moduleId),
Name: helpers.ModuleName(conn),
ModuleId: moduleId,
Data: data.Config,
Version: 1,
Active: xtypes.Bool(true),
}
err := s.configRepo.Insert(ctx, initialConfig)
if err != nil {
return errors.WithMessage(err, "insert config in store")
}
result, err := s.variableService.ExtractVariables(ctx, initialConfig.Id, initialConfig.Data)
if err != nil {
return errors.WithMessage(err, "extract and save variable links in store")
}
if len(result.AbsentVariables) > 0 {
return errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ","))
}
err = s.variableService.SaveVariableLinks(ctx, initialConfig.Id, result.VariableLinks)
if err != nil {
return errors.WithMessage(err, "save variable links in store")
}
config = &initialConfig
}
configData, err := s.variableService.RenderConfig(ctx, config.Data)
if err != nil {
return errors.WithMessage(err, "render config")
}
s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, configData)
s.subscriptionService.SubscribeToConfigChanges(conn, moduleId)
configSchema := entity.ConfigSchema{
Id: uuid.NewString(),
@@ -260,6 +241,21 @@ func (s Service) OnModuleConfigSchema(
return errors.WithMessage(err, "upsert config schema in store")
}
if config == nil {
config, err = s.storeInitialConfig(ctx, conn, moduleId, data)
if err != nil {
return err
}
}
configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data)
if err != nil {
return errors.WithMessage(err, "render config")
}
s.emitter.Emit(ctx, conn, cluster.ConfigSendConfigWhenConnected, configData)
s.subscriptionService.SubscribeToConfigChanges(conn, moduleId)
return nil
}
@@ -267,3 +263,193 @@ func idByKey(key string) string {
hash := sha256.Sum256([]byte(key))
return hex.EncodeToString(hash[:])
}
func (s Service) FilterSecretParams(ctx context.Context, config json.RawMessage, moduleId string) error {
if !s.configWriteDeny {
return nil
}
moduleSchema, err := s.configSchemaRepo.GetByModuleId(ctx, moduleId)
if err != nil {
return errors.WithMessage(err, "find module schema")
}
if moduleSchema == nil {
return nil
}
uiPaths, err := UIExposedPaths(moduleSchema.Data)
if err != nil {
return errors.WithMessage(err, "read schema params")
}
sensitivePaths, err := SensitivePaths(moduleSchema.Data)
if err != nil {
return errors.WithMessage(err, "read schema params")
}
if len(uiPaths) == 0 && len(sensitivePaths) == 0 {
return nil
}
leaves, err := configLeaves(config)
if err != nil {
return errors.WithMessage(err, "read config placeholders")
}
variableTypes, err := s.referencedVariableTypes(ctx, policyVariableNames(leaves, uiPaths, sensitivePaths))
if err != nil {
return err
}
errorDetails := uiExposedViolations(leaves, uiPaths, variableTypes)
if len(sensitivePaths) > 0 {
maps.Copy(errorDetails, sensitiveViolations(leaves, sensitivePaths, variableTypes))
}
if len(errorDetails) == 0 {
return nil
}
return errors.WithMessage(domain.NewConfigValidationError(errorDetails), "config violates the secret policy")
}
func (s Service) storeInitialConfig(ctx context.Context, conn *etp.Conn, moduleId string, data cluster.ConfigData) (*entity.Config, error) {
initialConfig := entity.Config{
Id: idByKey(moduleId),
Name: helpers.ModuleName(conn),
ModuleId: moduleId,
Data: data.Config,
Version: 1,
Active: xtypes.Bool(true),
}
result, err := s.variableService.ExtractVariables(ctx, initialConfig.Id, initialConfig.Data)
if err != nil {
return nil, errors.WithMessage(err, "extract variables from initial config")
}
if len(result.AbsentVariables) > 0 {
return nil, errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ","))
}
err = s.configRepo.Insert(ctx, initialConfig)
if err != nil {
return nil, errors.WithMessage(err, "insert config in store")
}
err = s.variableService.SaveVariableLinks(ctx, initialConfig.Id, result.VariableLinks)
if err != nil {
return nil, errors.WithMessage(err, "save variable links in store")
}
return &initialConfig, nil
}
func (s Service) referencedVariableTypes(ctx context.Context, names map[string]struct{}) (map[string]entity.VariableType, error) {
variableTypes := make(map[string]entity.VariableType, len(names))
if len(names) == 0 {
return variableTypes, nil
}
variables, err := s.variableRepo.GetVariablesByName(ctx, names)
if err != nil {
return nil, errors.WithMessage(err, "get variables")
}
for _, variable := range variables {
variableTypes[variable.Name] = variable.Type
}
return variableTypes, nil
}
func policyVariableNames(leaves map[string][]configLeaf, uiPaths, sensitivePaths []string) map[string]struct{} {
names := make(map[string]struct{})
for _, path := range uiPaths {
for _, leaf := range leaves[path] {
for _, name := range leaf.Refs {
names[name] = struct{}{}
}
}
}
for _, path := range sensitivePaths {
for _, leaf := range leaves[path] {
if isCompositeJSONString(leaf.Value) {
continue
}
for _, name := range leaf.Refs {
names[name] = struct{}{}
}
}
}
return names
}
func uiExposedViolations(leaves map[string][]configLeaf, uiPaths []string, variableTypes map[string]entity.VariableType) map[string]string {
details := make(map[string]string)
for _, path := range uiPaths {
seen := make(map[string]struct{})
secrets := make([]string, 0)
for _, leaf := range leaves[path] {
for _, name := range leaf.Refs {
if variableTypes[name] != entity.SecretType {
continue
}
if _, dup := seen[name]; dup {
continue
}
seen[name] = struct{}{}
secrets = append(secrets, name)
}
}
if len(secrets) == 0 {
continue
}
sort.Strings(secrets)
reference := "a variable"
if len(secrets) > 1 {
reference = "variables"
}
message := fmt.Sprintf("UI-exposed field must not reference %s of type SECRET: %s", reference, strings.Join(secrets, ", "))
details[path] = message
}
return details
}
func isCompositeJSONString(value string) bool {
trimmed := strings.TrimLeft(value, " \t\r\n")
if len(trimmed) == 0 {
return false
}
if trimmed[0] != '{' && trimmed[0] != '[' {
return false
}
var node any
err := json.Unmarshal([]byte(trimmed), &node)
if err != nil {
return false
}
switch node.(type) {
case map[string]any, []any:
return true
default:
return false
}
}
func sensitiveViolations(leaves map[string][]configLeaf, sensitivePaths []string, variableTypes map[string]entity.VariableType) map[string]string {
details := make(map[string]string)
for _, path := range sensitivePaths {
for _, leaf := range leaves[path] {
if leaf.Value == "" || isCompositeJSONString(leaf.Value) {
continue
}
if name, ok := singleVariableRef(leaf.Value); ok {
if t, known := variableTypes[name]; known && t != entity.SecretType {
details[path] = fmt.Sprintf("sensitive field must reference only variables of type SECRET: variable %s has type %s", name, t)
break
}
continue
}
details[path] = "plain value in sensitive field"
break
}
}
return details
}
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"strings"
"time"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
// Config represents the configuration as set by command-line flags.
+1 -1
View File
@@ -3,8 +3,8 @@ package rqlite
import (
"bytes"
"github.com/pkg/errors"
"github.com/rqlite/rqlite/v10/auth"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
)
+7 -1
View File
@@ -4,8 +4,8 @@ import (
"context"
"database/sql"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/json"
)
@@ -148,6 +148,12 @@ func (d Adapter) exec(ctx context.Context, inTx bool, requests [][]any) ([]sql.R
results := make([]sql.Result, 0, len(requests))
for _, result := range resp.Results {
// rqlite reports per-statement failures in individual results with HTTP 200,
// and aborts the whole transaction on the first failed statement.
err := catchError(nil, result)
if err != nil {
return nil, errors.WithMessagef(err, "exec transaction on statement: %v", requests[min(len(results), len(requests)-1)])
}
results = append(results, result)
}
+1 -1
View File
@@ -6,8 +6,8 @@ import (
"isp-config-service/repository"
"github.com/pkg/errors"
"github.com/pressly/goose/v3/database"
"github.com/txix-open/isp-kit/errors"
)
type Store struct {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"crypto/x509"
"os"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/errors"
)
// MTLSState indicates whether mutual TLS is enabled or disabled.
+1 -1
View File
@@ -19,7 +19,6 @@ import (
"isp-config-service/service/rqlite/internal/rarchive"
"isp-config-service/service/rqlite/internal/rtls"
"github.com/pkg/errors"
"github.com/rqlite/rqlite-disco-clients/dns"
"github.com/rqlite/rqlite-disco-clients/dnssrv"
"github.com/rqlite/rqlite/v10/auth"
@@ -34,6 +33,7 @@ import (
"github.com/rqlite/rqlite/v10/store"
"github.com/rqlite/rqlite/v10/tcp"
"github.com/txix-open/isp-kit/config"
"github.com/txix-open/isp-kit/errors"
)
const name = `rqlite`
+1 -1
View File
@@ -10,10 +10,10 @@ import (
"github.com/rqlite/rqlite/v10/auth"
"github.com/txix-open/isp-kit/http/httpcli"
"github.com/pkg/errors"
_ "github.com/rqlite/gorqlite/stdlib"
"github.com/rqlite/rqlite/v10/store"
"github.com/txix-open/isp-kit/config"
"github.com/txix-open/isp-kit/errors"
)
var (
+8 -1
View File
@@ -12,12 +12,12 @@ import (
"isp-config-service/service/rqlite/db"
"isp-config-service/service/rqlite/goose_store"
"github.com/pkg/errors"
"github.com/pressly/goose/v3"
"github.com/txix-open/isp-kit/app"
"github.com/txix-open/isp-kit/bootstrap"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/dbx/migration"
"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"
@@ -42,6 +42,7 @@ type Service struct {
// initialized in Run
locatorConfig *assembly.Config
db db.DB
}
func New(boot *bootstrap.Bootstrap) (*Service, error) {
@@ -129,6 +130,7 @@ func (s *Service) Run(ctx context.Context) error {
if err != nil {
return errors.WithMessage(err, "dial to embedded rqlite")
}
s.db = db
cfg := assembly.LocalConfig{
Local: s.cfg,
@@ -209,6 +211,11 @@ func (s *Service) Closers() []app.Closer {
}
}
// nolint:ireturn
func (s *Service) Db() db.DB {
return s.db
}
func (s *Service) leaderStartup(ctx context.Context) error {
db, err := s.rqlite.SqlDB()
if err != nil {
+78 -11
View File
@@ -2,15 +2,18 @@ package subscription
import (
"context"
"slices"
"strings"
"github.com/txix-open/etp/v4"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log"
"isp-config-service/entity"
"isp-config-service/helpers"
"isp-config-service/service/module/leader"
"isp-config-service/service/rqlite/db"
)
@@ -20,7 +23,7 @@ type ModuleRepo interface {
}
type BackendRepo interface {
GetByModuleId(ctx context.Context, moduleId string) ([]entity.Backend, error)
GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error)
All(ctx context.Context) ([]entity.Backend, error)
}
@@ -29,7 +32,7 @@ type ConfigRepo interface {
}
type VariableService interface {
RenderConfig(ctx context.Context, input []byte) ([]byte, error)
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error)
}
type Emitter interface {
@@ -81,7 +84,7 @@ func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error
if err != nil {
return errors.WithMessage(err, "get active config")
}
configData, err := s.variableService.RenderConfig(ctx, config.Data)
configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data)
if err != nil {
return errors.WithMessage(err, "render config")
}
@@ -173,20 +176,48 @@ func (s Service) notifyBackendsChanged(
conns []*etp.Conn,
) error {
ctx = db.NoneConsistency().ToContext(ctx)
backends, err := s.backendRepo.GetByModuleId(ctx, moduleId)
backends, err := s.backendRepo.GetForLeaderElection(ctx, moduleId)
if err != nil {
return errors.WithMessage(err, "get backends by module id")
}
addresses := make([]cluster.AddressConfiguration, 0)
for _, backend := range backends {
addr, err := helpers.SplitAddress(backend)
election := leader.Derive(backends)
if election.HasElection {
return s.emitLeaderAddress(ctx, moduleName, election, conns)
}
addresses, err := moduleAddresses(backends)
if err != nil {
return errors.WithMessage(err, "split address")
}
s.emitModuleConnectedEvent(ctx, conns, moduleName, addresses)
return nil
}
func (s Service) emitLeaderAddress(
ctx context.Context,
moduleName string,
election leader.Result,
conns []*etp.Conn,
) error {
addresses := make([]cluster.AddressConfiguration, 0, 1)
leaderAddress := ""
if election.Found {
address, err := helpers.SplitAddress(election.Leader)
if err != nil {
return errors.WithMessage(err, "split address")
}
addresses = append(addresses, addr)
address.IsModuleLeader = true
addresses = append(addresses, address)
leaderAddress = election.Leader.Address
}
s.logger.Info(ctx, "module address list narrowed to the leader",
log.String("moduleName", moduleName),
log.String("leaderAddress", leaderAddress))
s.emitModuleConnectedEvent(ctx, conns, moduleName, addresses)
return nil
@@ -199,12 +230,25 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
return errors.WithMessage(err, "get all backends")
}
elections := leader.DeriveByModule(backends)
moduleLeaders := make([]string, 0, len(elections))
routingConfig := cluster.RoutingConfig{}
for _, backend := range backends {
addr, err := helpers.SplitAddress(backend)
election := elections[backend.ModuleId]
if election.HasElection && election.Leader.WsConnectionId != backend.WsConnectionId {
continue
}
address, err := helpers.SplitAddress(backend)
if err != nil {
return errors.WithMessage(err, "split address")
}
if election.HasElection {
moduleLeaders = append(moduleLeaders, backend.ModuleName+"="+backend.Address)
}
declaration := cluster.BackendDeclaration{
ModuleName: backend.ModuleName,
Version: backend.Version,
@@ -212,10 +256,20 @@ func (s Service) notifyRoutingChanged(ctx context.Context, event string, conns [
Transport: backend.Transport,
Endpoints: backend.Endpoints.Value,
RequiredModules: backend.RequiredModules.Value,
Address: addr,
Address: cluster.AddressConfiguration{
IP: address.IP,
Port: address.Port,
IsModuleLeader: election.HasElection,
},
}
routingConfig = append(routingConfig, declaration)
}
if len(moduleLeaders) > 0 {
s.logger.Info(ctx, "routing map publishes module leaders",
log.String("moduleLeaders", strings.Join(moduleLeaders, ",")))
}
data, err := json.Marshal(routingConfig)
if err != nil {
return errors.WithMessage(err, "marshal routing config")
@@ -244,3 +298,16 @@ func (s Service) emitModuleConnectedEvent(
}()
}
}
func moduleAddresses(backends []entity.Backend) ([]cluster.AddressConfiguration, error) {
addresses := make([]cluster.AddressConfiguration, 0, len(backends))
for i := range slices.Backward(backends) {
address, err := helpers.SplitAddress(backends[i])
if err != nil {
return nil, errors.WithMessage(err, "split address")
}
addresses = append(addresses, address)
}
return addresses, nil
}
+86
View File
@@ -0,0 +1,86 @@
package variable
import (
"encoding/json"
"regexp"
"strings"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/errors"
)
var (
variableRefPattern = regexp.MustCompile(`_Var\((.*?)\)`)
stringToIntPattern = regexp.MustCompile(`"_ToInt\((\d+)\)"`)
)
type skippedRef struct {
Path string
Variable string
}
func Render(input []byte, uiPaths []string, vars map[string]entity.Variable) ([]byte, []skippedRef, []string, error) {
uiSet := make(map[string]struct{}, len(uiPaths))
for _, path := range uiPaths {
uiSet[path] = struct{}{}
}
skipped := make([]skippedRef, 0)
skippedSeen := make(map[string]struct{})
undefined := make([]string, 0)
substitute := func(path, value string) string {
return variableRefPattern.ReplaceAllStringFunc(value, func(match string) string {
name := variableRefPattern.FindStringSubmatch(match)[1]
variable, ok := vars[name]
if !ok {
undefined = append(undefined, name)
return match
}
_, isUI := uiSet[path]
if variable.Type != entity.SecretType || !isUI {
return variable.Value
}
key := path + "\x00" + name
if _, dup := skippedSeen[key]; !dup {
skippedSeen[key] = struct{}{}
skipped = append(skipped, skippedRef{Path: path, Variable: name})
}
return match
})
}
var root any
err := json.Unmarshal(input, &root)
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "unmarshal config value")
}
var renderLeaves func(node any, path string) any
renderLeaves = func(node any, path string) any {
switch v := node.(type) {
case map[string]any:
for key, child := range v {
v[key] = renderLeaves(child, strings.TrimPrefix(path+"."+key, "."))
}
return v
case []any:
for i, item := range v {
v[i] = renderLeaves(item, strings.TrimPrefix(path+".0", "."))
}
return v
case string:
return substitute(path, v)
}
return node
}
root = renderLeaves(root, "")
out, err := json.Marshal(root)
if err != nil {
return nil, nil, nil, errors.WithMessage(err, "marshal config value")
}
return stringToIntPattern.ReplaceAll(out, []byte("$1")), skipped, undefined, nil
}
+68 -34
View File
@@ -2,14 +2,16 @@ package variable
import (
"context"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/service/module"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log"
)
type Repo interface {
@@ -30,25 +32,31 @@ type EventRepo interface {
Insert(ctx context.Context, event entity.Event) error
}
type SchemaRepo interface {
GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error)
}
type Service struct {
repo Repo
configRepo ConfigRepo
eventRepo EventRepo
stringToIntRegexp *regexp.Regexp
variableRegexp *regexp.Regexp
repo Repo
configRepo ConfigRepo
eventRepo EventRepo
schemaRepo SchemaRepo
logger log.Logger
}
func NewService(
repo Repo,
configRepo ConfigRepo,
eventRepo EventRepo,
schemaRepo SchemaRepo,
logger log.Logger,
) Service {
return Service{
repo: repo,
configRepo: configRepo,
eventRepo: eventRepo,
stringToIntRegexp: regexp.MustCompile(`"_ToInt\((\d+)\)"`),
variableRegexp: regexp.MustCompile(`_Var\((.*?)\)`),
repo: repo,
configRepo: configRepo,
eventRepo: eventRepo,
schemaRepo: schemaRepo,
logger: logger,
}
}
@@ -180,7 +188,7 @@ func (s Service) Delete(ctx context.Context, name string) error {
}
//nolint:funlen
func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) {
func (s Service) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) {
variables, err := s.repo.All(ctx)
if err != nil {
return nil, errors.WithMessage(err, "get all variables")
@@ -188,36 +196,46 @@ func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error)
if len(variables) == 0 {
return input, nil
}
varsMap := make(map[string]string, len(variables))
varsMap := make(map[string]entity.Variable, len(variables))
for _, variable := range variables {
varsMap[variable.Name] = variable.Value
varsMap[variable.Name] = variable
}
undefinedVariables := make([]string, 0)
withReplacedVars := s.variableRegexp.ReplaceAllStringFunc(string(input), func(group string) string {
varName := s.variableRegexp.FindStringSubmatch(group)[1]
value, ok := varsMap[varName]
if !ok {
undefinedVariables = append(undefinedVariables, varName)
return varName
}
return value
})
if len(undefinedVariables) > 0 {
return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefinedVariables, ", "))
uiPaths, err := s.uiPaths(ctx, moduleId)
if err != nil {
return nil, err
}
result := s.stringToIntRegexp.ReplaceAll([]byte(withReplacedVars), []byte("$1"))
out, skipped, undefined, err := Render(input, uiPaths, varsMap)
if err != nil {
return nil, errors.WithMessage(err, "render config")
}
if len(undefined) > 0 {
return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefined, ", "))
}
return result, nil
for _, ref := range skipped {
s.logger.Error(ctx, "secret variable not substituted in ui-exposed field",
log.String("moduleId", moduleId),
log.String("path", ref.Path),
log.String("variable", ref.Variable),
)
}
return out, nil
}
func (s Service) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) {
matches := s.variableRegexp.FindAllStringSubmatch(string(input), -1)
varNames := make([]string, len(matches))
for i, match := range matches {
varNames[i] = match[1]
matches := variableRefPattern.FindAllStringSubmatch(string(input), -1)
seen := make(map[string]bool, len(matches))
varNames := make([]string, 0, len(matches))
for _, match := range matches {
name := match[1]
if seen[name] {
continue
}
seen[name] = true
varNames = append(varNames, name)
}
if len(varNames) == 0 {
return &domain.VariableExtractionResult{
@@ -263,6 +281,22 @@ func (s Service) SaveVariableLinks(ctx context.Context, configId string, links [
return nil
}
func (s Service) uiPaths(ctx context.Context, moduleId string) ([]string, error) {
schemaRow, err := s.schemaRepo.GetByModuleId(ctx, moduleId)
if err != nil {
return nil, errors.WithMessage(err, "find module schema")
}
if schemaRow == nil {
return nil, nil
}
paths, err := module.UIExposedPaths(schemaRow.Data)
if err != nil {
return nil, errors.WithMessage(err, "read ui-exposed paths")
}
return paths, nil
}
func (s Service) toDto(variable entity.Variable, metaByVariables map[string][]entity.ConfigMetaWithVariable) domain.Variable {
value := variable.Value
if variable.Type == "SECRET" {
+42 -2
View File
@@ -11,6 +11,7 @@ import (
"isp-config-service/conf"
"isp-config-service/domain"
"isp-config-service/service/rqlite/db"
"isp-config-service/service/startup"
"github.com/stretchr/testify/require"
@@ -90,6 +91,12 @@ func TestAcceptance(t *testing.T) {
require.EqualValues([]string{"10.2.9.1:9999"}, eventHandler.ReceivedHosts()[1])
require.Len(eventHandler.ReceivedRoutes(), 3)
for _, routes := range eventHandler.ReceivedRoutes() {
for _, declaration := range routes {
require.EqualValues(cluster.ModuleLeaderModeNone, declaration.ModuleLeaderMode)
require.False(declaration.Address.IsModuleLeader)
}
}
statusResponse := make([]domain.ModuleInfo, 0)
err = apiCli.Invoke("config/module/get_modules_info").
@@ -138,6 +145,29 @@ func newClusterClientWith(
defaultRemoteConfig []byte,
metricsAd *cluster.MetricsAutodiscovery,
logger log.Logger,
) *cluster.Client {
t.Helper()
return newClusterClientFull(
t,
moduleName,
host,
config,
defaultRemoteConfig,
metricsAd,
cluster.ModuleLeaderModeNone,
logger,
)
}
func newClusterClientFull(
t *testing.T,
moduleName string,
host string,
config any,
defaultRemoteConfig []byte,
metricsAd *cluster.MetricsAutodiscovery,
moduleLeaderMode string,
logger log.Logger,
) *cluster.Client {
t.Helper()
schema := schema.NewGenerator().Generate(config)
@@ -153,8 +183,9 @@ func newClusterClientWith(
IP: host,
Port: "9999",
},
Endpoints: nil,
EndpointsResolver: cluster.StaticEndpointResolver{},
MetricsAutodiscovery: metricsAd,
ModuleLeaderMode: moduleLeaderMode,
}, cluster.ConfigData{
Version: "1.0.0",
Schema: schemaData,
@@ -168,6 +199,14 @@ func newClusterClientWith(
func setupTest(t *testing.T) log.Logger {
t.Helper()
_, logger, _ := setupTestApp(t)
return logger
}
// nolint:ireturn
func setupTestApp(t *testing.T) (*require.Assertions, log.Logger, db.DB) {
t.Helper()
require := require.New(t)
t.Setenv("APP_CONFIG_PATH", "../conf/config.yml")
@@ -177,6 +216,7 @@ func setupTest(t *testing.T) log.Logger {
dataPath := dataDir(t)
boot.App.Config().Set("rqlite.DataPath", dataPath)
boot.App.Config().Set("backup.Enable", false)
boot.App.Config().Set("configWriteDeny", true)
logger := boot.App.Logger()
startup, err := startup.New(boot)
@@ -191,5 +231,5 @@ func setupTest(t *testing.T) log.Logger {
require.NoError(err)
time.Sleep(1 * time.Second)
return logger
return require, logger, startup.Db()
}
+106
View File
@@ -0,0 +1,106 @@
package tests_test
import (
"testing"
"time"
"isp-config-service/domain"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc/client"
)
type auditUiConfig struct {
Secrets string `schemaGen:"uiExposed"`
Token string `schemaGen:"sensitive"`
Plain string
}
//nolint:funlen,paralleltest
func TestAuditApi(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
err = apiCli.Invoke("config/variable/upsert").
JsonRequestBody([]domain.UpsertVariableRequest{
{Name: "audSecret", Description: "test", Type: "SECRET", Value: "top-secret"},
{Name: "audText", Description: "test", Type: "TEXT", Value: "visible"},
}).
Do(t.Context())
require.NoError(err)
clientA := newClusterClientWith(
t,
"AuditA",
"10.2.9.41",
auditUiConfig{},
[]byte(`{"secrets":"_Var(audSecret)","token":"legacy-pass","plain":"p"}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler()
err := clientA.Run(t.Context(), handler)
require.NoError(err) //nolint:testifylint
}()
clientB := newClusterClientWith(
t,
"AuditB",
"10.2.9.42",
auditUiConfig{},
[]byte(`{"secrets":"_Var(audText)","token":"_Var(audSecret)","plain":"p"}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler()
err := clientB.Run(t.Context(), handler)
_ = err
}()
time.Sleep(3 * time.Second)
var all []domain.AuditViolation
err = apiCli.Invoke("config/config/audit").
JsonRequestBody(domain.AuditRequest{}).
JsonResponseBody(&all).
Do(t.Context())
require.NoError(err)
require.Equal(
[]domain.AuditViolation{
{Module: "AuditA", Path: "secrets", Variables: []string{"audSecret"}, Reason: "secret variable in ui-exposed field"},
{Module: "AuditA", Path: "token", Variables: []string{}, Reason: "plain value in sensitive field"},
},
all,
)
var byName []domain.AuditViolation
err = apiCli.Invoke("config/config/audit").
JsonRequestBody(domain.AuditRequest{ModuleName: "AuditA"}).
JsonResponseBody(&byName).
Do(t.Context())
require.NoError(err)
require.Len(byName, 2)
require.Equal("AuditA", byName[0].Module)
var compliant []domain.AuditViolation
err = apiCli.Invoke("config/config/audit").
JsonRequestBody(domain.AuditRequest{ModuleName: "AuditB"}).
JsonResponseBody(&compliant).
Do(t.Context())
require.NoError(err)
require.Empty(compliant)
var absent []domain.AuditViolation
err = apiCli.Invoke("config/config/audit").
JsonRequestBody(domain.AuditRequest{ModuleName: "Absent"}).
JsonResponseBody(&absent).
Do(t.Context())
require.NoError(err)
require.Empty(absent)
}
+1
View File
@@ -97,6 +97,7 @@ func setupTestWithAppRun(t *testing.T) (*require.Assertions, log.Logger) {
dataPath := dataDir(t)
boot.App.Config().Set("rqlite.DataPath", dataPath)
boot.App.Config().Set("backup.Enable", false)
boot.App.Config().Set("configWriteDeny", true)
logger := boot.App.Logger()
startup, err := startup.New(boot)
+41
View File
@@ -0,0 +1,41 @@
package tests_test
import (
"testing"
"isp-config-service/entity"
"isp-config-service/service/event"
"github.com/stretchr/testify/require"
)
const eventTestModuleId = "test-module-id"
func TestCompactCollapsesModuleLifecycle(t *testing.T) {
t.Parallel()
require := require.New(t)
ready := entity.NewEvent(entity.EventPayload{
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId},
})
ready.Id = 1
disconnected := entity.NewEvent(entity.EventPayload{
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId},
})
disconnected.Id = 2
configUpdated := entity.NewEvent(entity.EventPayload{
ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: eventTestModuleId},
})
configUpdated.Id = 3
require.Equal("module_lifecycle_"+eventTestModuleId, ready.Key())
require.Equal("module_lifecycle_"+eventTestModuleId, disconnected.Key())
require.Equal("config_updated_"+eventTestModuleId, configUpdated.Key())
compacted := event.NewCompactor().Compact([]entity.Event{ready, disconnected, configUpdated})
require.Equal([]entity.Event{disconnected, configUpdated}, compacted,
"the newest lifecycle event wins, a config update is a key of its own")
}
+101
View File
@@ -0,0 +1,101 @@
package tests_test
import (
"context"
"fmt"
"testing"
"isp-config-service/entity"
"isp-config-service/service/event"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/log"
)
type subscriptionSpy struct {
backendsChanged []string
routingCalls int
}
func (s *subscriptionSpy) NotifyConfigChanged(ctx context.Context, moduleId string) error {
return nil
}
func (s *subscriptionSpy) NotifyBackendsChanged(ctx context.Context, moduleId string) error {
s.backendsChanged = append(s.backendsChanged, moduleId)
return nil
}
func (s *subscriptionSpy) NotifyRoutingChanged(ctx context.Context) error {
s.routingCalls++
return nil
}
type eventLoggerSpy struct {
errors []string
}
func (l *eventLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {
l.errors = append(l.errors, fmt.Sprint(message))
}
func (l *eventLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
func (l *eventLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
func (l *eventLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
func moduleReadyEvent(id int) entity.Event {
event := entity.NewEvent(entity.EventPayload{
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId},
})
event.Id = id
return event
}
func moduleDisconnectedEvent(id int) entity.Event {
event := entity.NewEvent(entity.EventPayload{
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId},
})
event.Id = id
return event
}
func TestHandleLifecycleBatchFansRoutingOnce(t *testing.T) {
t.Parallel()
require := require.New(t)
subscription := &subscriptionSpy{}
logger := &eventLoggerSpy{}
handler := event.NewHandler(subscription, logger)
batch := event.NewCompactor().Compact([]entity.Event{
moduleReadyEvent(1),
moduleDisconnectedEvent(2),
})
handler.Handle(t.Context(), batch)
require.Equal([]string{eventTestModuleId}, subscription.backendsChanged,
"ready and disconnected collapse into the newest lifecycle event")
require.Equal(1, subscription.routingCalls, "the routing map is broadcast once per batch")
require.Empty(logger.errors)
}
func TestHandleUnknownEventDoesNotAbortBatch(t *testing.T) {
t.Parallel()
require := require.New(t)
subscription := &subscriptionSpy{}
logger := &eventLoggerSpy{}
handler := event.NewHandler(subscription, logger)
unknown := entity.NewEvent(entity.EventPayload{})
handler.Handle(t.Context(), []entity.Event{unknown, moduleReadyEvent(1)})
require.Len(logger.errors, 1)
require.Contains(logger.errors[0], "unknown event")
require.Equal([]string{eventTestModuleId}, subscription.backendsChanged,
"an unknown payload kind must not stop the batch")
require.Equal(1, subscription.routingCalls)
}
+284
View File
@@ -0,0 +1,284 @@
package tests_test
import (
"context"
"testing"
"isp-config-service/entity"
"isp-config-service/service/module/backend"
"github.com/stretchr/testify/require"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
)
const (
backendTestModuleName = "test-module"
backendTestModuleId = "test-module-id"
testConnId = "test-conn-id"
testNodeId = "test-node-id"
backendLeaderConnId = "conn-1"
backendFollowerConnId = "conn-2"
backendLeaderAddress = "10.0.0.1:9000"
followerAddress = "10.0.0.2:9000"
)
type backendStoredLog struct {
message any
fields map[string]string
}
type backendLoggerSpy struct {
warns []backendStoredLog
}
func (l *backendLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {
entry := backendStoredLog{
message: message,
fields: make(map[string]string, len(fields)),
}
for _, field := range fields {
entry.fields[field.Key] = field.String
}
l.warns = append(l.warns, entry)
}
func (l *backendLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
func (l *backendLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
func (l *backendLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
type backendRepoSpy struct {
upserted []entity.Backend
deleted []string
calls []string
rows map[string]entity.Backend
}
func newBackendRepoSpy(backends ...entity.Backend) *backendRepoSpy {
rows := make(map[string]entity.Backend, len(backends))
for _, backend := range backends {
rows[backend.WsConnectionId] = backend
}
return &backendRepoSpy{rows: rows}
}
func (r *backendRepoSpy) Upsert(ctx context.Context, backend entity.Backend) error {
r.calls = append(r.calls, "upsert")
r.upserted = append(r.upserted, backend)
if r.rows == nil {
r.rows = make(map[string]entity.Backend, 1)
}
r.rows[backend.WsConnectionId] = backend
return nil
}
func (r *backendRepoSpy) DeleteByWsConnectionIds(ctx context.Context, wsConnIds []string) error {
r.calls = append(r.calls, "delete")
r.deleted = append(r.deleted, wsConnIds...)
for _, wsConnId := range wsConnIds {
delete(r.rows, wsConnId)
}
return nil
}
func (r *backendRepoSpy) GetByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) ([]entity.Backend, error) {
r.calls = append(r.calls, "own_node")
ownNode := make([]entity.Backend, 0, len(r.rows))
for _, backend := range r.rows {
ownNode = append(ownNode, backend)
}
return ownNode, nil
}
func (r *backendRepoSpy) DeleteByConfigServiceNodeId(ctx context.Context, configServiceNodeId string) (int, error) {
return 0, nil
}
type eventRepoSpy struct {
inserted []entity.Event
}
func (r *eventRepoSpy) Insert(ctx context.Context, event entity.Event) error {
r.inserted = append(r.inserted, event)
return nil
}
func TestConnectNormalizesModuleLeaderMode(t *testing.T) {
t.Parallel()
tests := []struct {
expectedMode string
announcedMode string
name string
expectedWarn bool
}{
{
name: "request election is stored as is",
announcedMode: cluster.ModuleLeaderModeRequestElection,
expectedMode: cluster.ModuleLeaderModeRequestElection,
},
{
name: "empty mode is stored as empty",
announcedMode: cluster.ModuleLeaderModeNone,
expectedMode: cluster.ModuleLeaderModeNone,
},
{
name: "im leader is reserved",
announcedMode: cluster.ModuleLeaderModeImLeader,
expectedMode: cluster.ModuleLeaderModeNone,
expectedWarn: true,
},
{
name: "im follower is reserved",
announcedMode: cluster.ModuleLeaderModeImFollower,
expectedMode: cluster.ModuleLeaderModeNone,
expectedWarn: true,
},
{
name: "garbage is unknown",
announcedMode: "SOMETHING_ELSE",
expectedMode: cluster.ModuleLeaderModeNone,
expectedWarn: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
require := require.New(t)
logger := &backendLoggerSpy{}
backendRepo := &backendRepoSpy{}
service := backend.NewBackend(backendRepo, &eventRepoSpy{}, testNodeId, nil, logger)
declaration := cluster.BackendDeclaration{
ModuleName: backendTestModuleName,
Version: "1.0.0",
LibVersion: "1.0.0",
Address: cluster.AddressConfiguration{IP: "10.0.0.1", Port: "9000"},
ModuleLeaderMode: tt.announcedMode,
}
connected, err := service.Connect(t.Context(), testConnId, backendTestModuleId, declaration)
require.NoError(err)
require.Len(backendRepo.upserted, 1)
require.Equal(tt.expectedMode, backendRepo.upserted[0].ModuleLeaderMode)
require.Equal(tt.expectedMode, connected.ModuleLeaderMode)
if !tt.expectedWarn {
require.Empty(logger.warns)
return
}
require.Len(logger.warns, 1)
require.Equal(backendTestModuleName, logger.warns[0].fields["moduleName"])
require.Equal(tt.announcedMode, logger.warns[0].fields["moduleLeaderMode"])
})
}
}
func TestConnectInsertsOnlyLifecycleEvent(t *testing.T) {
t.Parallel()
require := require.New(t)
events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy(backendElectedInstance(backendLeaderConnId, backendLeaderAddress))
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{})
declaration := cluster.BackendDeclaration{
ModuleName: backendTestModuleName,
Address: cluster.AddressConfiguration{IP: "10.0.0.2", Port: "9000"},
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
}
_, err := service.Connect(t.Context(), backendFollowerConnId, backendTestModuleId, declaration)
require.NoError(err)
require.Equal([]string{"upsert"}, backendRepo.calls,
"the connect path elects nobody: the leader is derived where the address list is emitted")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events),
"one lifecycle event per connect, no dedicated leader event")
}
func TestDisconnectInsertsOnlyLifecycleEvent(t *testing.T) {
t.Parallel()
require := require.New(t)
events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy(
backendElectedInstance(backendLeaderConnId, backendLeaderAddress),
backendElectedInstance(backendFollowerConnId, followerAddress),
)
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{})
err := service.Disconnect(t.Context(), entity.Backend{
WsConnectionId: backendLeaderConnId,
ModuleId: backendTestModuleId,
ModuleName: backendTestModuleName,
})
require.NoError(err)
require.Equal([]string{"delete"}, backendRepo.calls,
"the disconnect path elects nobody")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events),
"one lifecycle event per disconnect, no dedicated leader event")
}
func TestClearPhantomBackendsInsertsOneLifecycleEventPerModule(t *testing.T) {
t.Parallel()
require := require.New(t)
events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy(
backendElectedInstance(backendLeaderConnId, backendLeaderAddress),
backendElectedInstance(backendFollowerConnId, followerAddress),
)
service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &backendLoggerSpy{})
deleted, err := service.ClearPhantomBackends(t.Context())
require.NoError(err)
require.Equal(2, deleted)
require.Equal([]string{"own_node", "delete"}, backendRepo.calls,
"the cleanup deletes and announces, it elects nobody")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events),
"the instances of one module are announced once")
}
func TestDeleteOwnBackendsInsertsNoEvents(t *testing.T) {
t.Parallel()
require := require.New(t)
events := &eventRepoSpy{}
service := backend.NewBackend(newBackendRepoSpy(), events, testNodeId, nil, &backendLoggerSpy{})
service.DeleteOwnBackends(t.Context())
require.Empty(events.inserted, "graceful shutdown inserts no events at all")
}
func backendElectedInstance(connId string, address string) entity.Backend {
return entity.Backend{
WsConnectionId: connId,
ModuleId: backendTestModuleId,
ModuleName: backendTestModuleName,
Address: address,
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
}
}
func eventKeys(events *eventRepoSpy) []string {
keys := make([]string, 0, len(events.inserted))
for _, event := range events.inserted {
keys = append(keys, event.Key())
}
return keys
}
+213
View File
@@ -0,0 +1,213 @@
package tests_test
import (
"context"
"net"
"slices"
"testing"
"isp-config-service/domain"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc/client"
)
const (
apiObserverModule = "apiobserver"
apiObserverIP = "10.2.9.20"
apiSilentModule = "apisilent"
apiSilentHost = "10.2.9.21"
modulesInfoEndpoint = "config/module/get_modules_info"
routesEndpoint = "config/routing/get_routes"
)
//nolint:funlen,paralleltest
func TestModuleLeaderApiFlag(t *testing.T) {
require, logger, testDb := setupTestApp(t)
ctx := t.Context()
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
observer := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, apiObserverModule, apiObserverIP, logger),
cluster.NewEventHandler().RequireModule(electionModule, observer).RoutesReceiver(observer),
)
instances := []moduleInstance{
startModuleInstance(t, electionModule, electionHostOne, cluster.ModuleLeaderModeRequestElection, logger),
startModuleInstance(t, electionModule, electionHostTwo, cluster.ModuleLeaderModeRequestElection, logger),
startModuleInstance(t, electionModule, electionHostThree, cluster.ModuleLeaderModeRequestElection, logger),
startModuleInstance(t, plainModule, plainHostOne, cluster.ModuleLeaderModeNone, logger),
startModuleInstance(t, plainModule, plainHostTwo, cluster.ModuleLeaderModeNone, logger),
startModuleInstance(t, apiSilentModule, apiSilentHost, cluster.ModuleLeaderModeNone, logger),
}
byHost := make(map[string]moduleInstance, len(instances))
for _, instance := range instances {
byHost[instance.host] = instance
}
connected := map[string]int{electionModule: 3, plainModule: 2, apiSilentModule: 1}
require.Eventually(func() bool {
return len(selectLeaderOrder(ctx, testDb, electionModule)) == 3 &&
len(selectLeaderOrder(ctx, testDb, plainModule)) == 2 &&
len(selectLeaderOrder(ctx, testDb, apiSilentModule)) == 1
}, announceTimeout, announceTick, "every instance must be connected")
elected := selectLeaderOrder(ctx, testDb, electionModule)
derivedLeader := elected[0].Address
require.Eventually(func() bool {
return slices.Equal(lastHosts(observer), []string{derivedLeader})
}, announceTimeout, announceTick, "the subscriber must be balanced to the derived leader")
observedLeader := lastHosts(observer)[0]
status := requireApiCounts(t, ctx, apiCli, modulesInfoEndpoint, instanceCount, connected)
electionInfo := findModule(status, electionModule)
require.NotNil(electionInfo, electionModule)
require.True(electionInfo.Active)
require.Len(electionInfo.Status, 3, "modules info must keep every instance of the elected module")
apiLeader := requireSingleLeader(require, electionInfo.Status)
require.Equal(derivedLeader, apiLeader, "the leader of the API must be the leader derived from the DB")
require.Equal(observedLeader, apiLeader, "the leader of the API must be the address the subscriber receives")
requireNoLeaders(require, connectionsOf(status, plainModule), plainModule)
requireNoLeaders(require, connectionsOf(status, apiSilentModule), apiSilentModule)
routes := requireApiCounts(t, ctx, apiCli, routesEndpoint, connectionCount, connected)
require.Len(connectionsOfModule(routes, electionModule), 3, "routes must not narrow the elected module")
require.Equal(apiLeader, requireSingleLeader(require, connectionsOfModule(routes, electionModule)),
"routes must mark the same leader as modules info")
requireNoLeaders(require, connectionsOfModule(routes, plainModule), plainModule)
byHost[apiSilentHost].disconnect(t)
byHost[hostOf(t, elected[1].Address)].disconnect(t)
byHost[hostOf(t, elected[2].Address)].disconnect(t)
status = requireApiCounts(t, ctx, apiCli, modulesInfoEndpoint, instanceCount, map[string]int{
electionModule: 1,
plainModule: 2,
apiSilentModule: 0,
})
silentInfo := findModule(status, apiSilentModule)
require.NotNil(silentInfo, apiSilentModule)
require.False(silentInfo.Active)
require.Empty(silentInfo.Status, "a module without instances has no connection to mark")
electionInfo = findModule(status, electionModule)
require.NotNil(electionInfo, electionModule)
require.True(electionInfo.Active)
require.Len(electionInfo.Status, 1)
require.True(electionInfo.Status[0].IsModuleLeader, "the only instance of an elected module is its leader")
require.Equal(derivedLeader, connectionAddress(electionInfo.Status[0]),
"dropping standbys must not move leadership")
}
func connectionsOf(modules []domain.ModuleInfo, moduleName string) []domain.Connection {
for _, module := range modules {
if module.Name == moduleName {
return module.Status
}
}
return nil
}
func connectionsOfModule(connections []domain.Connection, moduleName string) []domain.Connection {
ofModule := make([]domain.Connection, 0, len(connections))
for _, connection := range connections {
if connection.ModuleName == moduleName {
ofModule = append(ofModule, connection)
}
}
return ofModule
}
func connectionAddress(connection domain.Connection) string {
return net.JoinHostPort(connection.Address.Ip, connection.Address.Port)
}
func requireSingleLeader(require *require.Assertions, connections []domain.Connection) string {
leaders := make([]string, 0, 1)
for _, connection := range connections {
if connection.IsModuleLeader {
leaders = append(leaders, connectionAddress(connection))
}
}
require.Len(leaders, 1, "an elected module must expose exactly one leader")
return leaders[0]
}
func requireNoLeaders(require *require.Assertions, connections []domain.Connection, moduleName string) {
require.NotEmpty(connections, moduleName)
for _, connection := range connections {
require.False(connection.IsModuleLeader, "a module without election must not expose a leader: "+moduleName)
}
}
func instanceCount(module domain.ModuleInfo) map[string]int {
return map[string]int{module.Name: len(module.Status)}
}
func connectionCount(connection domain.Connection) map[string]int {
return map[string]int{connection.ModuleName: 1}
}
func requireApiCounts[T any](
t *testing.T,
ctx context.Context,
apiCli *client.Client,
endpoint string,
countsOf func(row T) map[string]int,
expected map[string]int,
) []T {
t.Helper()
require := require.New(t)
rows := make([]T, 0)
require.Eventually(func() bool {
latest := make([]T, 0)
err := apiCli.Invoke(endpoint).JsonResponseBody(&latest).Do(ctx)
if err != nil {
return false
}
rows = latest
return countsMatch(countsByModule(rows, countsOf), expected)
}, announceTimeout, announceTick, endpoint+" must report every instance")
return rows
}
func countsByModule[T any](rows []T, countsOf func(row T) map[string]int) map[string]int {
counts := make(map[string]int, len(rows))
for _, row := range rows {
for moduleName, total := range countsOf(row) {
counts[moduleName] += total
}
}
return counts
}
func countsMatch(counts, expected map[string]int) bool {
for moduleName, total := range expected {
if counts[moduleName] != total {
return false
}
}
return true
}
+349
View File
@@ -0,0 +1,349 @@
package tests_test
import (
"context"
"net"
"slices"
"strings"
"testing"
"isp-config-service/service/rqlite/db"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
)
const (
electionHostOne = "10.2.9.1"
electionHostTwo = "10.2.9.2"
electionHostThree = "10.2.9.3"
plainModule = "plain"
plainHostOne = "10.2.9.7"
plainHostTwo = "10.2.9.8"
plainObserverModule = "plainobserver"
plainObserverIP = "10.2.9.10"
electionObserverModule = "electionobserver"
electionObserverIP = "10.2.9.9"
lateObserverModule = "lateobserver"
lateObserverIP = "10.2.9.11"
noLeaderModule = "noleader"
noLeaderHostOne = "10.2.9.12"
noLeaderHostTwo = "10.2.9.13"
noLeaderObserverIP = "10.2.9.14"
noLeaderObserverName = "noleaderobserver"
instancePort = "9999"
)
// nolint:tagliatelle
type leaderOrderRow struct {
WsConnectionId string `json:"ws_connection_id"`
Address string `json:"address"`
}
// nolint:tagliatelle
type schemaNameRow struct {
Name string `json:"name"`
}
type moduleInstance struct {
host string
cli *cluster.Client
cancel context.CancelFunc
}
//nolint:funlen,paralleltest
func TestModuleLeaderElection(t *testing.T) {
require, logger, testDb := setupTestApp(t)
ctx := t.Context()
electionObserver := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, electionObserverModule, electionObserverIP, logger),
cluster.NewEventHandler().RequireModule(electionModule, electionObserver).RoutesReceiver(electionObserver),
)
plainObserver := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, plainObserverModule, plainObserverIP, logger),
cluster.NewEventHandler().RequireModule(plainModule, plainObserver).RoutesReceiver(plainObserver),
)
electedInstances := []moduleInstance{
startModuleInstance(t, electionModule, electionHostOne, cluster.ModuleLeaderModeRequestElection, logger),
startModuleInstance(t, electionModule, electionHostTwo, cluster.ModuleLeaderModeRequestElection, logger),
startModuleInstance(t, electionModule, electionHostThree, cluster.ModuleLeaderModeRequestElection, logger),
}
byHost := make(map[string]moduleInstance, len(electedInstances))
for _, instance := range electedInstances {
byHost[instance.host] = instance
}
startModuleInstance(t, plainModule, plainHostOne, cluster.ModuleLeaderModeNone, logger)
startModuleInstance(t, plainModule, plainHostTwo, cluster.ModuleLeaderModeNone, logger)
announced := []string{addressOf(electionHostOne), addressOf(electionHostTwo), addressOf(electionHostThree)}
require.Eventually(func() bool {
return len(selectLeaderOrder(ctx, testDb, electionModule)) == 3
}, announceTimeout, announceTick, "all three instances of %s must be connected", electionModule)
elected := selectLeaderOrder(ctx, testDb, electionModule)
expectedLeader := elected[0].Address
expectedSuccessor := elected[1].Address
require.Eventually(func() bool {
return slices.Equal(lastHosts(electionObserver), []string{expectedLeader})
}, announceTimeout, announceTick, "the address list of an elected module must keep exactly the derived leader")
received := lastHosts(electionObserver)
require.Len(received, 1, "an elected module must be balanced to a single address")
require.Contains(announced, received[0], "the leader must be one of the announced instances")
require.Eventually(func() bool {
return routingLeaderOf(electionObserver, electionModule) == expectedLeader
}, announceTimeout, announceTick, "the routing map of an elected module must publish only the leader")
requireRoutingLeader(require, lastRoutesOf(electionObserver, electionModule), expectedLeader)
require.Eventually(func() bool {
return len(lastRoutesOf(electionObserver, plainModule)) == 2
}, announceTimeout, announceTick, "a module without election must publish every instance")
requireRoutingUntouched(require, lastRoutesOf(electionObserver, plainModule), plainHosts())
lateObserver := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, lateObserverModule, lateObserverIP, logger),
cluster.NewEventHandler().RequireModule(electionModule, lateObserver).RoutesReceiver(lateObserver),
)
require.Eventually(func() bool {
return slices.Equal(lastHosts(lateObserver), []string{expectedLeader}) &&
routingLeaderOf(lateObserver, electionModule) == expectedLeader
}, announceTimeout, announceTick, "a subscriber connected after the election must see the same leader")
requireRoutingLeader(require, lastRoutesOf(lateObserver, electionModule), expectedLeader)
standbySnapshots := len(electionObserver.ReceivedHosts())
byHost[hostOf(t, elected[2].Address)].disconnect(t)
require.Eventually(func() bool {
return len(electionObserver.ReceivedHosts()) > standbySnapshots
}, announceTimeout, announceTick, "disconnecting a standby must re-emit the address list")
require.Equal([]string{expectedLeader}, lastHosts(electionObserver),
"disconnecting a standby must not move leadership")
leaderSnapshots := len(electionObserver.ReceivedHosts())
byHost[hostOf(t, expectedLeader)].disconnect(t)
require.Eventually(func() bool {
return slices.Equal(lastHosts(electionObserver), []string{expectedSuccessor})
}, announceTimeout, announceTick, "disconnecting the leader must move leadership to the next one in derivation order")
require.Equal(expectedSuccessor, selectLeaderOrder(ctx, testDb, electionModule)[0].Address)
requireRoutingLeader(require, lastRoutesOf(electionObserver, electionModule), expectedSuccessor)
require.Greater(len(electionObserver.ReceivedHosts()), leaderSnapshots,
"disconnecting the leader must re-emit the address list")
lastSnapshots := len(electionObserver.ReceivedHosts())
byHost[hostOf(t, expectedSuccessor)].disconnect(t)
require.Eventually(func() bool {
return len(electionObserver.ReceivedHosts()) > lastSnapshots
}, announceTimeout, announceTick, "disconnecting the last instance must re-emit the address list")
require.Empty(lastHosts(electionObserver), "with no instances left the subscriber must receive an empty list")
require.Empty(selectLeaderOrder(ctx, testDb, electionModule))
require.Eventually(func() bool {
return slices.Equal(lastHosts(plainObserver), selectEmittedAddresses(ctx, testDb, plainModule))
}, announceTimeout, announceTick, "a module without election keeps its newest-first address list")
requireRoutingUntouched(require, lastRoutesOf(plainObserver, plainModule), plainHosts())
requireNoLeaderState(t, testDb)
}
//nolint:paralleltest
func TestModuleLeaderElectionWithoutLeader(t *testing.T) {
require, logger, testDb := setupTestApp(t)
ctx := t.Context()
observer := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, noLeaderObserverName, noLeaderObserverIP, logger),
cluster.NewEventHandler().RequireModule(noLeaderModule, observer).RoutesReceiver(observer),
)
byHost := map[string]moduleInstance{
noLeaderHostOne: startModuleInstance(t, noLeaderModule, noLeaderHostOne, cluster.ModuleLeaderModeRequestElection, logger),
noLeaderHostTwo: startModuleInstance(t, noLeaderModule, noLeaderHostTwo, cluster.ModuleLeaderModeRequestElection, logger),
}
require.Eventually(func() bool {
return len(selectLeaderOrder(ctx, testDb, noLeaderModule)) == 2
}, announceTimeout, announceTick, "both instances of %s must be connected", noLeaderModule)
order := selectLeaderOrder(ctx, testDb, noLeaderModule)
require.Eventually(func() bool {
return slices.Equal(lastHosts(observer), []string{order[0].Address})
}, announceTimeout, announceTick, "the leader address must be the only published address")
requireRoutingLeader(require, lastRoutesOf(observer, noLeaderModule), order[0].Address)
byHost[hostOf(t, order[0].Address)].disconnect(t)
var remaining []leaderOrderRow
require.Eventually(func() bool {
remaining = selectLeaderOrder(ctx, testDb, noLeaderModule)
return len(remaining) == 1 && slices.Equal(lastHosts(observer), []string{remaining[0].Address})
}, announceTimeout, announceTick, "leadership must move to the remaining instance")
snapshots := len(observer.ReceivedHosts())
byHost[hostOf(t, remaining[0].Address)].disconnect(t)
require.Eventually(func() bool {
return len(observer.ReceivedHosts()) > snapshots && len(lastHosts(observer)) == 0
}, announceTimeout, announceTick, "with no instances left the subscriber must receive an empty address list")
require.Empty(lastHosts(observer), "the client must receive an empty list, not the previous address")
require.Empty(selectLeaderOrder(ctx, testDb, noLeaderModule))
require.Empty(lastRoutesOf(observer, noLeaderModule), "a module without instances publishes no declaration")
}
func startModuleInstance(
t *testing.T,
moduleName string,
host string,
moduleLeaderMode string,
logger log.Logger,
) moduleInstance {
t.Helper()
cli := newClusterClientFull(t, moduleName, host, testModuleRemoteConfig{}, []byte("{}"), nil, moduleLeaderMode, logger)
ctx, cancel := context.WithCancel(t.Context())
runClusterClient(ctx, require.New(t), cli, cluster.NewEventHandler())
return moduleInstance{host: host, cli: cli, cancel: cancel}
}
func (i moduleInstance) disconnect(t *testing.T) {
t.Helper()
i.cancel()
require.NoError(t, i.cli.Close())
}
func addressOf(host string) string {
return net.JoinHostPort(host, instancePort)
}
func hostOf(t *testing.T, address string) string {
t.Helper()
host, _, err := net.SplitHostPort(address)
require.New(t).NoError(err)
return host
}
func plainHosts() []string {
return []string{addressOf(plainHostOne), addressOf(plainHostTwo)}
}
func lastHosts(handler *clusterEventHandler) []string {
snapshots := handler.ReceivedHosts()
if len(snapshots) == 0 {
return nil
}
return snapshots[len(snapshots)-1]
}
func lastRoutesOf(handler *clusterEventHandler, moduleName string) []cluster.BackendDeclaration {
snapshots := handler.ReceivedRoutes()
if len(snapshots) == 0 {
return nil
}
declarations := make([]cluster.BackendDeclaration, 0)
for _, declaration := range snapshots[len(snapshots)-1] {
if declaration.ModuleName == moduleName {
declarations = append(declarations, declaration)
}
}
return declarations
}
func routingLeaderOf(handler *clusterEventHandler, moduleName string) string {
declarations := lastRoutesOf(handler, moduleName)
if len(declarations) != 1 || !declarations[0].Address.IsModuleLeader {
return ""
}
return addressOf(declarations[0].Address.IP)
}
func requireRoutingLeader(require *require.Assertions, declarations []cluster.BackendDeclaration, leaderAddress string) {
require.Len(declarations, 1, "the routing map of an elected module must publish only the leader")
require.Equal(leaderAddress, addressOf(declarations[0].Address.IP))
require.True(declarations[0].Address.IsModuleLeader, "the leader declaration must carry the leader flag")
}
func requireRoutingUntouched(require *require.Assertions, declarations []cluster.BackendDeclaration, announced []string) {
require.Len(declarations, len(announced), "a module without election must publish every instance")
addresses := make([]string, 0, len(declarations))
for _, declaration := range declarations {
require.False(declaration.Address.IsModuleLeader)
addresses = append(addresses, addressOf(declaration.Address.IP))
}
require.ElementsMatch(announced, addresses)
}
func selectLeaderOrder(ctx context.Context, testDb db.DB, moduleName string) []leaderOrderRow {
rows := make([]leaderOrderRow, 0)
_ = testDb.Select(ctx, &rows, `
select ws_connection_id, address
from isp_config_service__backend
where module_name = ?
order by created_at asc, ws_connection_id asc`, moduleName)
return rows
}
func selectEmittedAddresses(ctx context.Context, testDb db.DB, moduleName string) []string {
rows := selectLeaderOrder(ctx, testDb, moduleName)
addresses := make([]string, 0, len(rows))
for i := range slices.Backward(rows) {
addresses = append(addresses, rows[i].Address)
}
return addresses
}
func requireNoLeaderState(t *testing.T, testDb db.DB) {
t.Helper()
require := require.New(t)
columns := make([]schemaNameRow, 0)
err := testDb.Select(t.Context(), &columns, `pragma table_info('isp_config_service__backend')`)
require.NoError(err)
leaderColumns := make([]string, 0)
for _, column := range columns {
if strings.Contains(strings.ToLower(column.Name), "leader") {
leaderColumns = append(leaderColumns, column.Name)
}
}
require.Equal([]string{"module_leader_mode"}, leaderColumns,
"only the announced mode is stored, the derived leader never is")
objects := make([]schemaNameRow, 0)
err = testDb.Select(t.Context(), &objects, `
select name from sqlite_master
where lower(name) like '%leader%' and type in ('table','view','index','trigger')`)
require.NoError(err)
require.Empty(objects, "leader election must not add a table, view, index, or trigger")
}
+281
View File
@@ -0,0 +1,281 @@
package tests_test
import (
"context"
"slices"
"testing"
"time"
"isp-config-service/domain"
"isp-config-service/service/rqlite/db"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/log"
)
const (
electionModule = "election"
noneModule = "none"
leaderModule = "imleader"
followerModule = "imfollower"
garbageModule = "garbage"
observerModule = "observer"
garbageLeaderMode = "SOMETHING_ELSE"
announceTimeout = 20 * time.Second
announceTick = 200 * time.Millisecond
)
// nolint:tagliatelle
type backendRow struct {
WsConnectionId string `json:"ws_connection_id"`
CreatedAt int64 `json:"created_at"`
ModuleLeaderMode *string `json:"module_leader_mode"`
}
// nolint:tagliatelle
type backendCountRow struct {
Total int `json:"total"`
}
// nolint:tagliatelle
type epochAdvancedRow struct {
Advanced int `json:"advanced"`
}
func (r backendRow) moduleLeaderMode() string {
if r.ModuleLeaderMode == nil {
return "null"
}
return *r.ModuleLeaderMode
}
//nolint:funlen,paralleltest
func TestModuleLeaderMode(t *testing.T) {
require, logger, testDb := setupTestApp(t)
ctx := t.Context()
routes := newClusterEventHandler()
runClusterClient(ctx, require,
newClusterClient(t, observerModule, "10.2.9.9", logger),
cluster.NewEventHandler().RoutesReceiver(routes),
)
electionCli := newClusterClientWithLeaderMode(t, electionModule, "10.2.9.1", cluster.ModuleLeaderModeRequestElection, logger)
runClusterClient(ctx, require, electionCli, cluster.NewEventHandler())
noneCli := newClusterClient(t, noneModule, "10.2.9.2", logger)
runClusterClient(ctx, require, noneCli, cluster.NewEventHandler())
leaderCli := newClusterClientWithLeaderMode(t, leaderModule, "10.2.9.3", cluster.ModuleLeaderModeImLeader, logger)
runClusterClient(ctx, require, leaderCli, cluster.NewEventHandler())
followerCli := newClusterClientWithLeaderMode(t, followerModule, "10.2.9.4", cluster.ModuleLeaderModeImFollower, logger)
runClusterClient(ctx, require, followerCli, cluster.NewEventHandler())
garbageCli := newClusterClientWithLeaderMode(t, garbageModule, "10.2.9.5", garbageLeaderMode, logger)
runClusterClient(ctx, require, garbageCli, cluster.NewEventHandler())
electionRow := requireBackendRow(t, testDb, electionModule)
require.Equal(cluster.ModuleLeaderModeRequestElection, electionRow.moduleLeaderMode())
noneRow := requireBackendRow(t, testDb, noneModule)
require.NotNil(noneRow.ModuleLeaderMode, "mode announced as empty must be stored as empty string")
require.Equal(cluster.ModuleLeaderModeNone, noneRow.moduleLeaderMode())
t.Logf("rqlite returns module_leader_mode of %s as %q", noneModule, noneRow.moduleLeaderMode())
reserved := []struct {
moduleName string
cli *cluster.Client
}{
{moduleName: leaderModule, cli: leaderCli},
{moduleName: followerModule, cli: followerCli},
{moduleName: garbageModule, cli: garbageCli},
}
for _, instance := range reserved {
row := requireBackendRow(t, testDb, instance.moduleName)
require.NotNil(row.ModuleLeaderMode, "reserved mode must be stored as empty string")
require.Equal(cluster.ModuleLeaderModeNone, row.moduleLeaderMode(), instance.moduleName)
require.Eventually(func() bool {
return instance.cli.Healthcheck(ctx) == nil
}, announceTimeout, announceTick, "handshake of %s must not be rejected", instance.moduleName)
}
requireAcceptedModules(require, ctx, leaderModule, followerModule, garbageModule)
for _, routing := range requireReceivedRoutes(require, routes) {
for _, declaration := range routing {
// electionModule declared REQUEST_ELECTION: its leader is published with the leader flag set.
if declaration.ModuleName == electionModule {
continue
}
require.False(declaration.Address.IsModuleLeader)
require.Equal(cluster.ModuleLeaderModeNone, declaration.ModuleLeaderMode)
}
}
require.Eventually(func() bool {
return backendCreatedAtPassed(t, testDb, electionModule)
}, announceTimeout, announceTick, "created_at must be older than now to detect a move")
beforeReannounce, err := selectBackendRow(t, testDb, electionModule)
require.NoError(err)
err = electionCli.SendModuleReady(ctx)
require.NoError(err)
reannouncedRow, err := selectBackendRow(t, testDb, electionModule)
require.NoError(err)
require.Equal(beforeReannounce.WsConnectionId, reannouncedRow.WsConnectionId)
require.Equal(beforeReannounce.CreatedAt, reannouncedRow.CreatedAt, "re-announcement must not move the instance")
require.Equal(cluster.ModuleLeaderModeRequestElection, reannouncedRow.moduleLeaderMode())
count := selectBackendCount(t, testDb, electionModule)
require.Equal(1, count.Total)
}
func newClusterClientWithLeaderMode(
t *testing.T,
moduleName string,
host string,
moduleLeaderMode string,
logger log.Logger,
) *cluster.Client {
t.Helper()
return newClusterClientFull(
t,
moduleName,
host,
testModuleRemoteConfig{},
[]byte("{}"),
nil,
moduleLeaderMode,
logger,
)
}
func runClusterClient(
ctx context.Context,
require *require.Assertions,
cli *cluster.Client,
handler *cluster.EventHandler,
) {
go func() {
err := cli.Run(ctx, handler)
require.NoError(err) //nolint:testifylint
}()
}
func selectBackendRow(t *testing.T, testDb db.DB, moduleName string) (backendRow, error) {
t.Helper()
var row backendRow
err := testDb.SelectRow(t.Context(), &row, `
select ws_connection_id, created_at, module_leader_mode
from isp_config_service__backend
where module_name = ?`, moduleName)
if err != nil {
return backendRow{}, errors.WithMessagef(err, "select backend row of module %s", moduleName)
}
return row, nil
}
func requireBackendRow(t *testing.T, testDb db.DB, moduleName string) backendRow {
t.Helper()
require := require.New(t)
var row backendRow
require.Eventually(func() bool {
stored, err := selectBackendRow(t, testDb, moduleName)
if err != nil {
return false
}
row = stored
return true
}, announceTimeout, announceTick, "module %s announcement is not stored", moduleName)
return row
}
func backendCreatedAtPassed(t *testing.T, testDb db.DB, moduleName string) bool {
t.Helper()
var row epochAdvancedRow
err := testDb.SelectRow(t.Context(), &row, `
select unixepoch() > created_at as advanced
from isp_config_service__backend
where module_name = ?`, moduleName)
return err == nil && row.Advanced == 1
}
func selectBackendCount(t *testing.T, testDb db.DB, moduleName string) backendCountRow {
t.Helper()
row := backendCountRow{}
err := testDb.SelectRow(t.Context(), &row, `
select count(*) as total
from isp_config_service__backend
where module_name = ?`, moduleName)
require.New(t).NoError(err)
return row
}
func requireAcceptedModules(require *require.Assertions, ctx context.Context, moduleNames ...string) {
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
modules := make([]domain.ModuleInfo, 0)
require.Eventually(func() bool {
modules = modules[:0]
err = apiCli.Invoke("config/module/get_modules_info").
JsonResponseBody(&modules).
Do(ctx)
if err != nil {
return false
}
connected := make([]string, 0, len(modules))
for _, module := range modules {
connected = append(connected, module.Name)
}
for _, moduleName := range moduleNames {
if !slices.Contains(connected, moduleName) {
return false
}
}
return true
}, announceTimeout, announceTick, "announced modules must be visible in modules info")
for _, moduleName := range moduleNames {
module := findModule(modules, moduleName)
require.NotNil(module, moduleName)
require.Len(module.Status, 1, moduleName)
}
}
func findModule(modules []domain.ModuleInfo, moduleName string) *domain.ModuleInfo {
for i := range modules {
if modules[i].Name == moduleName {
return &modules[i]
}
}
return nil
}
func requireReceivedRoutes(require *require.Assertions, handler *clusterEventHandler) []cluster.RoutingConfig {
require.Eventually(func() bool {
return len(handler.ReceivedRoutes()) > 0
}, announceTimeout, announceTick, "routing configuration must be received")
return handler.ReceivedRoutes()
}
+154
View File
@@ -0,0 +1,154 @@
package tests_test
import (
"slices"
"testing"
"time"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/service/module/leader"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
)
const (
electionMode = cluster.ModuleLeaderModeRequestElection
noElectionMode = cluster.ModuleLeaderModeNone
garbageMode = "SOMETHING_ELSE"
)
func TestDerive(t *testing.T) {
t.Parallel()
require := require.New(t)
elected := leader.Derive(instances(
instance("conn-c", 100, noElectionMode),
instance("conn-a", 200, electionMode),
instance("conn-b", 100, noElectionMode),
))
require.True(elected.HasElection)
require.True(elected.Found)
require.Equal("conn-b", elected.Leader.WsConnectionId, "leader is the earliest instance, tie broken by ws_connection_id")
first := leader.Derive(instances(
instance("conn-c", 100, noElectionMode),
instance("conn-a", 200, electionMode),
instance("conn-b", 100, noElectionMode),
))
second := leader.Derive(instances(
instance("conn-a", 200, electionMode),
instance("conn-b", 100, noElectionMode),
instance("conn-c", 100, noElectionMode),
))
require.Equal(first, second, "the same set of instances must yield the same leader")
require.Equal(elected.Leader.WsConnectionId, first.Leader.WsConnectionId)
require.Equal(elected.Leader.WsConnectionId, second.Leader.WsConnectionId)
}
func TestDerive_InputOrder(t *testing.T) {
t.Parallel()
require := require.New(t)
base := instances(
instance("conn-d", 100, electionMode),
instance("conn-a", 300, electionMode),
instance("conn-c", 100, noElectionMode),
instance("conn-b", 200, noElectionMode),
)
expected := leader.Derive(base)
require.Equal("conn-c", expected.Leader.WsConnectionId)
for _, input := range permutations(base) {
original := slices.Clone(base)
got := leader.Derive(input)
require.Equal(expected, got, "input order must not change the result")
require.Equal(original, base, "Derive must not mutate the caller slice")
}
}
func TestDerive_NoElection(t *testing.T) {
t.Parallel()
require := require.New(t)
got := leader.Derive(instances(
instance("conn-a", 100, noElectionMode),
instance("conn-b", 200, cluster.ModuleLeaderModeImLeader),
instance("conn-c", 50, garbageMode),
))
require.False(got.HasElection)
require.False(got.Found)
require.Equal(entity.Backend{}, got.Leader)
}
func TestDerive_SingleInstance(t *testing.T) {
t.Parallel()
require := require.New(t)
got := leader.Derive(instances(instance("conn-a", 100, electionMode)))
require.True(got.HasElection)
require.True(got.Found)
require.Equal("conn-a", got.Leader.WsConnectionId)
}
func TestDerive_NoInstances(t *testing.T) {
t.Parallel()
require := require.New(t)
got := leader.Derive(nil)
require.False(got.HasElection)
require.False(got.Found)
require.Equal(entity.Backend{}, got.Leader)
}
func TestDeriveByModule(t *testing.T) {
t.Parallel()
require := require.New(t)
first := instance("conn-a", 100, electionMode)
first.ModuleId = "module-1"
first.ModuleName = "module-one"
second := instance("conn-b", 200, noElectionMode)
second.ModuleId = "module-2"
second.ModuleName = "module-two"
elections := leader.DeriveByModule(instances(second, first))
require.Len(elections, 2, "every module gets its own election")
require.Equal("conn-a", elections["module-1"].Leader.WsConnectionId)
require.False(elections["module-2"].HasElection, "an instance of another module must not start an election")
}
func instance(wsConnectionId string, createdAt int64, mode string) entity.Backend {
return entity.Backend{
WsConnectionId: wsConnectionId,
ModuleId: "module-id",
ModuleName: "module",
Address: "10.2.9.1:9999",
ModuleLeaderMode: mode,
CreatedAt: xtypes.Time(time.Unix(createdAt, 0)),
}
}
func instances(backends ...entity.Backend) []entity.Backend {
return backends
}
func permutations(backends []entity.Backend) [][]entity.Backend {
reversed := slices.Clone(backends)
slices.Reverse(reversed)
rotated := append(slices.Clone(backends[1:]), backends[0])
return [][]entity.Backend{backends, reversed, rotated}
}
+251
View File
@@ -0,0 +1,251 @@
package tests_test
import (
"context"
"encoding/json"
"errors"
"reflect"
"testing"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service/module"
kitjson "github.com/txix-open/isp-kit/json"
)
type fakeSchemaRepo struct {
schema *entity.ConfigSchema
}
func (r fakeSchemaRepo) Upsert(ctx context.Context, schema entity.ConfigSchema) error {
return nil
}
func (r fakeSchemaRepo) GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) {
return r.schema, nil
}
type fakeVariableRepo struct {
variables []entity.Variable
}
func (r fakeVariableRepo) GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) {
out := make([]entity.Variable, 0, len(names))
for _, variable := range r.variables {
if _, ok := names[variable.Name]; ok {
out = append(out, variable)
}
}
return out, nil
}
func policyService(schema *entity.ConfigSchema, varRepo fakeVariableRepo, deny bool) module.Service {
return module.NewService(nil, nil, nil, fakeSchemaRepo{schema: schema}, nil, module.NewEmitter(nil), nil, varRepo, deny, nil)
}
func policyTestSchema(t *testing.T) []byte {
t.Helper()
schemaData, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"secrets": map[string]any{"type": "string", "x-ui-exposed": true},
"token": map[string]any{"type": "string", "x-sensitive": true},
"arr": map[string]any{
"type": "array",
"items": map[string]any{"type": "string", "x-sensitive": true},
},
},
})
if err != nil {
t.Fatalf("marshal schema: %v", err)
}
return schemaData
}
type policyTestCase struct {
name string
config string
wantErr bool
wantDetails map[string]string
}
//nolint:funlen
func policyTestCases() []policyTestCase {
return []policyTestCase{
{
name: "ui-exposed secret reference",
config: `{"secrets": "_Var(sec_var)"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"secrets": "UI-exposed field must not reference a variable of type SECRET: sec_var",
},
},
{
name: "ui-exposed multiple secret references",
config: `{"secrets": "_Var(sec_var) _Var(sec_var2)"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"secrets": "UI-exposed field must not reference variables of type SECRET: sec_var, sec_var2",
},
},
{
name: "ui-exposed composite secret reference is rejected",
config: `{"secrets": "{\"a\": \"_Var(sec_var)\"}"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"secrets": "UI-exposed field must not reference a variable of type SECRET: sec_var",
},
},
{
name: "sensitive literal without any references",
config: `{"token": "plain-pass"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"token": "plain value in sensitive field",
},
},
{
name: "sensitive non-secret reference",
config: `{"token": "_Var(txt_var)"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"token": "sensitive field must reference only variables of type SECRET: variable txt_var has type TEXT",
},
},
{
name: "sensitive secret reference",
config: `{"token": "_Var(sec_var)"}`,
},
{
name: "sensitive empty value",
config: `{"token": ""}`,
},
{
name: "sensitive field absent",
config: `{"secrets": "_Var(txt_var)"}`,
},
{
name: "sensitive composite json string is report-only",
config: `{"token": "{\"a\": 1}"}`,
},
{
name: "sensitive mixed value",
config: `{"token": "prefix _Var(sec_var)"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"token": "plain value in sensitive field",
},
},
{
name: "sensitive unknown reference is left to the absent-variable check",
config: `{"token": "_Var(ghost)"}`,
},
{
name: "sensitive array item literal",
config: `{"arr": ["plain-pass"]}`,
wantErr: true,
wantDetails: map[string]string{
"arr.0": "plain value in sensitive field",
},
},
{
name: "both violations at once",
config: `{"secrets": "_Var(sec_var)", "token": "plain-pass"}`,
wantErr: true,
wantDetails: map[string]string{ //nolint:gosec
"secrets": "UI-exposed field must not reference a variable of type SECRET: sec_var",
"token": "plain value in sensitive field",
},
},
{
name: "compliant config",
config: `{"secrets": "_Var(txt_var)", "token": "_Var(sec_var)"}`,
},
}
}
func TestFilterSecretParams(t *testing.T) {
t.Parallel()
const moduleId = "m1"
varRepo := fakeVariableRepo{variables: []entity.Variable{
{Name: "sec_var", Type: entity.SecretType},
{Name: "sec_var2", Type: entity.SecretType},
{Name: "txt_var", Type: entity.TextType},
}}
s := policyService(
&entity.ConfigSchema{Id: "s1", ModuleId: moduleId, Data: policyTestSchema(t)},
varRepo,
true,
)
for _, test := range policyTestCases() {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(test.config), moduleId)
if !test.wantErr {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
var validation domain.ConfigValidationError
if !errors.As(err, &validation) {
t.Fatalf("error = %v, want ConfigValidationError", err)
}
if !reflect.DeepEqual(validation.Details, test.wantDetails) {
t.Fatalf("details = %v, want %v", validation.Details, test.wantDetails)
}
})
}
}
func TestFilterSecretParamsDisabled(t *testing.T) {
t.Parallel()
s := policyService(
&entity.ConfigSchema{Id: "s1", ModuleId: "m1", Data: policyTestSchema(t)},
fakeVariableRepo{},
false,
)
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"secrets": "_Var(sec_var)", "token": "plain-pass"}`), "m1")
if err != nil {
t.Fatalf("expected no error with the policy disabled, got: %v", err)
}
}
func TestFilterSecretParamsWithoutSchema(t *testing.T) {
t.Parallel()
s := policyService(nil, fakeVariableRepo{}, true)
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"token": "plain-pass"}`), "m1")
if err != nil {
t.Fatalf("expected no error without a schema, got: %v", err)
}
}
func TestFilterSecretParamsSchemaWithoutPolicyPaths(t *testing.T) {
t.Parallel()
schemaData, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{"plain": map[string]any{"type": "string"}},
})
if err != nil {
t.Fatalf("marshal schema: %v", err)
}
s := policyService(
&entity.ConfigSchema{Id: "s1", ModuleId: "m1", Data: schemaData},
fakeVariableRepo{},
true,
)
err = s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"plain": "any value"}`), "m1")
if err != nil {
t.Fatalf("expected no error for a schema without policy paths, got: %v", err)
}
}
+86
View File
@@ -0,0 +1,86 @@
package tests_test
import (
"testing"
"time"
"isp-config-service/domain"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/json"
)
type renderPolicyConfig struct {
Exposed string `schemaGen:"uiExposed"`
Plain string
}
//nolint:funlen,paralleltest,noctx
func TestRenderSecretSkip(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
err = apiCli.Invoke("config/variable/upsert").
JsonRequestBody([]domain.UpsertVariableRequest{{
Name: "rdVar",
Description: "test",
Type: "TEXT",
Value: "render-visible",
}}).
Do(t.Context())
require.NoError(err)
eventHandler := newClusterEventHandler()
renderCli := newClusterClientWith(
t,
"RenderPolicy",
"10.2.9.41",
renderPolicyConfig{},
[]byte(`{"exposed":"_Var(rdVar)","plain":"_Var(rdVar)"}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler().RemoteConfigReceiver(eventHandler)
err := renderCli.Run(t.Context(), handler)
require.NoError(err) //nolint:testifylint
}()
time.Sleep(3 * time.Second)
active := domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "RenderPolicy"}).
JsonResponseBody(&active).
Do(t.Context())
require.NoError(err)
require.NotEmpty(active.ModuleId)
first := renderPolicyConfig{}
err = json.Unmarshal(eventHandler.ReceivedConfigs()[0], &first)
require.NoError(err)
require.Equal("render-visible", first.Exposed)
require.Equal("render-visible", first.Plain)
err = apiCli.Invoke("config/variable/upsert").
JsonRequestBody([]domain.UpsertVariableRequest{{
Name: "rdVar",
Description: "test",
Type: "SECRET",
Value: "render-secret-value",
}}).
Do(t.Context())
require.NoError(err)
time.Sleep(3 * time.Second)
last := renderPolicyConfig{}
err = json.Unmarshal(eventHandler.ReceivedConfigs()[len(eventHandler.ReceivedConfigs())-1], &last)
require.NoError(err)
require.Equal("_Var(rdVar)", last.Exposed, "the secret reference must stay a literal in the ui-exposed leaf")
require.Equal("render-secret-value", last.Plain)
}
+281
View File
@@ -0,0 +1,281 @@
package tests_test
import (
"encoding/json"
"testing"
"time"
"isp-config-service/domain"
"github.com/stretchr/testify/require"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/grpc/isp"
"google.golang.org/grpc/status"
)
type secretPolicyOauthClient struct {
ClientId string
LoginEndpoint string `schemaGen:"uiExposed"`
}
type secretPolicyOauth struct {
Clients []secretPolicyOauthClient
}
type secretPolicyConfig struct {
Secrets string `schemaGen:"uiExposed"`
Plain string
Oauth secretPolicyOauth
}
type businessError struct {
ErrorCode int `json:"errorCode"`
ErrorMessage string `json:"errorMessage"`
Details map[string]any `json:"details"`
}
func requireBusinessError(require *require.Assertions, err error, code int) businessError {
require.Error(err)
st, ok := status.FromError(err)
require.True(ok, "expected a gRPC status error, got: %v", err)
for _, detail := range st.Details() {
if msg, ok := detail.(*isp.Message); ok {
body, ok := msg.GetBody().(*isp.Message_BytesBody)
require.True(ok, "expected a bytes body, got: %T", msg.GetBody())
var be businessError
require.NoError(json.Unmarshal(body.BytesBody, &be))
require.Equal(code, be.ErrorCode, "unexpected error code: %s", body.BytesBody)
return be
}
}
require.Failf("business error not found in status details", "details: %+v", st.Details())
return businessError{}
}
//nolint:funlen,paralleltest,testifylint
func TestSecretPolicy(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
err = apiCli.Invoke("config/variable/upsert").
JsonRequestBody([]domain.UpsertVariableRequest{
{Name: "polSecret", Description: "test", Type: "SECRET", Value: "top-secret"},
{Name: "polText", Description: "test", Type: "TEXT", Value: "visible"},
}).
Do(t.Context())
require.NoError(err)
eventHandler := newClusterEventHandler()
clientA := newClusterClientWith(
t,
"SecretPolicyA",
"10.2.9.31",
secretPolicyConfig{},
[]byte(`{"secrets":"_Var(polText)","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polText)"}]}}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler().RemoteConfigReceiver(eventHandler)
err := clientA.Run(t.Context(), handler)
require.NoError(err) //nolint:testifylint
}()
time.Sleep(3 * time.Second)
active := domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyA"}).
JsonResponseBody(&active).
Do(t.Context())
require.NoError(err)
require.NotEmpty(active.Id)
be := requireBusinessError(require,
apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: active.Id,
Name: active.Name,
ModuleId: active.ModuleId,
Version: active.Version,
Data: []byte(`{"secrets":"_Var(polSecret)","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polText)"}]}}`),
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polSecret", be.Details["secrets"])
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyA"}).
JsonResponseBody(&active).
Do(t.Context())
require.NoError(err)
require.JSONEq(
`{"secrets":"_Var(polText)","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polText)"}]}}`,
string(active.Data))
be = requireBusinessError(require,
apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: active.Id,
Name: active.Name,
ModuleId: active.ModuleId,
Version: active.Version,
Data: []byte(`{"secrets":"_Var(polSecret)","plain":"p"}`),
Unsafe: true,
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polSecret", be.Details["secrets"])
be = requireBusinessError(require,
apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Name: "policy-insert",
ModuleId: active.ModuleId,
Data: []byte(`{"secrets":"_Var(polSecret)"}`),
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polSecret", be.Details["secrets"])
be = requireBusinessError(require,
apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: active.Id,
Name: active.Name,
ModuleId: active.ModuleId,
Version: active.Version,
Data: []byte(`{"secrets":"s","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polSecret)"}]}}`),
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polSecret", be.Details["oauth.clients.0.loginEndpoint"])
err = apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: active.Id,
Name: active.Name,
ModuleId: active.ModuleId,
Version: active.Version,
Data: []byte(`{"secrets":"s","plain":"_Var(polSecret)","oauth":{"clients":[{"clientId":"a","loginEndpoint":"x"}]}}`),
}).
Do(t.Context())
require.NoError(err)
active = domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyA"}).
JsonResponseBody(&active).
Do(t.Context())
require.NoError(err)
err = apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: active.Id,
Name: active.Name,
ModuleId: active.ModuleId,
Version: active.Version,
Data: []byte(`{"secrets":"_Var(polText)","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polText)"}]}}`),
}).
Do(t.Context())
require.NoError(err)
err = apiCli.Invoke("config/config/sync").
JsonRequestBody(domain.SyncConfigRequest{ModuleName: "SecretPolicyA"}).
Do(t.Context())
require.NoError(err)
time.Sleep(3 * time.Second)
require.GreaterOrEqual(len(eventHandler.ReceivedConfigs()), 2)
pushedBefore := len(eventHandler.ReceivedConfigs())
err = apiCli.Invoke("config/variable/upsert").
JsonRequestBody([]domain.UpsertVariableRequest{{
Name: "polText", Description: "test", Type: "SECRET", Value: "now-secret",
}}).
Do(t.Context())
require.NoError(err)
time.Sleep(3 * time.Second)
require.Greater(len(eventHandler.ReceivedConfigs()), pushedBefore)
be = requireBusinessError(require,
apiCli.Invoke("config/config/sync").
JsonRequestBody(domain.SyncConfigRequest{ModuleName: "SecretPolicyA"}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polText", be.Details["secrets"])
require.Equal("UI-exposed field must not reference a variable of type SECRET: polText", be.Details["oauth.clients.0.loginEndpoint"])
time.Sleep(3 * time.Second)
require.Len(eventHandler.ReceivedConfigs(), pushedBefore+1)
clientB := newClusterClientWith(
t,
"SecretPolicyB",
"10.2.9.32",
secretPolicyConfig{},
[]byte(`{"secrets":"_Var(polSecret)","plain":"p","oauth":{"clients":[]}}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler()
err := clientB.Run(t.Context(), handler)
_ = err
}()
time.Sleep(3 * time.Second)
initial := domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyB"}).
JsonResponseBody(&initial).
Do(t.Context())
require.NoError(err)
require.Contains(string(initial.Data), "_Var(polSecret)")
be = requireBusinessError(require,
apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Name: "policy-no-schema",
ModuleId: "00000000-0000-0000-0000-000000000000",
Data: []byte(`{"secrets":"_Var(polSecret)"}`),
}).
Do(t.Context()),
domain.ErrorCodeSchemaNotFound)
require.Empty(be.Details)
var marked domain.CreateUpdateConfigResponse
err = apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Name: "policy-mark",
ModuleId: active.ModuleId,
Data: []byte(`{"secrets":"s","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"x"}]}}`),
}).
JsonResponseBody(&marked).
Do(t.Context())
require.NoError(err)
require.NotEmpty(marked.Id)
err = apiCli.Invoke("config/config/mark_config_as_active").
JsonRequestBody(domain.IdRequest{Id: marked.Id}).
Do(t.Context())
require.NoError(err)
be = requireBusinessError(require,
apiCli.Invoke("config/config/mark_config_as_active").
JsonRequestBody(domain.IdRequest{Id: active.Id}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("UI-exposed field must not reference a variable of type SECRET: polText", be.Details["secrets"])
require.Equal("UI-exposed field must not reference a variable of type SECRET: polText", be.Details["oauth.clients.0.loginEndpoint"])
fetched := domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyA"}).
JsonResponseBody(&fetched).
Do(t.Context())
require.NoError(err)
require.Equal(marked.Id, fetched.Id)
}
+189
View File
@@ -0,0 +1,189 @@
package tests_test
import (
"context"
"testing"
"isp-config-service/entity"
"isp-config-service/service/subscription"
"github.com/stretchr/testify/require"
"github.com/txix-open/etp/v4"
"github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/log"
)
const (
subscriptionTestModuleId = "test-module-id"
subscriptionTestModuleName = "test-module"
subscriptionLeaderConnId = "conn-1"
subscriptionFollowerConnId = "conn-2"
subscriptionLeaderAddress = "10.0.0.1:9000"
successorAddress = "10.0.0.2:9000"
plainAddress = "10.0.0.3:9000"
)
type subscriptionStoredLog struct {
message any
fields map[string]string
}
type subscriptionLoggerSpy struct {
infos []subscriptionStoredLog
}
func (l *subscriptionLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {
entry := subscriptionStoredLog{
message: message,
fields: make(map[string]string, len(fields)),
}
for _, field := range fields {
entry.fields[field.Key] = field.String
}
l.infos = append(l.infos, entry)
}
func (l *subscriptionLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
func (l *subscriptionLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
func (l *subscriptionLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
type moduleRepoSpy struct{}
func (r *moduleRepoSpy) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
return []entity.Module{{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}}, nil
}
func (r *moduleRepoSpy) GetById(ctx context.Context, id string) (*entity.Module, error) {
return &entity.Module{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}, nil
}
type subscriptionBackendRepoSpy struct {
forLeaderElection []entity.Backend
all []entity.Backend
}
func (r *subscriptionBackendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
return r.forLeaderElection, nil
}
func (r *subscriptionBackendRepoSpy) All(ctx context.Context) ([]entity.Backend, error) {
return r.all, nil
}
type configRepoSpy struct{}
func (r *configRepoSpy) GetActive(ctx context.Context, moduleId string) (*entity.Config, error) {
return &entity.Config{ModuleId: moduleId}, nil
}
type variableServiceSpy struct{}
func (s *variableServiceSpy) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) {
return input, nil
}
type emitterSpy struct{}
func (e *emitterSpy) Emit(ctx context.Context, conn *etp.Conn, event string, data []byte) {}
// The on-call engineer answers "who is accepting sessions of this module" from the log of the node that
// emitted the address list: the same derivation the subscriber received, logged where it is published.
func TestNotifyBackendsChangedLogsTheLeaderItPublishes(t *testing.T) {
t.Parallel()
require := require.New(t)
logger := &subscriptionLoggerSpy{}
rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(subscriptionTestModuleName))
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
forLeaderElection: []entity.Backend{
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress),
subscriptionElectedInstance(subscriptionFollowerConnId, successorAddress),
},
})
err := service.NotifyBackendsChanged(t.Context(), subscriptionTestModuleId)
require.NoError(err)
require.Len(logger.infos, 1)
require.Equal("module address list narrowed to the leader", logger.infos[0].message)
require.Equal(subscriptionTestModuleName, logger.infos[0].fields["moduleName"])
require.Equal(subscriptionLeaderAddress, logger.infos[0].fields["leaderAddress"],
"the logged leader is the oldest elected instance, the one the subscriber received")
}
func TestNotifyRoutingChangedLogsPublishedLeaders(t *testing.T) {
t.Parallel()
require := require.New(t)
logger := &subscriptionLoggerSpy{}
rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
all: []entity.Backend{
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress),
subscriptionElectedInstance(subscriptionFollowerConnId, successorAddress),
plainInstance("conn-3", plainAddress),
},
})
err := service.NotifyRoutingChanged(t.Context())
require.NoError(err)
require.Len(logger.infos, 1, "one summary line per routing rebuild")
require.Equal("routing map publishes module leaders", logger.infos[0].message)
require.Equal(subscriptionTestModuleName+"="+subscriptionLeaderAddress, logger.infos[0].fields["moduleLeaders"],
"only the elected module and only its leader are published, the plain module is not listed")
}
func TestNotifyRoutingChangedWithoutElectionLogsNothing(t *testing.T) {
t.Parallel()
require := require.New(t)
logger := &subscriptionLoggerSpy{}
rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
all: []entity.Backend{plainInstance("conn-3", plainAddress)},
})
err := service.NotifyRoutingChanged(t.Context())
require.NoError(err)
require.Empty(logger.infos, "modules without election keep the previous behaviour, including the log")
}
func subscriptionElectedInstance(connId string, address string) entity.Backend {
return entity.Backend{
WsConnectionId: connId,
ModuleId: subscriptionTestModuleId,
ModuleName: subscriptionTestModuleName,
Address: address,
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
}
}
func plainInstance(connId string, address string) entity.Backend {
return entity.Backend{
WsConnectionId: connId,
ModuleId: "plain-module-id",
ModuleName: "plain-module",
Address: address,
}
}
func newService(logger log.Logger, rooms *etp.Rooms, backendRepo subscription.BackendRepo) subscription.Service {
return subscription.NewService(
&moduleRepoSpy{},
backendRepo,
&configRepoSpy{},
rooms,
&emitterSpy{},
&variableServiceSpy{},
logger,
)
}
+422
View File
@@ -0,0 +1,422 @@
package tests_test
import (
"encoding/json"
"strings"
"testing"
"isp-config-service/entity"
"isp-config-service/service/variable"
)
func textVar(name, value string) entity.Variable {
return entity.Variable{Name: name, Type: entity.TextType, Value: value}
}
func secretVar(value string) entity.Variable {
return entity.Variable{Name: "s1", Type: entity.SecretType, Value: value}
}
func TestRenderSubstitutesNonUI(t *testing.T) {
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"a":"x"}` {
t.Fatalf("out = %s, want %s", out, `{"a":"x"}`)
}
if len(skipped) != 0 || len(undefined) != 0 {
t.Fatalf("skipped = %v, undefined = %v, want both empty", skipped, undefined)
}
}
func TestRenderKeepsSecretInUI(t *testing.T) {
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(s1)"}`),
[]string{"a"},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"a":"_Var(s1)"}` {
t.Fatalf("out = %s, want the literal placeholder", out)
}
if strings.Contains(string(out), "top") {
t.Fatalf("the secret value leaked into the output: %s", out)
}
if len(skipped) != 1 || skipped[0].Path != "a" || skipped[0].Variable != "s1" {
t.Fatalf("skipped = %v, want [{$.a s1}]", skipped)
}
if len(undefined) != 0 {
t.Fatalf("undefined = %v, want empty", undefined)
}
}
func TestRenderSameVarUINonUI(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"ui":"_Var(s1)","plain":"_Var(s1)"}`),
[]string{"ui"},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"plain":"top","ui":"_Var(s1)"}` {
t.Fatalf("out = %s, want the non-UI leaf substituted and the UI leaf left as a literal", out)
}
if len(skipped) != 1 || skipped[0].Path != "ui" {
t.Fatalf("skipped = %v, want [{$.ui s1}]", skipped)
}
}
func TestRenderMixedUILeaf(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"a":"p/_Var(t1)/_Var(s1)"}`),
[]string{"a"},
map[string]entity.Variable{"t1": textVar("t1", "tv"), "s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"a":"p/tv/_Var(s1)"}` {
t.Fatalf("out = %s, want %s", out, `{"a":"p/tv/_Var(s1)"}`)
}
if len(skipped) != 1 || skipped[0].Variable != "s1" {
t.Fatalf("skipped = %v, want [{$.a s1}]", skipped)
}
}
func TestRenderSecretOutsideUI(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"a":"_Var(s1)"}`),
nil,
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"a":"top"}` {
t.Fatalf("out = %s, want %s", out, `{"a":"top"}`)
}
if len(skipped) != 0 {
t.Fatalf("skipped = %v, want empty", skipped)
}
}
func TestRenderArrayPath(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"oauth":{"clients":[{"e":"_Var(s1)"},{"e":"x"}]}}`),
[]string{"oauth.clients.0.e"},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"oauth":{"clients":[{"e":"_Var(s1)"},{"e":"x"}]}}` {
t.Fatalf("out = %s, want the literal in the UI array leaf", out)
}
if len(skipped) != 1 || skipped[0].Path != "oauth.clients.0.e" || skipped[0].Variable != "s1" {
t.Fatalf("skipped = %v, want [{$.oauth.clients[].e s1}]", skipped)
}
}
func TestRenderUndefined(t *testing.T) {
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(ghost)"}`),
nil,
map[string]entity.Variable{},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(undefined) != 1 || undefined[0] != "ghost" {
t.Fatalf("undefined = %v, want [ghost]", undefined)
}
if len(skipped) != 0 {
t.Fatalf("skipped = %v, want empty", skipped)
}
if string(out) != `{"a":"_Var(ghost)"}` {
t.Fatalf("out = %s, the unknown reference is left as-is", out)
}
}
func TestRenderUndefinedInUI(t *testing.T) {
t.Parallel()
_, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(ghost)"}`),
[]string{"a"},
map[string]entity.Variable{},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(undefined) != 1 || undefined[0] != "ghost" {
t.Fatalf("undefined = %v, want [ghost]", undefined)
}
if len(skipped) != 0 {
t.Fatalf("skipped = %v, want empty", skipped)
}
}
func TestRenderToInt(t *testing.T) {
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"n":"_ToInt(_Var(n1))"}`),
nil,
map[string]entity.Variable{"n1": textVar("n1", "42")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"n":42}` {
t.Fatalf("out = %s, want the number 42", out)
}
}
func TestRenderToIntSecretInUI(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"n":"_ToInt(_Var(s1))"}`),
[]string{"n"},
map[string]entity.Variable{"s1": secretVar("42")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"n":"_ToInt(_Var(s1))"}` {
t.Fatalf("out = %s, the _ToInt wrapper must not break the literal", out)
}
if len(skipped) != 1 || skipped[0].Variable != "s1" {
t.Fatalf("skipped = %v, want [{$.n s1}]", skipped)
}
}
func TestRenderKeysUntouched(t *testing.T) {
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"_Var(k)":"_Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"_Var(k)":"x"}` {
t.Fatalf("out = %s, JSON keys must not be substituted", out)
}
}
func TestRenderSkippedDeduped(t *testing.T) {
t.Parallel()
_, skipped, _, err := variable.Render(
[]byte(`{"a":"_Var(s1)_Var(s1)"}`),
[]string{"a"},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if len(skipped) != 1 {
t.Fatalf("skipped = %v, want a single entry", skipped)
}
}
func TestRenderNonStringUILeaf(t *testing.T) {
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"n":5}`),
[]string{"n"},
map[string]entity.Variable{},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"n":5}` {
t.Fatalf("out = %s, non-string leaves are untouched", out)
}
if len(skipped) != 0 {
t.Fatalf("skipped = %v, want empty", skipped)
}
}
func TestRenderInvalidJSON(t *testing.T) {
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":`),
nil,
map[string]entity.Variable{},
)
if err == nil {
t.Fatal("Render: want an error for invalid JSON")
}
if out != nil || len(skipped) != 0 || len(undefined) != 0 {
t.Fatalf("out = %s, skipped = %v, undefined = %v, want all empty", out, skipped, undefined)
}
}
func TestRenderEscapes(t *testing.T) {
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"a":"line1\nline2 _Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if string(out) != `{"a":"line1\nline2 x"}` {
t.Fatalf("out = %s, JSON escapes must survive the re-serialization", out)
}
}
func TestRenderCompositeInUIKeepsSecret(t *testing.T) {
t.Parallel()
composite, err := json.Marshal(map[string]any{"a": "_Var(s1)"})
if err != nil {
t.Fatalf("marshal composite: %v", err)
}
doc, err := json.Marshal(map[string]any{
"secrets": string(composite),
"plain": "_Var(s1)",
})
if err != nil {
t.Fatalf("marshal document: %v", err)
}
out, skipped, undefined, err := variable.Render(
doc,
[]string{"secrets", "plain"},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
if strings.Contains(string(out), "top") {
t.Fatalf("the secret value leaked into the output: %s", out)
}
var m map[string]any
err = json.Unmarshal(out, &m)
if err != nil {
t.Fatalf("unmarshal output: %v", err)
}
if got := m["secrets"]; got != string(composite) {
t.Fatalf("secrets = %v, want the composite with the literal reference: %s", got, composite)
}
if got := m["plain"]; got != "_Var(s1)" {
t.Fatalf("plain = %v, want the literal placeholder", got)
}
if len(skipped) != 2 {
t.Fatalf("skipped = %v, want 2 entries", skipped)
}
seen := make(map[string]struct{}, len(skipped))
for _, ref := range skipped {
seen[ref.Path+"\x00"+ref.Variable] = struct{}{}
}
if _, ok := seen["secrets\x00s1"]; !ok {
t.Fatalf("skipped = %v, want a secrets entry", skipped)
}
if _, ok := seen["plain\x00s1"]; !ok {
t.Fatalf("skipped = %v, want a plain entry", skipped)
}
if len(undefined) != 0 {
t.Fatalf("undefined = %v, want empty", undefined)
}
}
func TestRenderCompositeOutsideUISubstituted(t *testing.T) {
t.Parallel()
composite, err := json.Marshal(map[string]any{"a": "_Var(s1)"})
if err != nil {
t.Fatalf("marshal composite: %v", err)
}
doc, err := json.Marshal(map[string]any{"secrets": string(composite)})
if err != nil {
t.Fatalf("marshal document: %v", err)
}
out, skipped, undefined, err := variable.Render(
doc,
nil,
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
var m map[string]any
err = json.Unmarshal(out, &m)
if err != nil {
t.Fatalf("unmarshal output: %v", err)
}
if got := m["secrets"]; got != `{"a":"top"}` {
t.Fatalf("secrets = %v, want the secret value substituted", got)
}
if len(skipped) != 0 || len(undefined) != 0 {
t.Fatalf("skipped = %v, undefined = %v, want both empty", skipped, undefined)
}
}
func TestRenderCompositeUndefinedCollected(t *testing.T) {
t.Parallel()
composite, err := json.Marshal([]any{"_Var(ghost)"})
if err != nil {
t.Fatalf("marshal composite: %v", err)
}
doc, err := json.Marshal(map[string]any{"secrets": string(composite)})
if err != nil {
t.Fatalf("marshal document: %v", err)
}
out, skipped, undefined, err := variable.Render(
doc,
[]string{"secrets"},
map[string]entity.Variable{},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
var m map[string]any
err = json.Unmarshal(out, &m)
if err != nil {
t.Fatalf("unmarshal output: %v", err)
}
if got, want := m["secrets"], string(composite); got != want {
t.Fatalf("secrets = %v, want %s (the unknown reference stays a literal)", got, want)
}
if len(skipped) != 0 {
t.Fatalf("skipped = %v, want empty", skipped)
}
if len(undefined) != 1 || undefined[0] != "ghost" {
t.Fatalf("undefined = %v, want [ghost]", undefined)
}
}
+89
View File
@@ -124,6 +124,95 @@ func TestVariableAcceptance(t *testing.T) {
require.Empty(allResponse[1].Value) // secret
}
//nolint:funlen,paralleltest
func TestVariableLinksAfterConfigUpdate(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
apiCli, err := client.Default()
require.NoError(err)
apiCli.Upgrade([]string{"127.0.0.1:9002"})
err = apiCli.Invoke("config/variable/create").
JsonRequestBody(domain.CreateVariableRequest{
Name: "linkVar",
Description: "test",
Type: "TEXT",
Value: fake.It[string](),
}).
Do(t.Context())
require.NoError(err)
type linkTestConfig struct {
Addr string
Alias string
}
clientC := newClusterClientWith(
t,
"LinkTestModule",
"10.2.9.77",
linkTestConfig{},
[]byte(`{"addr":"init","alias":"init"}`),
nil,
logger,
)
go func() {
handler := cluster.NewEventHandler()
err := clientC.Run(t.Context(), handler)
require.NoError(err) //nolint:testifylint
}()
time.Sleep(2 * time.Second)
activeConfig := domain.Config{}
err = apiCli.Invoke("config/config/get_active_config_by_module_name").
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "LinkTestModule"}).
JsonResponseBody(&activeConfig).
Do(t.Context())
require.NoError(err)
// The same variable is referenced twice in the config data.
err = apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: activeConfig.Id,
Name: activeConfig.Name,
ModuleId: activeConfig.ModuleId,
Version: activeConfig.Version,
Data: []byte(`{"addr":"_Var(linkVar)","alias":"prefix/_Var(linkVar)"}`),
}).
Do(t.Context())
require.NoError(err)
varResponse := []domain.Variable{}
err = apiCli.Invoke("config/variable/all").
JsonResponseBody(&varResponse).
Do(t.Context())
require.NoError(err)
require.Len(varResponse, 1)
require.Equal("linkVar", varResponse[0].Name)
require.Len(varResponse[0].ContainsInConfigs, 1)
require.Equal(activeConfig.Id, varResponse[0].ContainsInConfigs[0].Id)
// Re-saving identical config data must keep the links.
err = apiCli.Invoke("config/config/create_update_config").
JsonRequestBody(domain.CreateUpdateConfigRequest{
Id: activeConfig.Id,
Name: activeConfig.Name,
ModuleId: activeConfig.ModuleId,
Version: activeConfig.Version,
Data: []byte(`{"alias":"prefix/_Var(linkVar)","addr":"_Var(linkVar)"}`),
}).
Do(t.Context())
require.NoError(err)
varResponse = []domain.Variable{}
err = apiCli.Invoke("config/variable/all").
JsonResponseBody(&varResponse).
Do(t.Context())
require.NoError(err)
require.Len(varResponse[0].ContainsInConfigs, 1)
require.Equal(activeConfig.Id, varResponse[0].ContainsInConfigs[0].Id)
}
func unmarshalConfig(require *require.Assertions, configData []byte) configWithVars {
firstConfig := configWithVars{}
err := json.Unmarshal(configData, &firstConfig)