Compare commits

..
38 Commits
Author SHA1 Message Date
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
txix 137eaaa07f 2026-07-07 15:31:10: merge [main:3b99380a623e70022ec99376377acdde8134a7c9];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-07-07 15:31:10 +03:00
txix 68c5b8c636 2026-05-13 14:30:13: merge [main:45b28e46e6901c486243d66775b0958aedc2b418];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-05-13 14:30:13 +03:00
txix 5bf1807cb3 2026-04-23 17:27:09: merge [main:48ccd130b2c03616d9d7fa2fecb57426bbf3c6c4]; 2026-04-23 17:27:09 +03:00
txix e571aa709a 2026-02-20 19:41:52: merge [main:416f9307c3185ce221c98d501d55584da7301600];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-20 19:41:52 +03:00
txix 3c0c32ec72 2026-02-10 17:42:12: merge [main:f97795bd90603310b924d685666ce64c68644e4a];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-10 17:42:12 +03:00
txix bd3a52e7f3 2026-02-09 12:15:13: merge [main:f7931b1d8350cf640562be540836310ee6da010b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2026-02-09 12:15:13 +03:00
txix bb02ef25ab 2026-02-06 11:20:37: merge [main:245cf8852da4396ef3b198c2af5f7e483379e391]; 2026-02-06 11:20:37 +03:00
txix bd633d1599 2026-02-05 17:50:20: merge [main:7b09eb3a07fc352b4ebee3cd1f0a9631f4ccb38d]; 2026-02-05 17:50:20 +03:00
txix 7ee7b6749f 2025-12-01 16:45:09: merge [main:8101f9a8c84d0c8c7bd462ac374f4db79dbc5d21];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-12-01 16:45:09 +03:00
txix 065c96042d 2025-10-09 15:30:52: merge [main:efed09bb923fb843bd0ebfcc65fd558a5a91727b];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-10-09 15:30:52 +03:00
txix 964ead61f7 2025-09-17 18:00:36: merge [main:5a3d4fffeaf49ec2831d3f9b1dea027c1e1784e1];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-09-17 18:00:36 +03:00
txix c36b4cdc1c 2025-08-21 16:39:38: merge [main:7a585711f6c2abcee6bbfb53dbf4c38fbbb68103]; 2025-08-21 16:39:38 +03:00
txix 261dfbd3cd 2025-07-08 11:38:08: merge [main:846129b1afe26f21c7e182be578112bb0c3f76ce];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-07-08 11:38:08 +03:00
txix f32c1bef30 2025-06-10 09:17:26: merge [main:78eeee0bc665dc8fd1e8b99c5ce47dc227342a7f];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-06-10 09:17:26 +03:00
txix 5e248d85fe 2025-06-06 17:09:42: merge [main:eb7997476085e283af784adf7ada881a3d37e535];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
2025-06-06 17:09:42 +03:00
txix 7ec4962301 2025-06-06 16:56:57: merge [main:350d22ae7512add0069a2d5ac30546bd8b32d979]; 2025-06-06 16:56:57 +03:00
txix 6b7ddafa32 2025-05-27 14:44:20: merge [main:3e7f2358764cd22b6766b4ea57d14a429cfb06ab]; 2025-05-27 14:44:20 +03:00
txix 7ba1f0a5e8 2025-04-18 12:20:59: merge [main:aefc14ece9229d4d8e88c117a09f85d1a6775b46]; 2025-04-18 12:20:59 +03:00
txix 18205b2e66 2025-04-17 18:01:00: merge [main:0e6b5dec5225670f20a213993b54e1c0fcd44c63]; 2025-04-17 18:01:00 +03:00
txix 22baffabfb 2025-03-24 15:30:34: merge [main:7a1d8822489f02be3b825bb1224de48bab9c1657]; 2025-03-24 15:30:34 +03:00
txix 4a95b4b578 2024-12-27 16:47:46: merge [main:69567c48694f02359eecd8e696669f7c3de0b398]; 2024-12-27 16:47:46 +03:00
txix 0fbe723485 2024-12-12 13:56:05: merge [main:5fbfe1b039c8b70814b6262508bfeda3a8069dd2]; 2024-12-12 13:56:05 +03:00
txix e81f8c64cf 2024-11-27 12:16:06: merge [master:8f9dc2048fde1f9cb1c40e716e65dd91b77256b8]; 2024-11-27 12:16:06 +03:00
txix 802ce18a5e 2024-11-26 19:14:10: merge [master:16d2701e265c75b03df0b81a0cefc06bc9563e7a]; 2024-11-26 19:14:10 +03:00
txix 77244d4997 2024-11-20 14:39:28: merge [master:83355f8bbc6bf330c8f3d946415d732d2590d17d]; 2024-11-20 14:39:28 +03:00
txix 12b71a1777 2024-11-15 13:12:14: merge [master:93f2a5ed50211ee88fbdb241f4dbaa4af50d1d38]; 2024-11-15 13:12:14 +03:00
txix 1badb6b931 2024-04-24 17:59:21: merge [master:5e72ec386437c66661a2a98b1a232a3ad49af893]; 2024-04-24 17:59:21 +03:00
txix 14221f778c 2024-03-25 17:42:24: merge [master:e2419e2c4bf843e66dc679b387cbb6900599ee22]; 2024-03-25 17:42:24 +03:00
txix a5ca7b230a 2024-03-25 17:06:20: merge [master:72afc94782d802dbef7d4b1b092b6b1d02301edf]; 2024-03-25 17:06:20 +03:00
txix 3427a92d08 2024-03-25 16:52:24: merge [master:02070b1db1d2009dc917980dfc5e731e9508b8d0]; 2024-03-25 16:52:24 +03:00
txix ef7c017e4c 2024-03-25 16:23:54: merge [master:2fc6c7ba91a773e1055473094b8e3d7192bf4df4]; 2024-03-25 16:23:54 +03:00
41 changed files with 277 additions and 3017 deletions

No files matched your search

-4
View File
@@ -10,7 +10,6 @@ linters:
- exhaustruct # не имеет смысла - exhaustruct # не имеет смысла
- exhaustruct_v5 # не имеет смысла - exhaustruct_v5 # не имеет смысла
- goconst # не всегда имеет смысл - goconst # не всегда имеет смысл
- gomodguard # deprecated
- godot # не актуально для swagger - godot # не актуально для swagger
- godox # не позволяет оставлять todo - godox # не позволяет оставлять todo
- musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур - musttag # у нас собственное правило: не используем теги, если работаем с пакетом isp-kit/json и с внутренними структурами(между нашими сервисами), при этом теги обязательный для всех внешних для нас структур
@@ -64,9 +63,6 @@ linters:
- unqueryvet - unqueryvet
- prealloc - prealloc
path: ".*_test\\.go$" path: ".*_test\\.go$"
- linters:
- testpackage
path: service/module # юниты обходов и аудита требуют доступа к неэкспортированным функциям
paths: paths:
- third_party$ - third_party$
- builtin$ - builtin$
+1 -1
View File
@@ -1 +1 @@
3.14.0 3.12.1
+1 -4
View File
@@ -96,7 +96,7 @@ func (l Locator) Config() *Config {
configHistoryRepo := repository.NewConfigHistory(l.db) configHistoryRepo := repository.NewConfigHistory(l.db)
variableRepo := repository.NewVariable(l.db) variableRepo := repository.NewVariable(l.db)
variableService := variable.NewService(variableRepo, configRepo, eventRepo, configSchemaRepo, l.logger) variableService := variable.NewService(variableRepo, configRepo, eventRepo)
variableController := api.NewVariable(variableService) variableController := api.NewVariable(variableService)
etpSrv := etp.NewServer( etpSrv := etp.NewServer(
@@ -134,8 +134,6 @@ func (l Locator) Config() *Config {
subscriptionService, subscriptionService,
emitter, emitter,
variableService, variableService,
variableRepo,
l.cfg.Local.EnableSensitiveFieldConfigChecking,
l.logger, l.logger,
) )
moduleController := controller.NewModule(moduleService, l.logger) moduleController := controller.NewModule(moduleService, l.logger)
@@ -150,7 +148,6 @@ func (l Locator) Config() *Config {
configApiService := apisvs.NewConfig( configApiService := apisvs.NewConfig(
configRepo, configRepo,
moduleRepo, moduleRepo,
moduleService,
configSchemaRepo, configSchemaRepo,
eventRepo, eventRepo,
configHistoryApiService, configHistoryApiService,
-6
View File
@@ -1,9 +1,3 @@
### v3.14.0
* Флаг `configWriteDeny` заменён на `enableSensitiveFieldConfigChecking`, по умолчанию `false`
* Обновлен isp-kit до v1.78.0: инфраструкционные поля-пароли и закрытые ключи (dbx, kafkax, stompx, grmqx) помечены тегом `schemaGen:"sensitive"`
### v3.13.0
* Добавлена обработка новых тегов конфигурации модулей: теги для UI экспонируемых полей и полей требующих ссылки на переменные с типом SECRET
* Добавлен эндпоинт `/config/audit` для получения информации о нарушении политики UI экспонируемых полей и полей требующих ссылки на переменные с типом SECRET
### v3.12.1 ### v3.12.1
* Обновление ограничений конфигурации: в параметре `KeepConfigVersions` допустимо значение `0` * Обновление ограничений конфигурации: в параметре `KeepConfigVersions` допустимо значение `0`
### v3.12.0 ### v3.12.0
-1
View File
@@ -7,7 +7,6 @@ replace isp-config-service => ../..
require ( require (
github.com/jmoiron/sqlx v1.4.0 github.com/jmoiron/sqlx v1.4.0
github.com/mattn/go-sqlite3 v1.14.47 github.com/mattn/go-sqlite3 v1.14.47
github.com/pkg/errors v0.9.1
github.com/pressly/goose/v3 v3.30.1 github.com/pressly/goose/v3 v3.30.1
github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/isp-kit v1.76.0
isp-config-service v0.0.0-00010101000000-000000000000 isp-config-service v0.0.0-00010101000000-000000000000
-38
View File
@@ -15,28 +15,15 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/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 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI= 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 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gabriel-vasile/mimetype v1.4.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 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4= 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 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8= 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.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 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
@@ -57,9 +44,6 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.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 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU= github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
@@ -78,9 +62,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
github.com/klauspost/compress v1.19.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 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -117,40 +98,21 @@ github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL
github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= 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 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= 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.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 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM= 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 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= 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 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= 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 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA= 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 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= 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 h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/sethvargo/go-retry v0.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 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
-2
View File
@@ -9,8 +9,6 @@ grpcInnerAddress:
port: 9002 port: 9002
moduleName: isp-config-service moduleName: isp-config-service
enableSensitiveFieldConfigChecking: false
infraServerPort: 9006 infraServerPort: 9006
logLevel: debug logLevel: debug
-1
View File
@@ -15,7 +15,6 @@ type Local struct {
InternalClientCredential string `validate:"required"` InternalClientCredential string `validate:"required"`
Rqlite Rqlite Rqlite Rqlite
Backup rqlite.Backup Backup rqlite.Backup
EnableSensitiveFieldConfigChecking bool
} }
type Rqlite struct { type Rqlite struct {
+4 -53
View File
@@ -5,13 +5,12 @@ import (
"context" "context"
"strconv" "strconv"
"isp-config-service/domain"
"isp-config-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc"
"github.com/txix-open/isp-kit/grpc/apierrors" "github.com/txix-open/isp-kit/grpc/apierrors"
"google.golang.org/grpc/metadata" "google.golang.org/grpc/metadata"
"isp-config-service/domain"
"isp-config-service/entity"
) )
type ConfigService interface { type ConfigService interface {
@@ -23,7 +22,6 @@ type ConfigService interface {
DeleteConfig(ctx context.Context, id string) error DeleteConfig(ctx context.Context, id string) error
UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error UpdateConfigName(ctx context.Context, req domain.UpdateConfigNameRequest) error
SyncConfig(ctx context.Context, moduleName string) error SyncConfig(ctx context.Context, moduleName string) error
Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error)
} }
type Config struct { type Config struct {
@@ -186,24 +184,12 @@ func (c Config) GetConfigById(ctx context.Context, req domain.IdRequest) (*domai
// @Produce json // @Produce json
// @Param body body domain.IdRequest true "id конфигурации для изменения" // @Param body body domain.IdRequest true "id конфигурации для изменения"
// @Success 200 // @Success 200
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - конфигурация нарушает политику секретных переменных (детали по путям в `details`)<br/>" // @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} apierrors.Error
// @Router /config/mark_config_as_active [POST] // @Router /config/mark_config_as_active [POST]
func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.IdRequest) error { func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.IdRequest) error {
err := c.service.MarkConfigAsActive(ctx, identity.Id) err := c.service.MarkConfigAsActive(ctx, identity.Id)
var validationError domain.ConfigValidationError
switch { 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): case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError( return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound, domain.ErrorCodeConfigNotFound,
@@ -286,56 +272,21 @@ func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNam
// @Produce json // @Produce json
// @Param body body domain.SyncConfigRequest true "название модуля" // @Param body body domain.SyncConfigRequest true "название модуля"
// @Success 200 {object} domain.Config // @Success 200 {object} domain.Config
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - в UI-экспонируемых полях активная конфигурация ссылается на секретную переменную" // @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден"
// @Failure 500 {object} apierrors.Error // @Failure 500 {object} apierrors.Error
// @Router /config/sync_config [POST] // @Router /config/sync_config [POST]
func (c Config) SyncConfig(ctx context.Context, req domain.SyncConfigRequest) error { func (c Config) SyncConfig(ctx context.Context, req domain.SyncConfigRequest) error {
err := c.service.SyncConfig(ctx, req.ModuleName) err := c.service.SyncConfig(ctx, req.ModuleName)
var validationError domain.ConfigValidationError
switch { 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): case errors.Is(err, entity.ErrModuleNotFound):
return apierrors.NewBusinessError( return apierrors.NewBusinessError(
domain.ErrorCodeModuleNotFound, domain.ErrorCodeModuleNotFound,
"module not found", "module not found",
err, err,
) )
case errors.Is(err, entity.ErrConfigNotFound):
return apierrors.NewBusinessError(
domain.ErrorCodeConfigNotFound,
"config not found",
err,
)
case err != nil: case err != nil:
return apierrors.NewInternalServiceError(err) return apierrors.NewInternalServiceError(err)
default: default:
return nil 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 -28
View File
@@ -2,11 +2,6 @@ package controller
import ( import (
"context" "context"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/helpers"
"github.com/txix-open/isp-kit/grpc/apierrors"
"github.com/txix-open/etp/v4" "github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/msg" "github.com/txix-open/etp/v4/msg"
@@ -14,6 +9,7 @@ import (
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
"isp-config-service/helpers"
) )
var ( var (
@@ -39,7 +35,6 @@ type ModuleService interface {
conn *etp.Conn, conn *etp.Conn,
data cluster.ConfigData, data cluster.ConfigData,
) error ) error
Audit(ctx context.Context, moduleName string) ([]domain.AuditViolation, error)
} }
type Module struct { type Module struct {
@@ -54,28 +49,6 @@ 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) { func (m Module) OnConnect(conn *etp.Conn) {
ctx := conn.HttpRequest().Context() ctx := conn.HttpRequest().Context()
err := conn.HttpRequest().ParseForm() err := conn.HttpRequest().ParseForm()
+2 -52
View File
@@ -7,24 +7,6 @@ definitions:
port: port:
type: string type: string
type: object 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: domain.Config:
properties: properties:
active: active:
@@ -372,35 +354,6 @@ info:
title: isp-config-service title: isp-config-service
version: 3.0.0 version: 3.0.0
paths: 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: /config/create_update_config:
post: post:
consumes: consumes:
@@ -640,9 +593,7 @@ paths:
"200": "200":
description: OK description: OK
"400": "400":
description: '`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` description: '`errorCode: 2002` - конфиг не найден<br/>'
- конфигурация нарушает политику секретных переменных (детали по путям
в `details`)<br/>'
schema: schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error' $ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500": "500":
@@ -706,8 +657,7 @@ paths:
$ref: '#/definitions/domain.Config' $ref: '#/definitions/domain.Config'
"400": "400":
description: '`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` description: '`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002`
- конфиг не найден<br/>`errorCode: 2003` - в UI-экспонируемых полях активная - конфиг не найден'
конфигурация ссылается на секретную переменную'
schema: schema:
$ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error' $ref: '#/definitions/github_com_txix-open_isp-kit_grpc_apierrors.Error'
"500": "500":
-4
View File
@@ -21,10 +21,6 @@ type GetByModuleNameRequest struct {
ModuleName string `validate:"required"` ModuleName string `validate:"required"`
} }
type AuditRequest struct {
ModuleName string
}
type UpdateSchemaRequest struct { type UpdateSchemaRequest struct {
ModuleName string `validate:"required"` ModuleName string `validate:"required"`
Schema json.RawMessage `validate:"required" swaggertype:"object"` Schema json.RawMessage `validate:"required" swaggertype:"object"`
-7
View File
@@ -10,13 +10,6 @@ type DeleteResponse struct {
Deleted int Deleted int
} }
type AuditViolation struct {
Module string
Path string
Variables []string
Reason string
}
type CreateUpdateConfigResponse struct { type CreateUpdateConfigResponse struct {
Config Config
+1 -8
View File
@@ -5,17 +5,10 @@ import (
"isp-config-service/entity/xtypes" "isp-config-service/entity/xtypes"
) )
type VariableType = string
const (
SecretType VariableType = "SECRET"
TextType VariableType = "TEXT"
)
type Variable struct { type Variable struct {
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description"` Description string `json:"description"`
Type VariableType `json:"type"` Type string `json:"type"`
Value string `json:"value"` Value string `json:"value"`
CreatedAt xtypes.Time `json:"created_at"` CreatedAt xtypes.Time `json:"created_at"`
UpdatedAt xtypes.Time `json:"updated_at"` UpdatedAt xtypes.Time `json:"updated_at"`
+2 -2
View File
@@ -17,10 +17,9 @@ require (
github.com/rqlite/rqlite/v10 v10.2.7 github.com/rqlite/rqlite/v10 v10.2.7
github.com/stretchr/testify v1.12.1 github.com/stretchr/testify v1.12.1
github.com/tidwall/gjson v1.18.0 github.com/tidwall/gjson v1.18.0
github.com/txix-open/bellows v1.2.0
github.com/txix-open/etp/v4 v4.1.3 github.com/txix-open/etp/v4 v4.1.3
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60 github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60
github.com/txix-open/isp-kit v1.78.0 github.com/txix-open/isp-kit v1.76.0
github.com/xeipuuv/gojsonschema v1.2.0 github.com/xeipuuv/gojsonschema v1.2.0
golang.org/x/sync v0.25.0 golang.org/x/sync v0.25.0
google.golang.org/grpc v1.85.0 google.golang.org/grpc v1.85.0
@@ -93,6 +92,7 @@ require (
github.com/sethvargo/go-retry v0.5.0 // indirect github.com/sethvargo/go-retry v0.5.0 // indirect
github.com/tidwall/match v1.2.0 // indirect github.com/tidwall/match v1.2.0 // indirect
github.com/tidwall/pretty v1.2.1 // 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/jsonschema v1.3.0 // indirect
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // indirect
github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
+2 -2
View File
@@ -279,8 +279,8 @@ github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60 h1:7SZ72lNU69g8ei
github.com/txix-open/go-cmp v0.0.0-20240401171944-16b203530f60/go.mod h1:jzpq0uwcdGq0OSNXZ6vv6UJkCOU/fLPgeoz+KkGDYgo= 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 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE= github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
github.com/txix-open/isp-kit v1.78.0 h1:EV1sR3FxHiCskNVijptPtUZ3t9hJ83OiCkLI42LnjcM= github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
github.com/txix-open/isp-kit v1.78.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M= github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4= github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00= github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs= github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
+2 -32
View File
@@ -5,12 +5,11 @@ import (
"database/sql" "database/sql"
"strings" "strings"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/entity" "isp-config-service/entity"
"isp-config-service/middlewares/sql_metrics" "isp-config-service/middlewares/sql_metrics"
"isp-config-service/service/rqlite/db" "isp-config-service/service/rqlite/db"
"github.com/Masterminds/squirrel"
"github.com/txix-open/isp-kit/errors"
) )
type Variable struct { type Variable struct {
@@ -67,35 +66,6 @@ func (r Variable) GetByName(ctx context.Context, name string) (*entity.Variable,
return &result, nil 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 { func (r Variable) Insert(ctx context.Context, variable entity.Variable) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert") ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert")
-5
View File
@@ -116,11 +116,6 @@ func configsDescriptors(c Controllers) []cluster.EndpointDescriptor {
Inner: true, Inner: true,
Extra: cluster.RequireAdminPermission("module_view"), Extra: cluster.RequireAdminPermission("module_view"),
Handler: c.ConfigApi.GetConfigsByModuleId, 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", Path: "config/config/create_update_config",
Inner: true, Inner: true,
+91 -141
View File
@@ -4,16 +4,15 @@ import (
"context" "context"
"time" "time"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/txix-open/go-cmp/cmp" "github.com/txix-open/go-cmp/cmp"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
"github.com/xeipuuv/gojsonschema" "github.com/xeipuuv/gojsonschema"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
) )
type ConfigRepo interface { type ConfigRepo interface {
@@ -40,15 +39,9 @@ type VariableService interface {
SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error 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 { type Config struct {
configRepo ConfigRepo configRepo ConfigRepo
moduleRepo ModuleRepo moduleRepo ModuleRepo
moduleService ModuleService
schemaRepo SchemaRepo schemaRepo SchemaRepo
eventRepo EventRepo eventRepo EventRepo
configHistoryService ConfigHistoryService configHistoryService ConfigHistoryService
@@ -59,7 +52,6 @@ type Config struct {
func NewConfig( func NewConfig(
configRepo ConfigRepo, configRepo ConfigRepo,
moduleRepo ModuleRepo, moduleRepo ModuleRepo,
moduleService ModuleService,
schemaRepo SchemaRepo, schemaRepo SchemaRepo,
eventRepo EventRepo, eventRepo EventRepo,
configHistoryService ConfigHistoryService, configHistoryService ConfigHistoryService,
@@ -69,7 +61,6 @@ func NewConfig(
return Config{ return Config{
configRepo: configRepo, configRepo: configRepo,
moduleRepo: moduleRepo, moduleRepo: moduleRepo,
moduleService: moduleService,
schemaRepo: schemaRepo, schemaRepo: schemaRepo,
eventRepo: eventRepo, eventRepo: eventRepo,
configHistoryService: configHistoryService, configHistoryService: configHistoryService,
@@ -130,13 +121,8 @@ func (c Config) CreateUpdateConfig(
adminId int, adminId int,
req domain.CreateUpdateConfigRequest, req domain.CreateUpdateConfigRequest,
) (*domain.CreateUpdateConfigResponse, error) { ) (*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 { if !req.Unsafe {
err = c.validateConfigUpdate(ctx, req.ModuleId, req.Data) err := c.validateConfigUpdate(ctx, req.ModuleId, req.Data)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "validate config") return nil, errors.WithMessage(err, "validate config")
} }
@@ -148,123 +134,6 @@ func (c Config) CreateUpdateConfig(
Config: newConfig, IsChanged: true}, err 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) variableExtractionResult, err := c.extractAndCheckVariables(ctx, req.Id, req.Data)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "extract variables") return nil, errors.WithMessage(err, "extract variables")
@@ -330,6 +199,92 @@ func (c Config) updateConfig(ctx context.Context, adminId int, req domain.Create
Config: configToDto(newConfig, nil), IsChanged: true}, nil 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) { func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (domain.Config, error) {
config := entity.Config{ config := entity.Config{
Id: uuid.NewString(), Id: uuid.NewString(),
@@ -340,12 +295,7 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre
Active: false, Active: false,
AdminId: adminId, AdminId: adminId,
} }
// Check variables before insert so a config with missing variables is never persisted without links.
err := c.moduleService.FilterSecretParams(ctx, req.Data, req.ModuleId)
if err != nil {
return domain.Config{}, errors.WithMessage(err, "filter secret params")
}
extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data) extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data)
if err != nil { if err != nil {
return domain.Config{}, err return domain.Config{}, err
@@ -1,4 +1,4 @@
package tests_test package event_test
import ( import (
"testing" "testing"
@@ -9,30 +9,30 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
const eventTestModuleId = "test-module-id" const testModuleId = "test-module-id"
func TestCompactCollapsesModuleLifecycle(t *testing.T) { func TestCompactCollapsesModuleLifecycle(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
ready := entity.NewEvent(entity.EventPayload{ ready := entity.NewEvent(entity.EventPayload{
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId}, ModuleReady: &entity.PayloadModuleReady{ModuleId: testModuleId},
}) })
ready.Id = 1 ready.Id = 1
disconnected := entity.NewEvent(entity.EventPayload{ disconnected := entity.NewEvent(entity.EventPayload{
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId}, ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: testModuleId},
}) })
disconnected.Id = 2 disconnected.Id = 2
configUpdated := entity.NewEvent(entity.EventPayload{ configUpdated := entity.NewEvent(entity.EventPayload{
ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: eventTestModuleId}, ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: testModuleId},
}) })
configUpdated.Id = 3 configUpdated.Id = 3
require.Equal("module_lifecycle_"+eventTestModuleId, ready.Key()) require.Equal("module_lifecycle_"+testModuleId, ready.Key())
require.Equal("module_lifecycle_"+eventTestModuleId, disconnected.Key()) require.Equal("module_lifecycle_"+testModuleId, disconnected.Key())
require.Equal("config_updated_"+eventTestModuleId, configUpdated.Key()) require.Equal("config_updated_"+testModuleId, configUpdated.Key())
compacted := event.NewCompactor().Compact([]entity.Event{ready, disconnected, configUpdated}) compacted := event.NewCompactor().Compact([]entity.Event{ready, disconnected, configUpdated})
@@ -1,4 +1,4 @@
package tests_test package event_test
import ( import (
"context" "context"
@@ -31,23 +31,23 @@ func (s *subscriptionSpy) NotifyRoutingChanged(ctx context.Context) error {
return nil return nil
} }
type eventLoggerSpy struct { type loggerSpy struct {
errors []string errors []string
} }
func (l *eventLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) { func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {
l.errors = append(l.errors, fmt.Sprint(message)) l.errors = append(l.errors, fmt.Sprint(message))
} }
func (l *eventLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
func (l *eventLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
func (l *eventLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
func moduleReadyEvent(id int) entity.Event { func moduleReadyEvent(id int) entity.Event {
event := entity.NewEvent(entity.EventPayload{ event := entity.NewEvent(entity.EventPayload{
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId}, ModuleReady: &entity.PayloadModuleReady{ModuleId: testModuleId},
}) })
event.Id = id event.Id = id
return event return event
@@ -55,7 +55,7 @@ func moduleReadyEvent(id int) entity.Event {
func moduleDisconnectedEvent(id int) entity.Event { func moduleDisconnectedEvent(id int) entity.Event {
event := entity.NewEvent(entity.EventPayload{ event := entity.NewEvent(entity.EventPayload{
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId}, ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: testModuleId},
}) })
event.Id = id event.Id = id
return event return event
@@ -66,7 +66,7 @@ func TestHandleLifecycleBatchFansRoutingOnce(t *testing.T) {
require := require.New(t) require := require.New(t)
subscription := &subscriptionSpy{} subscription := &subscriptionSpy{}
logger := &eventLoggerSpy{} logger := &loggerSpy{}
handler := event.NewHandler(subscription, logger) handler := event.NewHandler(subscription, logger)
batch := event.NewCompactor().Compact([]entity.Event{ batch := event.NewCompactor().Compact([]entity.Event{
@@ -75,7 +75,7 @@ func TestHandleLifecycleBatchFansRoutingOnce(t *testing.T) {
}) })
handler.Handle(t.Context(), batch) handler.Handle(t.Context(), batch)
require.Equal([]string{eventTestModuleId}, subscription.backendsChanged, require.Equal([]string{testModuleId}, subscription.backendsChanged,
"ready and disconnected collapse into the newest lifecycle event") "ready and disconnected collapse into the newest lifecycle event")
require.Equal(1, subscription.routingCalls, "the routing map is broadcast once per batch") require.Equal(1, subscription.routingCalls, "the routing map is broadcast once per batch")
require.Empty(logger.errors) require.Empty(logger.errors)
@@ -86,7 +86,7 @@ func TestHandleUnknownEventDoesNotAbortBatch(t *testing.T) {
require := require.New(t) require := require.New(t)
subscription := &subscriptionSpy{} subscription := &subscriptionSpy{}
logger := &eventLoggerSpy{} logger := &loggerSpy{}
handler := event.NewHandler(subscription, logger) handler := event.NewHandler(subscription, logger)
unknown := entity.NewEvent(entity.EventPayload{}) unknown := entity.NewEvent(entity.EventPayload{})
@@ -95,7 +95,7 @@ func TestHandleUnknownEventDoesNotAbortBatch(t *testing.T) {
require.Len(logger.errors, 1) require.Len(logger.errors, 1)
require.Contains(logger.errors[0], "unknown event") require.Contains(logger.errors[0], "unknown event")
require.Equal([]string{eventTestModuleId}, subscription.backendsChanged, require.Equal([]string{testModuleId}, subscription.backendsChanged,
"an unknown payload kind must not stop the batch") "an unknown payload kind must not stop the batch")
require.Equal(1, subscription.routingCalls) require.Equal(1, subscription.routingCalls)
} }
-175
View File
@@ -1,175 +0,0 @@
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
@@ -1,320 +0,0 @@
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)
}
}
@@ -1,4 +1,4 @@
package tests_test package backend_test
import ( import (
"context" "context"
@@ -14,28 +14,28 @@ import (
) )
const ( const (
backendTestModuleName = "test-module" testModuleName = "test-module"
backendTestModuleId = "test-module-id" testModuleId = "test-module-id"
testConnId = "test-conn-id" testConnId = "test-conn-id"
testNodeId = "test-node-id" testNodeId = "test-node-id"
backendLeaderConnId = "conn-1" leaderConnId = "conn-1"
backendFollowerConnId = "conn-2" followerConnId = "conn-2"
backendLeaderAddress = "10.0.0.1:9000" leaderAddress = "10.0.0.1:9000"
followerAddress = "10.0.0.2:9000" followerAddress = "10.0.0.2:9000"
) )
type backendStoredLog struct { type storedLog struct {
message any message any
fields map[string]string fields map[string]string
} }
type backendLoggerSpy struct { type loggerSpy struct {
warns []backendStoredLog warns []storedLog
} }
func (l *backendLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) { func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {
entry := backendStoredLog{ entry := storedLog{
message: message, message: message,
fields: make(map[string]string, len(fields)), fields: make(map[string]string, len(fields)),
} }
@@ -45,11 +45,11 @@ func (l *backendLoggerSpy) Warn(ctx context.Context, message any, fields ...log.
l.warns = append(l.warns, entry) l.warns = append(l.warns, entry)
} }
func (l *backendLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
func (l *backendLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
func (l *backendLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
type backendRepoSpy struct { type backendRepoSpy struct {
upserted []entity.Backend upserted []entity.Backend
@@ -155,18 +155,18 @@ func TestConnectNormalizesModuleLeaderMode(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
logger := &backendLoggerSpy{} logger := &loggerSpy{}
backendRepo := &backendRepoSpy{} backendRepo := &backendRepoSpy{}
service := backend.NewBackend(backendRepo, &eventRepoSpy{}, testNodeId, nil, logger) service := backend.NewBackend(backendRepo, &eventRepoSpy{}, testNodeId, nil, logger)
declaration := cluster.BackendDeclaration{ declaration := cluster.BackendDeclaration{
ModuleName: backendTestModuleName, ModuleName: testModuleName,
Version: "1.0.0", Version: "1.0.0",
LibVersion: "1.0.0", LibVersion: "1.0.0",
Address: cluster.AddressConfiguration{IP: "10.0.0.1", Port: "9000"}, Address: cluster.AddressConfiguration{IP: "10.0.0.1", Port: "9000"},
ModuleLeaderMode: tt.announcedMode, ModuleLeaderMode: tt.announcedMode,
} }
connected, err := service.Connect(t.Context(), testConnId, backendTestModuleId, declaration) connected, err := service.Connect(t.Context(), testConnId, testModuleId, declaration)
require.NoError(err) require.NoError(err)
require.Len(backendRepo.upserted, 1) require.Len(backendRepo.upserted, 1)
@@ -179,7 +179,7 @@ func TestConnectNormalizesModuleLeaderMode(t *testing.T) {
} }
require.Len(logger.warns, 1) require.Len(logger.warns, 1)
require.Equal(backendTestModuleName, logger.warns[0].fields["moduleName"]) require.Equal(testModuleName, logger.warns[0].fields["moduleName"])
require.Equal(tt.announcedMode, logger.warns[0].fields["moduleLeaderMode"]) require.Equal(tt.announcedMode, logger.warns[0].fields["moduleLeaderMode"])
}) })
} }
@@ -190,20 +190,20 @@ func TestConnectInsertsOnlyLifecycleEvent(t *testing.T) {
require := require.New(t) require := require.New(t)
events := &eventRepoSpy{} events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy(backendElectedInstance(backendLeaderConnId, backendLeaderAddress)) backendRepo := newBackendRepoSpy(electedInstance(leaderConnId, leaderAddress))
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{}) service := backend.NewBackend(backendRepo, events, testNodeId, nil, &loggerSpy{})
declaration := cluster.BackendDeclaration{ declaration := cluster.BackendDeclaration{
ModuleName: backendTestModuleName, ModuleName: testModuleName,
Address: cluster.AddressConfiguration{IP: "10.0.0.2", Port: "9000"}, Address: cluster.AddressConfiguration{IP: "10.0.0.2", Port: "9000"},
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection, ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
} }
_, err := service.Connect(t.Context(), backendFollowerConnId, backendTestModuleId, declaration) _, err := service.Connect(t.Context(), followerConnId, testModuleId, declaration)
require.NoError(err) require.NoError(err)
require.Equal([]string{"upsert"}, backendRepo.calls, require.Equal([]string{"upsert"}, backendRepo.calls,
"the connect path elects nobody: the leader is derived where the address list is emitted") "the connect path elects nobody: the leader is derived where the address list is emitted")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events), require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
"one lifecycle event per connect, no dedicated leader event") "one lifecycle event per connect, no dedicated leader event")
} }
@@ -213,21 +213,21 @@ func TestDisconnectInsertsOnlyLifecycleEvent(t *testing.T) {
events := &eventRepoSpy{} events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy( backendRepo := newBackendRepoSpy(
backendElectedInstance(backendLeaderConnId, backendLeaderAddress), electedInstance(leaderConnId, leaderAddress),
backendElectedInstance(backendFollowerConnId, followerAddress), electedInstance(followerConnId, followerAddress),
) )
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{}) service := backend.NewBackend(backendRepo, events, testNodeId, nil, &loggerSpy{})
err := service.Disconnect(t.Context(), entity.Backend{ err := service.Disconnect(t.Context(), entity.Backend{
WsConnectionId: backendLeaderConnId, WsConnectionId: leaderConnId,
ModuleId: backendTestModuleId, ModuleId: testModuleId,
ModuleName: backendTestModuleName, ModuleName: testModuleName,
}) })
require.NoError(err) require.NoError(err)
require.Equal([]string{"delete"}, backendRepo.calls, require.Equal([]string{"delete"}, backendRepo.calls,
"the disconnect path elects nobody") "the disconnect path elects nobody")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events), require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
"one lifecycle event per disconnect, no dedicated leader event") "one lifecycle event per disconnect, no dedicated leader event")
} }
@@ -237,10 +237,10 @@ func TestClearPhantomBackendsInsertsOneLifecycleEventPerModule(t *testing.T) {
events := &eventRepoSpy{} events := &eventRepoSpy{}
backendRepo := newBackendRepoSpy( backendRepo := newBackendRepoSpy(
backendElectedInstance(backendLeaderConnId, backendLeaderAddress), electedInstance(leaderConnId, leaderAddress),
backendElectedInstance(backendFollowerConnId, followerAddress), electedInstance(followerConnId, followerAddress),
) )
service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &backendLoggerSpy{}) service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &loggerSpy{})
deleted, err := service.ClearPhantomBackends(t.Context()) deleted, err := service.ClearPhantomBackends(t.Context())
@@ -248,7 +248,7 @@ func TestClearPhantomBackendsInsertsOneLifecycleEventPerModule(t *testing.T) {
require.Equal(2, deleted) require.Equal(2, deleted)
require.Equal([]string{"own_node", "delete"}, backendRepo.calls, require.Equal([]string{"own_node", "delete"}, backendRepo.calls,
"the cleanup deletes and announces, it elects nobody") "the cleanup deletes and announces, it elects nobody")
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, eventKeys(events), require.Equal([]string{"module_lifecycle_" + testModuleId}, eventKeys(events),
"the instances of one module are announced once") "the instances of one module are announced once")
} }
@@ -257,18 +257,18 @@ func TestDeleteOwnBackendsInsertsNoEvents(t *testing.T) {
require := require.New(t) require := require.New(t)
events := &eventRepoSpy{} events := &eventRepoSpy{}
service := backend.NewBackend(newBackendRepoSpy(), events, testNodeId, nil, &backendLoggerSpy{}) service := backend.NewBackend(newBackendRepoSpy(), events, testNodeId, nil, &loggerSpy{})
service.DeleteOwnBackends(t.Context()) service.DeleteOwnBackends(t.Context())
require.Empty(events.inserted, "graceful shutdown inserts no events at all") require.Empty(events.inserted, "graceful shutdown inserts no events at all")
} }
func backendElectedInstance(connId string, address string) entity.Backend { func electedInstance(connId string, address string) entity.Backend {
return entity.Backend{ return entity.Backend{
WsConnectionId: connId, WsConnectionId: connId,
ModuleId: backendTestModuleId, ModuleId: testModuleId,
ModuleName: backendTestModuleName, ModuleName: testModuleName,
Address: address, Address: address,
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection, ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
} }
@@ -1,4 +1,4 @@
package tests_test package leader_test
import ( import (
"slices" "slices"
-68
View File
@@ -1,68 +0,0 @@
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
@@ -1,160 +0,0 @@
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
@@ -1,73 +0,0 @@
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
@@ -1,213 +0,0 @@
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)
}
}
+42 -227
View File
@@ -4,23 +4,18 @@ import (
"context" "context"
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"fmt"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/helpers"
"maps"
"sort"
"strings" "strings"
"github.com/txix-open/isp-kit/json"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/txix-open/etp/v4" "github.com/txix-open/etp/v4"
"github.com/txix-open/etp/v4/store" "github.com/txix-open/etp/v4/store"
"github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/cluster"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/helpers"
) )
const ( const (
@@ -34,7 +29,6 @@ type Repo interface {
ctx context.Context, ctx context.Context,
moduleId string, moduleId string,
) error ) error
All(ctx context.Context) ([]entity.Module, error)
} }
type BackendService interface { type BackendService interface {
@@ -44,7 +38,6 @@ type BackendService interface {
type ConfigSchemaRepo interface { type ConfigSchemaRepo interface {
Upsert(ctx context.Context, schema entity.ConfigSchema) error Upsert(ctx context.Context, schema entity.ConfigSchema) error
GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error)
} }
type ConfigRepo interface { type ConfigRepo interface {
@@ -52,12 +45,8 @@ type ConfigRepo interface {
GetActive(ctx context.Context, moduleId string) (*entity.Config, error) 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 { type VariableService interface {
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) RenderConfig(ctx context.Context, input []byte) ([]byte, error)
ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error)
SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error
} }
@@ -76,8 +65,6 @@ type Service struct {
subscriptionService SubscriptionService subscriptionService SubscriptionService
emitter Emitter emitter Emitter
variableService VariableService variableService VariableService
variableRepo VariableRepo
enableSensitiveFieldConfigChecking bool
logger log.Logger logger log.Logger
} }
@@ -89,8 +76,6 @@ func NewService(
subscriptionService SubscriptionService, subscriptionService SubscriptionService,
emitter Emitter, emitter Emitter,
variableService VariableService, variableService VariableService,
variableRepo VariableRepo,
enableSensitiveFieldConfigChecking bool,
logger log.Logger, logger log.Logger,
) Service { ) Service {
return Service{ return Service{
@@ -101,8 +86,6 @@ func NewService(
subscriptionService: subscriptionService, subscriptionService: subscriptionService,
emitter: emitter, emitter: emitter,
variableService: variableService, variableService: variableService,
variableRepo: variableRepo,
enableSensitiveFieldConfigChecking: enableSensitiveFieldConfigChecking,
logger: logger, logger: logger,
} }
} }
@@ -229,6 +212,43 @@ func (s Service) OnModuleConfigSchema(
if err != nil { if err != nil {
return errors.WithMessage(err, "get active config") 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),
}
result, err := s.variableService.ExtractVariables(ctx, initialConfig.Id, initialConfig.Data)
if err != nil {
return errors.WithMessage(err, "extract variables from initial config")
}
if len(result.AbsentVariables) > 0 {
return errors.Errorf("missing variables in initial config: [%s]", strings.Join(result.AbsentVariables, ","))
}
err = s.configRepo.Insert(ctx, initialConfig)
if err != nil {
return errors.WithMessage(err, "insert config in store")
}
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{ configSchema := entity.ConfigSchema{
Id: uuid.NewString(), Id: uuid.NewString(),
@@ -241,21 +261,6 @@ func (s Service) OnModuleConfigSchema(
return errors.WithMessage(err, "upsert config schema in store") 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 return nil
} }
@@ -263,193 +268,3 @@ func idByKey(key string) string {
hash := sha256.Sum256([]byte(key)) hash := sha256.Sum256([]byte(key))
return hex.EncodeToString(hash[:]) return hex.EncodeToString(hash[:])
} }
func (s Service) FilterSecretParams(ctx context.Context, config json.RawMessage, moduleId string) error {
if !s.enableSensitiveFieldConfigChecking {
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
}
+2 -2
View File
@@ -32,7 +32,7 @@ type ConfigRepo interface {
} }
type VariableService interface { type VariableService interface {
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) RenderConfig(ctx context.Context, input []byte) ([]byte, error)
} }
type Emitter interface { type Emitter interface {
@@ -84,7 +84,7 @@ func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error
if err != nil { if err != nil {
return errors.WithMessage(err, "get active config") return errors.WithMessage(err, "get active config")
} }
configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data) configData, err := s.variableService.RenderConfig(ctx, config.Data)
if err != nil { if err != nil {
return errors.WithMessage(err, "render config") return errors.WithMessage(err, "render config")
} }
@@ -1,4 +1,4 @@
package tests_test package subscription_test
import ( import (
"context" "context"
@@ -14,28 +14,28 @@ import (
) )
const ( const (
subscriptionTestModuleId = "test-module-id" testModuleId = "test-module-id"
subscriptionTestModuleName = "test-module" testModuleName = "test-module"
subscriptionLeaderConnId = "conn-1" leaderConnId = "conn-1"
subscriptionFollowerConnId = "conn-2" followerConnId = "conn-2"
subscriptionLeaderAddress = "10.0.0.1:9000" leaderAddress = "10.0.0.1:9000"
successorAddress = "10.0.0.2:9000" successorAddress = "10.0.0.2:9000"
plainAddress = "10.0.0.3:9000" plainAddress = "10.0.0.3:9000"
) )
type subscriptionStoredLog struct { type storedLog struct {
message any message any
fields map[string]string fields map[string]string
} }
type subscriptionLoggerSpy struct { type loggerSpy struct {
infos []subscriptionStoredLog infos []storedLog
} }
func (l *subscriptionLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) { func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {
entry := subscriptionStoredLog{ entry := storedLog{
message: message, message: message,
fields: make(map[string]string, len(fields)), fields: make(map[string]string, len(fields)),
} }
@@ -45,32 +45,32 @@ func (l *subscriptionLoggerSpy) Info(ctx context.Context, message any, fields ..
l.infos = append(l.infos, entry) l.infos = append(l.infos, entry)
} }
func (l *subscriptionLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
func (l *subscriptionLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
func (l *subscriptionLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {} func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
type moduleRepoSpy struct{} type moduleRepoSpy struct{}
func (r *moduleRepoSpy) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) { func (r *moduleRepoSpy) GetByNames(ctx context.Context, names []string) ([]entity.Module, error) {
return []entity.Module{{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}}, nil return []entity.Module{{Id: testModuleId, Name: testModuleName}}, nil
} }
func (r *moduleRepoSpy) GetById(ctx context.Context, id string) (*entity.Module, error) { func (r *moduleRepoSpy) GetById(ctx context.Context, id string) (*entity.Module, error) {
return &entity.Module{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}, nil return &entity.Module{Id: testModuleId, Name: testModuleName}, nil
} }
type subscriptionBackendRepoSpy struct { type backendRepoSpy struct {
forLeaderElection []entity.Backend forLeaderElection []entity.Backend
all []entity.Backend all []entity.Backend
} }
func (r *subscriptionBackendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) { func (r *backendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
return r.forLeaderElection, nil return r.forLeaderElection, nil
} }
func (r *subscriptionBackendRepoSpy) All(ctx context.Context) ([]entity.Backend, error) { func (r *backendRepoSpy) All(ctx context.Context) ([]entity.Backend, error) {
return r.all, nil return r.all, nil
} }
@@ -82,7 +82,7 @@ func (r *configRepoSpy) GetActive(ctx context.Context, moduleId string) (*entity
type variableServiceSpy struct{} type variableServiceSpy struct{}
func (s *variableServiceSpy) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) { func (s *variableServiceSpy) RenderConfig(ctx context.Context, input []byte) ([]byte, error) {
return input, nil return input, nil
} }
@@ -96,23 +96,23 @@ func TestNotifyBackendsChangedLogsTheLeaderItPublishes(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
logger := &subscriptionLoggerSpy{} logger := &loggerSpy{}
rooms := etp.NewServer().Rooms() rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(subscriptionTestModuleName)) rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(testModuleName))
service := newService(logger, rooms, &subscriptionBackendRepoSpy{ service := newService(logger, rooms, &backendRepoSpy{
forLeaderElection: []entity.Backend{ forLeaderElection: []entity.Backend{
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress), electedInstance(leaderConnId, leaderAddress),
subscriptionElectedInstance(subscriptionFollowerConnId, successorAddress), electedInstance(followerConnId, successorAddress),
}, },
}) })
err := service.NotifyBackendsChanged(t.Context(), subscriptionTestModuleId) err := service.NotifyBackendsChanged(t.Context(), testModuleId)
require.NoError(err) require.NoError(err)
require.Len(logger.infos, 1) require.Len(logger.infos, 1)
require.Equal("module address list narrowed to the leader", logger.infos[0].message) require.Equal("module address list narrowed to the leader", logger.infos[0].message)
require.Equal(subscriptionTestModuleName, logger.infos[0].fields["moduleName"]) require.Equal(testModuleName, logger.infos[0].fields["moduleName"])
require.Equal(subscriptionLeaderAddress, logger.infos[0].fields["leaderAddress"], require.Equal(leaderAddress, logger.infos[0].fields["leaderAddress"],
"the logged leader is the oldest elected instance, the one the subscriber received") "the logged leader is the oldest elected instance, the one the subscriber received")
} }
@@ -120,13 +120,13 @@ func TestNotifyRoutingChangedLogsPublishedLeaders(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
logger := &subscriptionLoggerSpy{} logger := &loggerSpy{}
rooms := etp.NewServer().Rooms() rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom()) rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
service := newService(logger, rooms, &subscriptionBackendRepoSpy{ service := newService(logger, rooms, &backendRepoSpy{
all: []entity.Backend{ all: []entity.Backend{
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress), electedInstance(leaderConnId, leaderAddress),
subscriptionElectedInstance(subscriptionFollowerConnId, successorAddress), electedInstance(followerConnId, successorAddress),
plainInstance("conn-3", plainAddress), plainInstance("conn-3", plainAddress),
}, },
}) })
@@ -136,7 +136,7 @@ func TestNotifyRoutingChangedLogsPublishedLeaders(t *testing.T) {
require.NoError(err) require.NoError(err)
require.Len(logger.infos, 1, "one summary line per routing rebuild") require.Len(logger.infos, 1, "one summary line per routing rebuild")
require.Equal("routing map publishes module leaders", logger.infos[0].message) require.Equal("routing map publishes module leaders", logger.infos[0].message)
require.Equal(subscriptionTestModuleName+"="+subscriptionLeaderAddress, logger.infos[0].fields["moduleLeaders"], require.Equal(testModuleName+"="+leaderAddress, logger.infos[0].fields["moduleLeaders"],
"only the elected module and only its leader are published, the plain module is not listed") "only the elected module and only its leader are published, the plain module is not listed")
} }
@@ -144,10 +144,10 @@ func TestNotifyRoutingChangedWithoutElectionLogsNothing(t *testing.T) {
t.Parallel() t.Parallel()
require := require.New(t) require := require.New(t)
logger := &subscriptionLoggerSpy{} logger := &loggerSpy{}
rooms := etp.NewServer().Rooms() rooms := etp.NewServer().Rooms()
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom()) rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
service := newService(logger, rooms, &subscriptionBackendRepoSpy{ service := newService(logger, rooms, &backendRepoSpy{
all: []entity.Backend{plainInstance("conn-3", plainAddress)}, all: []entity.Backend{plainInstance("conn-3", plainAddress)},
}) })
@@ -157,11 +157,11 @@ func TestNotifyRoutingChangedWithoutElectionLogsNothing(t *testing.T) {
require.Empty(logger.infos, "modules without election keep the previous behaviour, including the log") require.Empty(logger.infos, "modules without election keep the previous behaviour, including the log")
} }
func subscriptionElectedInstance(connId string, address string) entity.Backend { func electedInstance(connId string, address string) entity.Backend {
return entity.Backend{ return entity.Backend{
WsConnectionId: connId, WsConnectionId: connId,
ModuleId: subscriptionTestModuleId, ModuleId: testModuleId,
ModuleName: subscriptionTestModuleName, ModuleName: testModuleName,
Address: address, Address: address,
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection, ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
} }
-86
View File
@@ -1,86 +0,0 @@
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
}
+25 -53
View File
@@ -2,16 +2,14 @@ package variable
import ( import (
"context" "context"
"regexp"
"strings" "strings"
"time" "time"
"github.com/txix-open/isp-kit/errors"
"isp-config-service/domain" "isp-config-service/domain"
"isp-config-service/entity" "isp-config-service/entity"
"isp-config-service/entity/xtypes" "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 { type Repo interface {
@@ -32,31 +30,25 @@ type EventRepo interface {
Insert(ctx context.Context, event entity.Event) error Insert(ctx context.Context, event entity.Event) error
} }
type SchemaRepo interface {
GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error)
}
type Service struct { type Service struct {
repo Repo repo Repo
configRepo ConfigRepo configRepo ConfigRepo
eventRepo EventRepo eventRepo EventRepo
schemaRepo SchemaRepo stringToIntRegexp *regexp.Regexp
logger log.Logger variableRegexp *regexp.Regexp
} }
func NewService( func NewService(
repo Repo, repo Repo,
configRepo ConfigRepo, configRepo ConfigRepo,
eventRepo EventRepo, eventRepo EventRepo,
schemaRepo SchemaRepo,
logger log.Logger,
) Service { ) Service {
return Service{ return Service{
repo: repo, repo: repo,
configRepo: configRepo, configRepo: configRepo,
eventRepo: eventRepo, eventRepo: eventRepo,
schemaRepo: schemaRepo, stringToIntRegexp: regexp.MustCompile(`"_ToInt\((\d+)\)"`),
logger: logger, variableRegexp: regexp.MustCompile(`_Var\((.*?)\)`),
} }
} }
@@ -188,7 +180,7 @@ func (s Service) Delete(ctx context.Context, name string) error {
} }
//nolint:funlen //nolint:funlen
func (s Service) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) { func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) {
variables, err := s.repo.All(ctx) variables, err := s.repo.All(ctx)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "get all variables") return nil, errors.WithMessage(err, "get all variables")
@@ -196,37 +188,33 @@ func (s Service) RenderConfig(ctx context.Context, moduleId string, input []byte
if len(variables) == 0 { if len(variables) == 0 {
return input, nil return input, nil
} }
varsMap := make(map[string]entity.Variable, len(variables)) varsMap := make(map[string]string, len(variables))
for _, variable := range variables { for _, variable := range variables {
varsMap[variable.Name] = variable varsMap[variable.Name] = variable.Value
} }
uiPaths, err := s.uiPaths(ctx, moduleId) undefinedVariables := make([]string, 0)
if err != nil { withReplacedVars := s.variableRegexp.ReplaceAllStringFunc(string(input), func(group string) string {
return nil, err 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, ", "))
} }
out, skipped, undefined, err := Render(input, uiPaths, varsMap) result := s.stringToIntRegexp.ReplaceAll([]byte(withReplacedVars), []byte("$1"))
if err != nil {
return nil, errors.WithMessage(err, "render config")
}
if len(undefined) > 0 {
return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefined, ", "))
}
for _, ref := range skipped { return result, nil
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) { func (s Service) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) {
matches := variableRefPattern.FindAllStringSubmatch(string(input), -1) matches := s.variableRegexp.FindAllStringSubmatch(string(input), -1)
seen := make(map[string]bool, len(matches)) seen := make(map[string]bool, len(matches))
varNames := make([]string, 0, len(matches)) varNames := make([]string, 0, len(matches))
for _, match := range matches { for _, match := range matches {
@@ -281,22 +269,6 @@ func (s Service) SaveVariableLinks(ctx context.Context, configId string, links [
return nil 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 { func (s Service) toDto(variable entity.Variable, metaByVariables map[string][]entity.ConfigMetaWithVariable) domain.Variable {
value := variable.Value value := variable.Value
if variable.Type == "SECRET" { if variable.Type == "SECRET" {
+2 -3
View File
@@ -214,9 +214,8 @@ func setupTestApp(t *testing.T) (*require.Assertions, log.Logger, db.DB) {
boot := bootstrap.New("1.0.0", conf.Remote{}, nil, cluster.GrpcTransport) boot := bootstrap.New("1.0.0", conf.Remote{}, nil, cluster.GrpcTransport)
boot.MigrationsDir = "../migrations" boot.MigrationsDir = "../migrations"
dataPath := dataDir(t) dataPath := dataDir(t)
boot.App.Config().Set("rqlite.datapath", dataPath) boot.App.Config().Set("rqlite.DataPath", dataPath)
boot.App.Config().Set("backup.enable", false) boot.App.Config().Set("backup.Enable", false)
boot.App.Config().Set("enablesensitivefieldconfigchecking", true)
logger := boot.App.Logger() logger := boot.App.Logger()
startup, err := startup.New(boot) startup, err := startup.New(boot)
-106
View File
@@ -1,106 +0,0 @@
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)
}
+2 -3
View File
@@ -95,9 +95,8 @@ func setupTestWithAppRun(t *testing.T) (*require.Assertions, log.Logger) {
boot := bootstrap.New("1.0.0", conf.Remote{}, nil, cluster.GrpcTransport) boot := bootstrap.New("1.0.0", conf.Remote{}, nil, cluster.GrpcTransport)
boot.MigrationsDir = "../migrations" boot.MigrationsDir = "../migrations"
dataPath := dataDir(t) dataPath := dataDir(t)
boot.App.Config().Set("rqlite.datapath", dataPath) boot.App.Config().Set("rqlite.DataPath", dataPath)
boot.App.Config().Set("backup.enable", false) boot.App.Config().Set("backup.Enable", false)
boot.App.Config().Set("enablesensitivefieldconfigchecking", true)
logger := boot.App.Logger() logger := boot.App.Logger()
startup, err := startup.New(boot) startup, err := startup.New(boot)
-251
View File
@@ -1,251 +0,0 @@
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
@@ -1,86 +0,0 @@
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
@@ -1,281 +0,0 @@
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)
}
-422
View File
@@ -1,422 +0,0 @@
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)
}
}