Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a70a9477b2 | ||
|
|
cf57714d14 | ||
|
|
5f3e86f831 | ||
|
|
5c81d58dff | ||
|
|
8d14d4c187 | ||
|
|
0cf9de5629 | ||
|
|
3a191331a7 | ||
|
|
861ffc9d05 | ||
|
|
2a37ec39fa | ||
|
|
4173e21a06 | ||
|
|
cdf700b062 | ||
|
|
f7a141d25e | ||
|
|
6731fc6b93 | ||
|
|
d45f814d6a | ||
|
|
1ff499ace3 | ||
|
|
b481c2a45e | ||
|
|
dde6c49b92 | ||
|
|
9a66bd060a | ||
|
|
d669c65038 | ||
|
|
c9ee296835 | ||
|
|
53dff62759 | ||
|
|
439e6f5ebf | ||
|
|
a8a475435c | ||
|
|
b36cb1cd0e | ||
|
|
06ec2c6a87 | ||
|
|
45d7ea443f | ||
|
|
2bb06ffb8e | ||
|
|
45de1d1b12 | ||
|
|
6cd0b2c712 | ||
|
|
3d04dd2df7 | ||
|
|
6cfa1955ea | ||
|
|
9e24122e75 | ||
|
|
71997dc438 | ||
|
|
bd8a1b2de4 | ||
|
|
7b0108a358 | ||
|
|
a195c76799 | ||
|
|
780c2232fb | ||
|
|
ef0978e064 | ||
|
|
c464393e93 | ||
|
|
7f4e3ef028 | ||
|
|
5c8a554d4f | ||
|
|
5bdb4813b5 | ||
|
|
17ec4bdce9 | ||
|
|
428de36857 | ||
|
|
fc9c4f956f | ||
|
|
44961d8416 | ||
|
|
2a846c67e4 | ||
|
|
481f06bfec | ||
|
|
3b99380a62 | ||
|
|
ffa09db7b2 | ||
|
|
94af308030 | ||
|
|
36e320af28 | ||
|
|
c2d7aea679 | ||
|
|
aebd33e5cb | ||
|
|
45b28e46e6 | ||
|
|
48ccd130b2 | ||
|
|
7eb341856d | ||
|
|
38fe10f3a1 | ||
|
|
fa327ecf5c | ||
|
|
6c3e8a632e | ||
|
|
03fcb26473 | ||
|
|
7f4a1c8131 | ||
|
|
416f9307c3 | ||
|
|
1273869b07 | ||
|
|
1839a18bb4 | ||
|
|
34d7fabf61 | ||
|
|
c295bda53b | ||
|
|
f97795bd90 | ||
|
|
f7931b1d83 | ||
|
|
245cf8852d | ||
|
|
7b09eb3a07 | ||
|
|
e45900fbaa | ||
|
|
b0330e80f3 | ||
|
|
9a2cdd0662 | ||
|
|
9b577e96b1 | ||
|
|
7873c57c8e | ||
|
|
38fdb65ec2 | ||
|
|
9ebf03a15a | ||
|
|
8101f9a8c8 | ||
|
|
924d1cf6fe | ||
|
|
de3e456617 | ||
|
|
fc5a21d6bb | ||
|
|
4763d88628 | ||
|
|
a6d72ec1a4 | ||
|
|
99d4aaca45 | ||
|
|
2f614a5c75 | ||
|
|
960b87d86d | ||
|
|
35e15b7ae1 | ||
|
|
392e5f5cff | ||
|
|
451d277644 | ||
|
|
2caed6b3f0 | ||
|
|
a349df7b05 | ||
|
|
efed09bb92 | ||
|
|
a2c222dfd9 | ||
|
|
129ce7c2c6 | ||
|
|
cde261cf5d | ||
|
|
8ef12f8b11 | ||
|
|
99782ef3bb | ||
|
|
6a36603b5d | ||
|
|
5a3d4fffea | ||
|
|
7a585711f6 | ||
|
|
d024e038c2 | ||
|
|
7b329a8c73 | ||
|
|
e62089f019 | ||
|
|
c3ed4a0e27 | ||
|
|
846129b1af | ||
|
|
66edb03aa4 | ||
|
|
d56d6613bb | ||
|
|
5a67d0cc4f | ||
|
|
803b067278 | ||
|
|
78eeee0bc6 | ||
|
|
c6f2c3a813 | ||
|
|
441702a180 | ||
|
|
de85ffa726 | ||
|
|
1482636ad8 | ||
|
|
b62b0eef8b | ||
|
|
37f85f56fa | ||
|
|
4c131093b1 | ||
|
|
22bfe6f2a1 | ||
|
|
fd5ce55c4c | ||
|
|
e5494e2849 | ||
|
|
eb79974760 | ||
|
|
350d22ae75 | ||
|
|
3e7f235876 | ||
|
|
778e194d1d | ||
|
|
bfe9764707 | ||
|
|
5877176645 | ||
|
|
10e74db016 | ||
|
|
82f6d624ba | ||
|
|
22e76538c4 | ||
|
|
11a5477bcb | ||
|
|
aefc14ece9 | ||
|
|
0e6b5dec52 | ||
|
|
2a424699d7 | ||
|
|
3c19a8d532 | ||
|
|
28be68322c | ||
|
|
867fd98bce | ||
|
|
1d3bacd22c | ||
|
|
a483722e1d | ||
|
|
6ab012444f | ||
|
|
57f58e7fb7 | ||
|
|
a51aae9b69 | ||
|
|
4214bd3f20 | ||
|
|
a0b2a75c9d | ||
|
|
159db8114e | ||
|
|
a7b203bcd0 | ||
|
|
d0b55947c5 | ||
|
|
a3c65a1434 | ||
|
|
29c1a4deeb | ||
|
|
ee44e68af9 | ||
|
|
7a426b647b | ||
|
|
9d299beaf6 | ||
|
|
7a1d882248 | ||
|
|
ab95da7242 | ||
|
|
f63bf4a9f1 | ||
|
|
a9d4b96305 | ||
|
|
cedb376a91 | ||
|
|
93d09a779d | ||
|
|
41fa496052 | ||
|
|
398d537d8a | ||
|
|
c501354be1 | ||
|
|
7852772e9d | ||
|
|
efc4a4ee38 | ||
|
|
25c07ef016 | ||
|
|
b3511f018a | ||
|
|
46ba9541eb | ||
|
|
ecf2d06cfa | ||
|
|
d6a8f77610 | ||
|
|
be0dea3702 | ||
|
|
148327c74e | ||
|
|
eed94a4920 | ||
|
|
e47646c953 | ||
|
|
69567c4869 | ||
|
|
7a00dd1794 | ||
|
|
5fbfe1b039 | ||
|
|
8f9dc2048f | ||
|
|
ca70e4a038 | ||
|
|
16d2701e26 | ||
|
|
005510e0a5 | ||
|
|
5ba6913d5f | ||
|
|
c3400ab6cd | ||
|
|
83355f8bbc | ||
|
|
93f2a5ed50 | ||
|
|
120abaf6dd | ||
|
|
2db855d360 | ||
|
|
7aa2805f4c | ||
|
|
1342f0dcf2 | ||
|
|
4f4fb5e6c7 | ||
|
|
68c8681a9b | ||
|
|
cb8c66849a | ||
|
|
3f60267bdc | ||
|
|
43a1a206d5 | ||
|
|
d4badbb8db | ||
|
|
5346030323 | ||
|
|
c32c9d5eba | ||
|
|
000a5aacdf | ||
|
|
62815a7691 | ||
|
|
e52c0f760c | ||
|
|
bfe2a7f817 | ||
|
|
99c0e1b17d | ||
|
|
e1547dbb94 | ||
|
|
38c4295d0b | ||
|
|
3a9e163c9e | ||
|
|
0065c7c5a7 | ||
|
|
fb21d43425 | ||
|
|
13c5ed92f4 | ||
|
|
c3d626f074 | ||
|
|
a6fa3eee8a | ||
|
|
bf024474d1 | ||
|
|
2228e02770 | ||
|
|
d7d17e7f13 | ||
|
|
9bc9655c3d | ||
|
|
0320131d57 | ||
|
|
8275c01d21 | ||
|
|
125013ba0a | ||
|
|
3b34468842 | ||
|
|
cddd3383e8 | ||
|
|
c6148a1c1c | ||
|
|
b2e34c00a4 | ||
|
|
80a99c425b | ||
|
|
f90063cb03 | ||
|
|
c4abdaa54b | ||
|
|
8a2a65d8ed | ||
|
|
2e23e882bb | ||
|
|
4e96b7a930 | ||
|
|
5e72ec3864 | ||
|
|
05eb762273 | ||
|
|
e2419e2c4b | ||
|
|
72afc94782 | ||
|
|
02070b1db1 | ||
|
|
2fc6c7ba91 | ||
|
|
c706d7932d | ||
|
|
62714cdfe1 | ||
|
|
a2c49ac39f | ||
|
|
de55ea643c | ||
|
|
5fb60e14b8 | ||
|
|
02603cb018 | ||
|
|
ffbff595d1 | ||
|
|
989429824e | ||
|
|
a31e6080e2 | ||
|
|
90e05dfb4b | ||
|
|
2af27ddb68 | ||
|
|
d004faa9e0 | ||
|
|
45a4a23112 | ||
|
|
1bb50f8175 | ||
|
|
0cbfcab3f9 | ||
|
|
d4125963b2 | ||
|
|
2e33c2275c | ||
|
|
a5b21198e0 | ||
|
|
e765cda3f9 | ||
|
|
5a91184d6c | ||
|
|
e2094296f4 | ||
|
|
777e856d00 | ||
|
|
c3f419bbc5 | ||
|
|
52705f6982 | ||
|
|
a5134181be | ||
|
|
79c801d493 | ||
|
|
f9823d5303 | ||
|
|
8339591b27 | ||
|
|
17a6e3186d | ||
|
|
213bad9722 | ||
|
|
ef33bd9fd2 | ||
|
|
123de3d452 | ||
|
|
6591bff728 | ||
|
|
88c0779aa2 | ||
|
|
95adcb117c | ||
|
|
372636f43b | ||
|
|
54dae1ab2b | ||
|
|
f0f50a8507 | ||
|
|
c3d0d5be4c | ||
|
|
929132743c | ||
|
|
6643e8937c | ||
|
|
08b4ee461e | ||
|
|
ae501969bf | ||
|
|
c29ed6d41e | ||
|
|
1c28c895b5 | ||
|
|
d9c32437c9 | ||
|
|
0429bed9e3 | ||
|
|
8bdc36a302 | ||
|
|
a3576cc3f4 | ||
|
|
713db0aa4c | ||
|
|
95aae06a41 | ||
|
|
31a4a6f5b8 | ||
|
|
1c66729974 | ||
|
|
6387947b22 | ||
|
|
3a8469c5a9 | ||
|
|
44715591ef | ||
|
|
ceb9d71a1a | ||
|
|
15ad05277b | ||
|
|
14c5b0a678 | ||
|
|
c95964fa3c | ||
|
|
a46f2cee34 | ||
|
|
1764ce9a30 | ||
|
|
384fa0417a | ||
|
|
97ba1050a7 | ||
|
|
628c506e85 | ||
|
|
9226796463 | ||
|
|
83176ba878 | ||
|
|
94cb067214 | ||
|
|
b56b6e0e42 | ||
|
|
28aa3eae33 | ||
|
|
96dee8dee3 | ||
|
|
400410c449 | ||
|
|
ab08abb3f6 | ||
|
|
01e32537a8 | ||
|
|
652d1c8c4f | ||
|
|
64e7792778 | ||
|
|
bfb03c6d1e | ||
|
|
1fa20f9cda | ||
|
|
9d61ec49c3 | ||
|
|
9dc598feff | ||
|
|
49fde946ac | ||
|
|
c4ded39e7c | ||
|
|
c8518e9f35 | ||
|
|
97d3a38ed8 | ||
|
|
e840b53978 | ||
|
|
c43e52e9ad | ||
|
|
2a2bd99fcf | ||
|
|
c4f9fc4585 | ||
|
|
0222dfd865 | ||
|
|
11f91b67a8 | ||
|
|
6e2d485b90 | ||
|
|
e336a57e13 | ||
|
|
29e7c119bd | ||
|
|
882228558d | ||
|
|
51360e802f | ||
|
|
7a06660597 | ||
|
|
4553cd0261 | ||
|
|
2bbc426bef | ||
|
|
b22a22cac9 | ||
|
|
cc7b931e0a | ||
|
|
d4a44b0d72 | ||
|
|
284a9bb444 | ||
|
|
ef4dc0e972 | ||
|
|
def031958b | ||
|
|
00c1936683 | ||
|
|
cc3aab1e7b | ||
|
|
c14de6d198 | ||
|
|
f9f8186451 | ||
|
|
0259cf84ce | ||
|
|
04ceb5f4fa | ||
|
|
6efcbe7c70 | ||
|
|
e0ce92a9f3 | ||
|
|
28e08e108a | ||
|
|
4e68903251 | ||
|
|
73515e5179 | ||
|
|
f752770788 | ||
|
|
6eb6efe844 | ||
|
|
837b8755a0 | ||
|
|
e3b5e867b1 | ||
|
|
362efd9546 | ||
|
|
a958874731 | ||
|
|
0d5094cfb5 | ||
|
|
74b32e064e | ||
|
|
3ad5dfe030 | ||
|
|
95242965da | ||
|
|
8c15105087 | ||
|
|
db68505cca | ||
|
|
795aee86d1 | ||
|
|
33621ff523 | ||
|
|
415a694228 | ||
|
|
1fe8b7f78d | ||
|
|
c2fc3c54da | ||
|
|
652c2d95b8 | ||
|
|
da1b6caf67 | ||
|
|
deafdfb7ab | ||
|
|
f9feaeab0b | ||
|
|
330c160122 | ||
|
|
238c7b3a44 | ||
|
|
1317696cb7 | ||
|
|
23108f2224 | ||
|
|
6b14252577 | ||
|
|
8386cd7503 | ||
|
|
c6225eeb3a | ||
|
|
a12c2fd120 | ||
|
|
9e503ab31f | ||
|
|
c31abb84c9 | ||
|
|
b1a0bc252f | ||
|
|
599b1639e7 | ||
|
|
1199f9ae8e | ||
|
|
cb8ae318c4 | ||
|
|
fec8a759bc | ||
|
|
5d4b54c39c | ||
|
|
4ebab3a967 | ||
|
|
73315e6671 | ||
|
|
db03a888fb | ||
|
|
7d4a5c4c6c | ||
|
|
94397ea4c7 | ||
|
|
e05319432e | ||
|
|
f1bce695fb | ||
|
|
7aad2697f7 | ||
|
|
848a2d74d6 | ||
|
|
a2a470ad93 | ||
|
|
78150b2661 | ||
|
|
ed2e1a0936 | ||
|
|
445389b7d8 | ||
|
|
1bb8cbf3ab | ||
|
|
ca6fe7b86e | ||
|
|
0b351ea3a2 | ||
|
|
05c5db53bd | ||
|
|
7632e07f4e | ||
|
|
1ddbe43618 | ||
|
|
79f83e245c | ||
|
|
d678f28909 | ||
|
|
c3e95fa98c | ||
|
|
e32e55df15 | ||
|
|
48eaf48797 | ||
|
|
ead505d40c | ||
|
|
a39a53561e | ||
|
|
ebf715c368 | ||
|
|
87f2c360c5 | ||
|
|
b0584b4ead | ||
|
|
1575a4cc34 | ||
|
|
1bc12d7a33 | ||
|
|
89707ff412 | ||
|
|
33b9e220d3 | ||
|
|
d3e39f66a2 | ||
|
|
48a991e11b | ||
|
|
3ef79e51ca | ||
|
|
d945add7a0 | ||
|
|
2e0e25de42 | ||
|
|
334043947a | ||
|
|
e5e8f2b962 | ||
|
|
a16ecbc8a9 | ||
|
|
3c6e9c75a9 | ||
|
|
980bcb2eb5 | ||
|
|
3b73722bca | ||
|
|
15f7a970b1 | ||
|
|
e6083dbe81 | ||
|
|
54a77441fd | ||
|
|
353cf671da | ||
|
|
02c280009b | ||
|
|
379db84504 | ||
|
|
bd56df8ed8 |
No files matched your search
+4
-1
@@ -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)
|
variableService := variable.NewService(variableRepo, configRepo, eventRepo, configSchemaRepo, l.logger)
|
||||||
variableController := api.NewVariable(variableService)
|
variableController := api.NewVariable(variableService)
|
||||||
|
|
||||||
etpSrv := etp.NewServer(
|
etpSrv := etp.NewServer(
|
||||||
@@ -134,6 +134,8 @@ func (l Locator) Config() *Config {
|
|||||||
subscriptionService,
|
subscriptionService,
|
||||||
emitter,
|
emitter,
|
||||||
variableService,
|
variableService,
|
||||||
|
variableRepo,
|
||||||
|
l.cfg.Local.ConfigWriteDeny,
|
||||||
l.logger,
|
l.logger,
|
||||||
)
|
)
|
||||||
moduleController := controller.NewModule(moduleService, l.logger)
|
moduleController := controller.NewModule(moduleService, l.logger)
|
||||||
@@ -148,6 +150,7 @@ func (l Locator) Config() *Config {
|
|||||||
configApiService := apisvs.NewConfig(
|
configApiService := apisvs.NewConfig(
|
||||||
configRepo,
|
configRepo,
|
||||||
moduleRepo,
|
moduleRepo,
|
||||||
|
moduleService,
|
||||||
configSchemaRepo,
|
configSchemaRepo,
|
||||||
eventRepo,
|
eventRepo,
|
||||||
configHistoryApiService,
|
configHistoryApiService,
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
### v3.12.2
|
||||||
|
* Добавлена обработка новых тегов конфигурации модулей: теги для UI экспонируемых полей и полей требующих ссылки на переменные с типом SECRET
|
||||||
### v3.12.1
|
### v3.12.1
|
||||||
* Обновление ограничений конфигурации: в параметре `KeepConfigVersions` допустимо значение `0`
|
* Обновление ограничений конфигурации: в параметре `KeepConfigVersions` допустимо значение `0`
|
||||||
### v3.12.0
|
### v3.12.0
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ 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
|
||||||
|
|||||||
@@ -15,15 +15,28 @@ 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=
|
||||||
@@ -44,6 +57,9 @@ 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=
|
||||||
@@ -62,6 +78,9 @@ 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=
|
||||||
@@ -98,21 +117,40 @@ 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=
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ type Local struct {
|
|||||||
InternalClientCredential string `validate:"required"`
|
InternalClientCredential string `validate:"required"`
|
||||||
Rqlite Rqlite
|
Rqlite Rqlite
|
||||||
Backup rqlite.Backup
|
Backup rqlite.Backup
|
||||||
|
ConfigWriteDeny bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type Rqlite struct {
|
type Rqlite struct {
|
||||||
|
|||||||
@@ -5,12 +5,13 @@ 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 {
|
||||||
@@ -184,12 +185,24 @@ 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/>"
|
// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - конфигурация нарушает политику секретных переменных (детали по путям в `details`)<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,
|
||||||
@@ -272,18 +285,36 @@ 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` - конфиг не найден"
|
// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден<br/>`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003` - в UI-экспонируемых полях активная конфигурация ссылается на секретную переменную"
|
||||||
// @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:
|
||||||
|
|||||||
+5
-2
@@ -593,7 +593,9 @@ paths:
|
|||||||
"200":
|
"200":
|
||||||
description: OK
|
description: OK
|
||||||
"400":
|
"400":
|
||||||
description: '`errorCode: 2002` - конфиг не найден<br/>'
|
description: '`errorCode: 2002` - конфиг не найден<br/>`errorCode: 2003`
|
||||||
|
- конфигурация нарушает политику секретных переменных (детали по путям
|
||||||
|
в `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":
|
||||||
@@ -657,7 +659,8 @@ 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":
|
||||||
|
|||||||
+13
-6
@@ -5,13 +5,20 @@ 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 string `json:"type"`
|
Type VariableType `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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigHasVariable struct {
|
type ConfigHasVariable struct {
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ require (
|
|||||||
github.com/tidwall/gjson v1.18.0
|
github.com/tidwall/gjson v1.18.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.76.0
|
github.com/txix-open/isp-kit v1.31.5-0.20261127095759-c39408f3bd58
|
||||||
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
|
||||||
|
|||||||
@@ -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.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
github.com/txix-open/isp-kit v1.31.5-0.20261127095759-c39408f3bd58 h1:huhPwzaU5BBwfhXD0vkBNBNv1xhjvAvplEZ/dOK1osQ=
|
||||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
github.com/txix-open/isp-kit v1.31.5-0.20261127095759-c39408f3bd58/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=
|
||||||
|
|||||||
+32
-2
@@ -5,11 +5,12 @@ 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 {
|
||||||
@@ -66,6 +67,35 @@ 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")
|
||||||
|
|
||||||
|
|||||||
+134
-90
@@ -4,15 +4,16 @@ 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 {
|
||||||
@@ -39,9 +40,14 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
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
|
||||||
@@ -52,6 +58,7 @@ 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,
|
||||||
@@ -61,6 +68,7 @@ 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,
|
||||||
@@ -121,8 +129,13 @@ 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")
|
||||||
}
|
}
|
||||||
@@ -134,6 +147,117 @@ 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
|
||||||
|
}
|
||||||
|
|
||||||
|
// updateConfig updates an existing config version, records the history and
|
||||||
|
// variable links, and emits the active-config change event when needed.
|
||||||
|
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")
|
||||||
@@ -199,92 +323,6 @@ func (c Config) CreateUpdateConfig(
|
|||||||
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(),
|
||||||
@@ -295,6 +333,12 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre
|
|||||||
Active: false,
|
Active: false,
|
||||||
AdminId: adminId,
|
AdminId: adminId,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
err := c.moduleService.FilterSecretParams(ctx, req.Data, req.ModuleId)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Config{}, errors.WithMessage(err, "filter secret params")
|
||||||
|
}
|
||||||
|
|
||||||
// Check variables before insert so a config with missing variables is never persisted without links.
|
// Check variables before insert so a config with missing variables is never persisted without links.
|
||||||
extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data)
|
extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
+265
-42
@@ -4,18 +4,25 @@ 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/txix-open/isp-kit/rc"
|
||||||
|
"github.com/txix-open/isp-kit/rc/schema"
|
||||||
|
|
||||||
"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 (
|
||||||
@@ -38,6 +45,7 @@ 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 {
|
||||||
@@ -45,8 +53,12 @@ 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, input []byte) ([]byte, error)
|
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error)
|
||||||
ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error)
|
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
|
||||||
}
|
}
|
||||||
@@ -65,6 +77,8 @@ type Service struct {
|
|||||||
subscriptionService SubscriptionService
|
subscriptionService SubscriptionService
|
||||||
emitter Emitter
|
emitter Emitter
|
||||||
variableService VariableService
|
variableService VariableService
|
||||||
|
variableRepo VariableRepo
|
||||||
|
configWriteDeny bool
|
||||||
logger log.Logger
|
logger log.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +90,8 @@ func NewService(
|
|||||||
subscriptionService SubscriptionService,
|
subscriptionService SubscriptionService,
|
||||||
emitter Emitter,
|
emitter Emitter,
|
||||||
variableService VariableService,
|
variableService VariableService,
|
||||||
|
variableRepo VariableRepo,
|
||||||
|
configWriteDeny bool,
|
||||||
logger log.Logger,
|
logger log.Logger,
|
||||||
) Service {
|
) Service {
|
||||||
return Service{
|
return Service{
|
||||||
@@ -86,6 +102,8 @@ func NewService(
|
|||||||
subscriptionService: subscriptionService,
|
subscriptionService: subscriptionService,
|
||||||
emitter: emitter,
|
emitter: emitter,
|
||||||
variableService: variableService,
|
variableService: variableService,
|
||||||
|
variableRepo: variableRepo,
|
||||||
|
configWriteDeny: configWriteDeny,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -212,43 +230,6 @@ 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(),
|
||||||
@@ -261,6 +242,21 @@ 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
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,3 +264,230 @@ func idByKey(key string) string {
|
|||||||
hash := sha256.Sum256([]byte(key))
|
hash := sha256.Sum256([]byte(key))
|
||||||
return hex.EncodeToString(hash[:])
|
return hex.EncodeToString(hash[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FilterSecretParams checks the config against the secret write policy:
|
||||||
|
// ui-exposed fields must not reference SECRET variables, and sensitive fields
|
||||||
|
// must hold only a single reference to a SECRET variable. A no-op when the
|
||||||
|
// config write policy is disabled.
|
||||||
|
func (s Service) FilterSecretParams(ctx context.Context, config json.RawMessage, moduleId string) error {
|
||||||
|
if !s.configWriteDeny {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
moduleSchema, err := s.configSchemaRepo.GetByModuleId(ctx, moduleId)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "find module schema")
|
||||||
|
}
|
||||||
|
|
||||||
|
if moduleSchema == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
uiPaths, sensitivePaths, err := policyPaths(moduleSchema.Data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(uiPaths) == 0 && len(sensitivePaths) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
placeholders, err := rc.PlaceHolderReader(config)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "read config placeholders")
|
||||||
|
}
|
||||||
|
|
||||||
|
refsByPath, names, sensitiveSet := policyRefs(placeholders, uiPaths, sensitivePaths)
|
||||||
|
variableTypes, err := s.referencedVariableTypes(ctx, names)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
errorDetails := uiExposedViolations(refsByPath, variableTypes)
|
||||||
|
if len(sensitivePaths) > 0 {
|
||||||
|
sensitiveDetails, err := sensitiveViolations(config, sensitiveSet, sensitivePaths, variableTypes)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
maps.Copy(errorDetails, sensitiveDetails)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(errorDetails) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.WithMessage(domain.NewConfigValidationError(errorDetails), "config violates the secret policy")
|
||||||
|
}
|
||||||
|
|
||||||
|
// storeInitialConfig checks the secret write policy and persists the module's
|
||||||
|
// initial config with its variable links. A violating default config is never
|
||||||
|
// persisted on the first module connection.
|
||||||
|
func (s Service) storeInitialConfig(ctx context.Context, conn *etp.Conn, moduleId string, data cluster.ConfigData) (*entity.Config, error) {
|
||||||
|
err := s.FilterSecretParams(ctx, data.Config, moduleId)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "filter secret params in store")
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// referencedVariableTypes resolves the types of the variables referenced on
|
||||||
|
// the policy paths.
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// policyPaths reads the ui-exposed and sensitive leaf paths from the schema.
|
||||||
|
func policyPaths(schemaData []byte) ([]string, []string, error) {
|
||||||
|
uiPaths, err := schema.UIExposedPaths(schemaData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.WithMessage(err, "read schema params")
|
||||||
|
}
|
||||||
|
sensitivePaths, err := schema.SensitivePaths(schemaData)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, errors.WithMessage(err, "read schema params")
|
||||||
|
}
|
||||||
|
return uiPaths, sensitivePaths, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// policyRefs collects the ui-exposed references (kept per path for the
|
||||||
|
// report), the set of all referenced variable names and the sensitive paths.
|
||||||
|
func policyRefs(placeholders map[string][]string, uiPaths, sensitivePaths []string) (map[string][]string, map[string]struct{}, map[string]struct{}) {
|
||||||
|
refsByPath := make(map[string][]string)
|
||||||
|
names := make(map[string]struct{})
|
||||||
|
sensitiveSet := make(map[string]struct{}, len(sensitivePaths))
|
||||||
|
for _, path := range uiPaths {
|
||||||
|
for _, name := range placeholders[path] {
|
||||||
|
names[name] = struct{}{}
|
||||||
|
refsByPath[path] = append(refsByPath[path], name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range sensitivePaths {
|
||||||
|
sensitiveSet[path] = struct{}{}
|
||||||
|
for _, name := range placeholders[path] {
|
||||||
|
names[name] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return refsByPath, names, sensitiveSet
|
||||||
|
}
|
||||||
|
|
||||||
|
// uiExposedViolations reports the ui-exposed paths that reference SECRET
|
||||||
|
// variables.
|
||||||
|
func uiExposedViolations(refsByPath map[string][]string, variableTypes map[string]entity.VariableType) map[string]string {
|
||||||
|
details := make(map[string]string)
|
||||||
|
for path, refs := range refsByPath {
|
||||||
|
secrets := make([]string, 0, len(refs))
|
||||||
|
for _, name := range refs {
|
||||||
|
if variableTypes[name] == entity.SecretType {
|
||||||
|
secrets = append(secrets, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(secrets) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sort.Strings(secrets)
|
||||||
|
plural := "переменную"
|
||||||
|
if len(secrets) > 1 {
|
||||||
|
plural = "переменные"
|
||||||
|
}
|
||||||
|
message := fmt.Sprintf("UI-экспортируемое поле не должно ссылаться на %s с типом SECRET: %s", plural, strings.Join(secrets, ", "))
|
||||||
|
details[policyFieldPath(path)] = message
|
||||||
|
}
|
||||||
|
return details
|
||||||
|
}
|
||||||
|
|
||||||
|
// sensitiveViolations reports the sensitive paths whose value is not a single
|
||||||
|
// reference to a SECRET variable. Composite JSON strings are report-only and
|
||||||
|
// never rejected.
|
||||||
|
func sensitiveViolations(
|
||||||
|
config json.RawMessage,
|
||||||
|
sensitiveSet map[string]struct{},
|
||||||
|
sensitivePaths []string,
|
||||||
|
variableTypes map[string]entity.VariableType,
|
||||||
|
) (map[string]string, error) {
|
||||||
|
details := make(map[string]string)
|
||||||
|
|
||||||
|
values, err := leafValuesAt(config, sensitiveSet)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, path := range sensitivePaths {
|
||||||
|
value, exists := values[path]
|
||||||
|
if !exists || value == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if rc.IsCompositeJSONString(value) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if name, ok := rc.SingleVariableRef(value); ok {
|
||||||
|
if t, known := variableTypes[name]; known && t != entity.SecretType {
|
||||||
|
message := fmt.Sprintf("sensitive-поле должно ссылаться только на переменные с типом SECRET: переменная %s имеет тип %s", name, t)
|
||||||
|
details[policyFieldPath(path)] = message
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
details[policyFieldPath(path)] = "plain value in sensitive field"
|
||||||
|
}
|
||||||
|
|
||||||
|
return details, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// leafValuesAt collects the raw values of the config's string leaves located
|
||||||
|
// at the given canonical paths.
|
||||||
|
func leafValuesAt(data []byte, paths map[string]struct{}) (map[string]string, error) {
|
||||||
|
values := make(map[string]string, len(paths))
|
||||||
|
_, err := rc.TransformStringLeaves(data, func(path, value string) string {
|
||||||
|
if _, want := paths[path]; want {
|
||||||
|
values[path] = value
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "read config leaf values")
|
||||||
|
}
|
||||||
|
return values, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func policyFieldPath(canonical string) string {
|
||||||
|
path := strings.TrimPrefix(canonical, "$.")
|
||||||
|
return strings.ReplaceAll(path, "[]", ".0")
|
||||||
|
}
|
||||||
@@ -32,7 +32,7 @@ type ConfigRepo interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type VariableService interface {
|
type VariableService interface {
|
||||||
RenderConfig(ctx context.Context, input []byte) ([]byte, error)
|
RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Emitter interface {
|
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, config.Data)
|
configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithMessage(err, "render config")
|
return errors.WithMessage(err, "render config")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package variable
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
|
||||||
|
"isp-config-service/entity"
|
||||||
|
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/rc"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
variableRefPattern = regexp.MustCompile(`_Var\((.*?)\)`)
|
||||||
|
stringToIntPattern = regexp.MustCompile(`"_ToInt\((\d+)\)"`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// skippedRef names a UI-exposed path and a SECRET variable left unrendered there.
|
||||||
|
type skippedRef struct {
|
||||||
|
Path string
|
||||||
|
Variable string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render substitutes _Var(name) references in the config's string leaves.
|
||||||
|
// On UI-exposed paths (uiPaths) references to SECRET variables are left as
|
||||||
|
// literals and reported in skipped; every other reference is substituted.
|
||||||
|
// Composite JSON string leaves are report-only (see rc.VariableRefReport):
|
||||||
|
// the secret policy does not apply to them, so every known reference is
|
||||||
|
// substituted. References to unknown variables are collected in undefined.
|
||||||
|
// The document is re-assembled into JSON and _ToInt is applied to the
|
||||||
|
// assembled bytes, as before; object key order is not preserved.
|
||||||
|
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, policyActive bool) 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
|
||||||
|
}
|
||||||
|
if policyActive && variable.Type == entity.SecretType {
|
||||||
|
if _, isUI := uiSet[path]; isUI {
|
||||||
|
key := path + "\x00" + name
|
||||||
|
if _, dup := skippedSeen[key]; !dup {
|
||||||
|
skippedSeen[key] = struct{}{}
|
||||||
|
skipped = append(skipped, skippedRef{Path: path, Variable: name})
|
||||||
|
}
|
||||||
|
return match
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return variable.Value
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := rc.TransformStringLeaves(input, func(path, value string) string {
|
||||||
|
if rc.IsCompositeJSONString(value) {
|
||||||
|
return substitute(path, value, false)
|
||||||
|
}
|
||||||
|
return substitute(path, value, true)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, errors.WithMessage(err, "transform config leaves")
|
||||||
|
}
|
||||||
|
|
||||||
|
return stringToIntPattern.ReplaceAll(out, []byte("$1")), skipped, undefined, nil
|
||||||
|
}
|
||||||
+96
-31
@@ -2,14 +2,19 @@ package variable
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"regexp"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"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"
|
||||||
|
|
||||||
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
|
"github.com/txix-open/isp-kit/errors"
|
||||||
|
"github.com/txix-open/isp-kit/log"
|
||||||
|
"github.com/txix-open/isp-kit/metrics"
|
||||||
|
"github.com/txix-open/isp-kit/rc/schema"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Repo interface {
|
type Repo interface {
|
||||||
@@ -30,28 +35,56 @@ 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
|
||||||
stringToIntRegexp *regexp.Regexp
|
schemaRepo SchemaRepo
|
||||||
variableRegexp *regexp.Regexp
|
logger log.Logger
|
||||||
|
secretSkipped *prometheus.CounterVec
|
||||||
|
uiPathsCache *uiPathsCache
|
||||||
}
|
}
|
||||||
|
|
||||||
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,
|
||||||
stringToIntRegexp: regexp.MustCompile(`"_ToInt\((\d+)\)"`),
|
schemaRepo: schemaRepo,
|
||||||
variableRegexp: regexp.MustCompile(`_Var\((.*?)\)`),
|
logger: logger,
|
||||||
|
secretSkipped: metrics.GetOrRegister(metrics.DefaultRegistry,
|
||||||
|
prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||||
|
Subsystem: "config",
|
||||||
|
Name: "render_secret_skipped_total",
|
||||||
|
Help: "Secret variables left unrendered in UI-exposed config leaves",
|
||||||
|
}, []string{"module", "variable"}),
|
||||||
|
),
|
||||||
|
uiPathsCache: &uiPathsCache{entries: make(map[string]cachedUIPaths)},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// cachedUIPaths is the module's ui-exposed leaf paths for a schema version.
|
||||||
|
type cachedUIPaths struct {
|
||||||
|
version string
|
||||||
|
paths []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// uiPathsCache caches ui-exposed paths per module, invalidated on schema version change.
|
||||||
|
type uiPathsCache struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
entries map[string]cachedUIPaths
|
||||||
|
}
|
||||||
|
|
||||||
func (s Service) All(ctx context.Context) ([]domain.Variable, error) {
|
func (s Service) All(ctx context.Context) ([]domain.Variable, error) {
|
||||||
variables, err := s.repo.All(ctx)
|
variables, err := s.repo.All(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -180,7 +213,7 @@ func (s Service) Delete(ctx context.Context, name string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//nolint:funlen
|
//nolint:funlen
|
||||||
func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) {
|
func (s Service) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) {
|
||||||
variables, err := s.repo.All(ctx)
|
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")
|
||||||
@@ -188,33 +221,38 @@ func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error)
|
|||||||
if len(variables) == 0 {
|
if len(variables) == 0 {
|
||||||
return input, nil
|
return input, nil
|
||||||
}
|
}
|
||||||
varsMap := make(map[string]string, len(variables))
|
varsMap := make(map[string]entity.Variable, len(variables))
|
||||||
for _, variable := range variables {
|
for _, variable := range variables {
|
||||||
varsMap[variable.Name] = variable.Value
|
varsMap[variable.Name] = variable
|
||||||
}
|
}
|
||||||
|
|
||||||
undefinedVariables := make([]string, 0)
|
uiPaths, err := s.uiPaths(ctx, moduleId)
|
||||||
withReplacedVars := s.variableRegexp.ReplaceAllStringFunc(string(input), func(group string) string {
|
if err != nil {
|
||||||
varName := s.variableRegexp.FindStringSubmatch(group)[1]
|
return nil, err
|
||||||
|
|
||||||
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, ", "))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
result := s.stringToIntRegexp.ReplaceAll([]byte(withReplacedVars), []byte("$1"))
|
out, skipped, undefined, err := Render(input, uiPaths, varsMap)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "render config")
|
||||||
|
}
|
||||||
|
if len(undefined) > 0 {
|
||||||
|
return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefined, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
return result, nil
|
for _, ref := range skipped {
|
||||||
|
s.logger.Error(ctx, "secret variable not substituted in ui-exposed field",
|
||||||
|
log.String("moduleId", moduleId),
|
||||||
|
log.String("path", ref.Path),
|
||||||
|
log.String("variable", ref.Variable),
|
||||||
|
)
|
||||||
|
s.secretSkipped.WithLabelValues(moduleId, ref.Variable).Inc()
|
||||||
|
}
|
||||||
|
|
||||||
|
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 := s.variableRegexp.FindAllStringSubmatch(string(input), -1)
|
matches := variableRefPattern.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 {
|
||||||
@@ -269,6 +307,33 @@ func (s Service) SaveVariableLinks(ctx context.Context, configId string, links [
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// uiPaths returns the canonical paths of the module's ui-exposed leaves,
|
||||||
|
// cached per module and schema version. A module without a schema (or with a
|
||||||
|
// schema without the keyword) yields an empty set, so rendering behaves as
|
||||||
|
// before.
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
s.uiPathsCache.mu.Lock()
|
||||||
|
defer s.uiPathsCache.mu.Unlock()
|
||||||
|
if cached, ok := s.uiPathsCache.entries[moduleId]; ok && cached.version == schemaRow.ModuleVersion {
|
||||||
|
return cached.paths, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
paths, err := schema.UIExposedPaths(schemaRow.Data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.WithMessage(err, "read ui-exposed paths")
|
||||||
|
}
|
||||||
|
s.uiPathsCache.entries[moduleId] = cachedUIPaths{version: schemaRow.ModuleVersion, paths: 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" {
|
||||||
|
|||||||
@@ -216,6 +216,7 @@ func setupTestApp(t *testing.T) (*require.Assertions, log.Logger, db.DB) {
|
|||||||
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("configWriteDeny", true)
|
||||||
logger := boot.App.Logger()
|
logger := boot.App.Logger()
|
||||||
|
|
||||||
startup, err := startup.New(boot)
|
startup, err := startup.New(boot)
|
||||||
|
|||||||
@@ -97,6 +97,7 @@ func setupTestWithAppRun(t *testing.T) (*require.Assertions, log.Logger) {
|
|||||||
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("configWriteDeny", true)
|
||||||
logger := boot.App.Logger()
|
logger := boot.App.Logger()
|
||||||
|
|
||||||
startup, err := startup.New(boot)
|
startup, err := startup.New(boot)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
package event_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
@@ -9,30 +9,30 @@ import (
|
|||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
|
|
||||||
const testModuleId = "test-module-id"
|
const eventTestModuleId = "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: testModuleId},
|
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId},
|
||||||
})
|
})
|
||||||
ready.Id = 1
|
ready.Id = 1
|
||||||
|
|
||||||
disconnected := entity.NewEvent(entity.EventPayload{
|
disconnected := entity.NewEvent(entity.EventPayload{
|
||||||
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: testModuleId},
|
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId},
|
||||||
})
|
})
|
||||||
disconnected.Id = 2
|
disconnected.Id = 2
|
||||||
|
|
||||||
configUpdated := entity.NewEvent(entity.EventPayload{
|
configUpdated := entity.NewEvent(entity.EventPayload{
|
||||||
ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: testModuleId},
|
ConfigUpdated: &entity.PayloadConfigUpdated{ModuleId: eventTestModuleId},
|
||||||
})
|
})
|
||||||
configUpdated.Id = 3
|
configUpdated.Id = 3
|
||||||
|
|
||||||
require.Equal("module_lifecycle_"+testModuleId, ready.Key())
|
require.Equal("module_lifecycle_"+eventTestModuleId, ready.Key())
|
||||||
require.Equal("module_lifecycle_"+testModuleId, disconnected.Key())
|
require.Equal("module_lifecycle_"+eventTestModuleId, disconnected.Key())
|
||||||
require.Equal("config_updated_"+testModuleId, configUpdated.Key())
|
require.Equal("config_updated_"+eventTestModuleId, 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 event_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -31,23 +31,23 @@ func (s *subscriptionSpy) NotifyRoutingChanged(ctx context.Context) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type loggerSpy struct {
|
type eventLoggerSpy struct {
|
||||||
errors []string
|
errors []string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {
|
func (l *eventLoggerSpy) 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 *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *eventLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *eventLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *eventLoggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func moduleReadyEvent(id int) entity.Event {
|
func moduleReadyEvent(id int) entity.Event {
|
||||||
event := entity.NewEvent(entity.EventPayload{
|
event := entity.NewEvent(entity.EventPayload{
|
||||||
ModuleReady: &entity.PayloadModuleReady{ModuleId: testModuleId},
|
ModuleReady: &entity.PayloadModuleReady{ModuleId: eventTestModuleId},
|
||||||
})
|
})
|
||||||
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: testModuleId},
|
ModuleDisconnected: &entity.PayloadModuleDisconnected{ModuleId: eventTestModuleId},
|
||||||
})
|
})
|
||||||
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 := &loggerSpy{}
|
logger := &eventLoggerSpy{}
|
||||||
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{testModuleId}, subscription.backendsChanged,
|
require.Equal([]string{eventTestModuleId}, 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 := &loggerSpy{}
|
logger := &eventLoggerSpy{}
|
||||||
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{testModuleId}, subscription.backendsChanged,
|
require.Equal([]string{eventTestModuleId}, 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)
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package backend_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -14,28 +14,28 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
testModuleName = "test-module"
|
backendTestModuleName = "test-module"
|
||||||
testModuleId = "test-module-id"
|
backendTestModuleId = "test-module-id"
|
||||||
testConnId = "test-conn-id"
|
testConnId = "test-conn-id"
|
||||||
testNodeId = "test-node-id"
|
testNodeId = "test-node-id"
|
||||||
|
|
||||||
leaderConnId = "conn-1"
|
backendLeaderConnId = "conn-1"
|
||||||
followerConnId = "conn-2"
|
backendFollowerConnId = "conn-2"
|
||||||
leaderAddress = "10.0.0.1:9000"
|
backendLeaderAddress = "10.0.0.1:9000"
|
||||||
followerAddress = "10.0.0.2:9000"
|
followerAddress = "10.0.0.2:9000"
|
||||||
)
|
)
|
||||||
|
|
||||||
type storedLog struct {
|
type backendStoredLog struct {
|
||||||
message any
|
message any
|
||||||
fields map[string]string
|
fields map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
type loggerSpy struct {
|
type backendLoggerSpy struct {
|
||||||
warns []storedLog
|
warns []backendStoredLog
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {
|
func (l *backendLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {
|
||||||
entry := storedLog{
|
entry := backendStoredLog{
|
||||||
message: message,
|
message: message,
|
||||||
fields: make(map[string]string, len(fields)),
|
fields: make(map[string]string, len(fields)),
|
||||||
}
|
}
|
||||||
@@ -45,11 +45,11 @@ func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field)
|
|||||||
l.warns = append(l.warns, entry)
|
l.warns = append(l.warns, entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *backendLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *backendLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *backendLoggerSpy) 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 := &loggerSpy{}
|
logger := &backendLoggerSpy{}
|
||||||
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: testModuleName,
|
ModuleName: backendTestModuleName,
|
||||||
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, testModuleId, declaration)
|
connected, err := service.Connect(t.Context(), testConnId, backendTestModuleId, 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(testModuleName, logger.warns[0].fields["moduleName"])
|
require.Equal(backendTestModuleName, 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(electedInstance(leaderConnId, leaderAddress))
|
backendRepo := newBackendRepoSpy(backendElectedInstance(backendLeaderConnId, backendLeaderAddress))
|
||||||
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &loggerSpy{})
|
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{})
|
||||||
|
|
||||||
declaration := cluster.BackendDeclaration{
|
declaration := cluster.BackendDeclaration{
|
||||||
ModuleName: testModuleName,
|
ModuleName: backendTestModuleName,
|
||||||
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(), followerConnId, testModuleId, declaration)
|
_, err := service.Connect(t.Context(), backendFollowerConnId, backendTestModuleId, 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_" + testModuleId}, eventKeys(events),
|
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, 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(
|
||||||
electedInstance(leaderConnId, leaderAddress),
|
backendElectedInstance(backendLeaderConnId, backendLeaderAddress),
|
||||||
electedInstance(followerConnId, followerAddress),
|
backendElectedInstance(backendFollowerConnId, followerAddress),
|
||||||
)
|
)
|
||||||
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &loggerSpy{})
|
service := backend.NewBackend(backendRepo, events, testNodeId, nil, &backendLoggerSpy{})
|
||||||
|
|
||||||
err := service.Disconnect(t.Context(), entity.Backend{
|
err := service.Disconnect(t.Context(), entity.Backend{
|
||||||
WsConnectionId: leaderConnId,
|
WsConnectionId: backendLeaderConnId,
|
||||||
ModuleId: testModuleId,
|
ModuleId: backendTestModuleId,
|
||||||
ModuleName: testModuleName,
|
ModuleName: backendTestModuleName,
|
||||||
})
|
})
|
||||||
|
|
||||||
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_" + testModuleId}, eventKeys(events),
|
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, 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(
|
||||||
electedInstance(leaderConnId, leaderAddress),
|
backendElectedInstance(backendLeaderConnId, backendLeaderAddress),
|
||||||
electedInstance(followerConnId, followerAddress),
|
backendElectedInstance(backendFollowerConnId, followerAddress),
|
||||||
)
|
)
|
||||||
service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &loggerSpy{})
|
service := backend.NewBackend(backendRepo, events, testNodeId, &etp.Rooms{}, &backendLoggerSpy{})
|
||||||
|
|
||||||
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_" + testModuleId}, eventKeys(events),
|
require.Equal([]string{"module_lifecycle_" + backendTestModuleId}, 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, &loggerSpy{})
|
service := backend.NewBackend(newBackendRepoSpy(), events, testNodeId, nil, &backendLoggerSpy{})
|
||||||
|
|
||||||
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 electedInstance(connId string, address string) entity.Backend {
|
func backendElectedInstance(connId string, address string) entity.Backend {
|
||||||
return entity.Backend{
|
return entity.Backend{
|
||||||
WsConnectionId: connId,
|
WsConnectionId: connId,
|
||||||
ModuleId: testModuleId,
|
ModuleId: backendTestModuleId,
|
||||||
ModuleName: testModuleName,
|
ModuleName: backendTestModuleName,
|
||||||
Address: address,
|
Address: address,
|
||||||
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
|
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package leader_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"slices"
|
"slices"
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// policyService builds a module Service wired with the policy dependencies;
|
||||||
|
// the remaining dependencies are unused by FilterSecretParams and left 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
|
||||||
|
}
|
||||||
|
|
||||||
|
func policyTestCases() []policyTestCase {
|
||||||
|
return []policyTestCase{
|
||||||
|
{
|
||||||
|
name: "ui-exposed secret reference",
|
||||||
|
config: `{"secrets": "_Var(sec_var)"}`,
|
||||||
|
wantErr: true,
|
||||||
|
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
|
||||||
|
"secrets": "UI-экспортируемое поле не должно ссылаться на переменную с типом 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 // test fixture, not credentials
|
||||||
|
"secrets": "UI-экспортируемое поле не должно ссылаться на переменные с типом SECRET: sec_var, sec_var2",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sensitive literal without any references",
|
||||||
|
config: `{"token": "plain-pass"}`,
|
||||||
|
wantErr: true,
|
||||||
|
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
|
||||||
|
"token": "plain value in sensitive field",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "sensitive non-secret reference",
|
||||||
|
config: `{"token": "_Var(txt_var)"}`,
|
||||||
|
wantErr: true,
|
||||||
|
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
|
||||||
|
"token": "sensitive-поле должно ссылаться только на переменные с типом SECRET: переменная txt_var имеет тип 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 // test fixture, not credentials
|
||||||
|
"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 // test fixture, not credentials
|
||||||
|
"secrets": "UI-экспортируемое поле не должно ссылаться на переменную с типом 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
package tests_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"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"
|
||||||
|
"github.com/txix-open/isp-kit/metrics"
|
||||||
|
)
|
||||||
|
|
||||||
|
// renderPolicyConfig has one ui-exposed leaf and one plain leaf.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// Legacy regime: the variable referenced by the stored config becomes SECRET.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// The skip is observable: a positive counter for the module and the variable.
|
||||||
|
recorder := httptest.NewRecorder()
|
||||||
|
metrics.DefaultRegistry.MetricsHandler().ServeHTTP(recorder, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/internal/metrics", nil))
|
||||||
|
require.Regexp(
|
||||||
|
fmt.Sprintf(`render_secret_skipped[^\n]*module=%q[^\n]*variable="rdVar"[^\n]* [1-9]`, active.ModuleId),
|
||||||
|
recorder.Body.String(),
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// requireBusinessError decodes the business error carried in the gRPC status
|
||||||
|
// details and asserts its error code.
|
||||||
|
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"})
|
||||||
|
|
||||||
|
// Variables: one SECRET, one TEXT.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// Module A: the default config references only the TEXT variable, so the
|
||||||
|
// initial config is persisted on the first connection.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 1) Update: a SECRET variable in a UI-exposed field is rejected with a
|
||||||
|
// per-path detail, and the config is not changed.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом 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))
|
||||||
|
|
||||||
|
// 2) unsafe=true does not bypass the policy.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polSecret", be.Details["secrets"])
|
||||||
|
|
||||||
|
// 3) Insert path (empty Id): the new config is not created.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polSecret", be.Details["secrets"])
|
||||||
|
|
||||||
|
// 4) Nested array path: the detail key matches the gojsonschema field
|
||||||
|
// format used by schema validation errors.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polSecret", be.Details["oauth.clients.0.loginEndpoint"])
|
||||||
|
|
||||||
|
// 5) A SECRET variable outside a UI-exposed field is allowed.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// Restore the original data for the sync checks below.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 6) Sync with a compliant active config succeeds and re-pushes it.
|
||||||
|
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())
|
||||||
|
|
||||||
|
// 7) The variable referenced by the stored config becomes SECRET (the
|
||||||
|
// legacy regime): sync is rejected with per-path details and nothing is
|
||||||
|
// re-pushed.
|
||||||
|
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)
|
||||||
|
// The variable change itself triggers a re-render push.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polText", be.Details["secrets"])
|
||||||
|
require.Equal("UI-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polText", be.Details["oauth.clients.0.loginEndpoint"])
|
||||||
|
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
// No extra push: the rejected sync did not emit a change event.
|
||||||
|
require.Len(eventHandler.ReceivedConfigs(), pushedBefore+1)
|
||||||
|
|
||||||
|
// 8) First connection of module B: the default config references a SECRET
|
||||||
|
// variable in a UI-exposed field, so the initial config is not persisted.
|
||||||
|
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 // the connection is rejected by the write policy
|
||||||
|
}()
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
|
||||||
|
requireBusinessError(require,
|
||||||
|
apiCli.Invoke("config/config/get_active_config_by_module_name").
|
||||||
|
JsonRequestBody(domain.GetByModuleNameRequest{ModuleName: "SecretPolicyB"}).
|
||||||
|
Do(t.Context()),
|
||||||
|
domain.ErrorCodeConfigNotFound)
|
||||||
|
|
||||||
|
// 9) Unknown module id (no schema row at all): the write policy must not
|
||||||
|
// panic on the missing schema — the request fails with the regular
|
||||||
|
// schema-not-found error, not an internal one.
|
||||||
|
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)
|
||||||
|
|
||||||
|
// 10) mark_config_as_active: the active config of module A now violates
|
||||||
|
// the policy (its referenced variable became SECRET after the config was
|
||||||
|
// saved — the legacy regime). Activating a saved config must pass the
|
||||||
|
// policy, so rolling back to the violating config is rejected with
|
||||||
|
// per-path details and the active config is not switched.
|
||||||
|
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-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polText", be.Details["secrets"])
|
||||||
|
require.Equal("UI-экспортируемое поле не должно ссылаться на переменную с типом 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)
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package subscription_test
|
package tests_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -14,28 +14,28 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
testModuleId = "test-module-id"
|
subscriptionTestModuleId = "test-module-id"
|
||||||
testModuleName = "test-module"
|
subscriptionTestModuleName = "test-module"
|
||||||
|
|
||||||
leaderConnId = "conn-1"
|
subscriptionLeaderConnId = "conn-1"
|
||||||
followerConnId = "conn-2"
|
subscriptionFollowerConnId = "conn-2"
|
||||||
|
|
||||||
leaderAddress = "10.0.0.1:9000"
|
subscriptionLeaderAddress = "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 storedLog struct {
|
type subscriptionStoredLog struct {
|
||||||
message any
|
message any
|
||||||
fields map[string]string
|
fields map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
type loggerSpy struct {
|
type subscriptionLoggerSpy struct {
|
||||||
infos []storedLog
|
infos []subscriptionStoredLog
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {
|
func (l *subscriptionLoggerSpy) Info(ctx context.Context, message any, fields ...log.Field) {
|
||||||
entry := storedLog{
|
entry := subscriptionStoredLog{
|
||||||
message: message,
|
message: message,
|
||||||
fields: make(map[string]string, len(fields)),
|
fields: make(map[string]string, len(fields)),
|
||||||
}
|
}
|
||||||
@@ -45,32 +45,32 @@ func (l *loggerSpy) Info(ctx context.Context, message any, fields ...log.Field)
|
|||||||
l.infos = append(l.infos, entry)
|
l.infos = append(l.infos, entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *loggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *subscriptionLoggerSpy) Error(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *subscriptionLoggerSpy) Warn(ctx context.Context, message any, fields ...log.Field) {}
|
||||||
|
|
||||||
func (l *loggerSpy) Debug(ctx context.Context, message any, fields ...log.Field) {}
|
func (l *subscriptionLoggerSpy) 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: testModuleId, Name: testModuleName}}, nil
|
return []entity.Module{{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}}, 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: testModuleId, Name: testModuleName}, nil
|
return &entity.Module{Id: subscriptionTestModuleId, Name: subscriptionTestModuleName}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type backendRepoSpy struct {
|
type subscriptionBackendRepoSpy struct {
|
||||||
forLeaderElection []entity.Backend
|
forLeaderElection []entity.Backend
|
||||||
all []entity.Backend
|
all []entity.Backend
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *backendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
|
func (r *subscriptionBackendRepoSpy) GetForLeaderElection(ctx context.Context, moduleId string) ([]entity.Backend, error) {
|
||||||
return r.forLeaderElection, nil
|
return r.forLeaderElection, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *backendRepoSpy) All(ctx context.Context) ([]entity.Backend, error) {
|
func (r *subscriptionBackendRepoSpy) 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, input []byte) ([]byte, error) {
|
func (s *variableServiceSpy) RenderConfig(ctx context.Context, moduleId string, 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 := &loggerSpy{}
|
logger := &subscriptionLoggerSpy{}
|
||||||
rooms := etp.NewServer().Rooms()
|
rooms := etp.NewServer().Rooms()
|
||||||
rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(testModuleName))
|
rooms.Join(&etp.Conn{}, subscription.BackendsChangingRoom(subscriptionTestModuleName))
|
||||||
service := newService(logger, rooms, &backendRepoSpy{
|
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
|
||||||
forLeaderElection: []entity.Backend{
|
forLeaderElection: []entity.Backend{
|
||||||
electedInstance(leaderConnId, leaderAddress),
|
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress),
|
||||||
electedInstance(followerConnId, successorAddress),
|
subscriptionElectedInstance(subscriptionFollowerConnId, successorAddress),
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
err := service.NotifyBackendsChanged(t.Context(), testModuleId)
|
err := service.NotifyBackendsChanged(t.Context(), subscriptionTestModuleId)
|
||||||
|
|
||||||
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(testModuleName, logger.infos[0].fields["moduleName"])
|
require.Equal(subscriptionTestModuleName, logger.infos[0].fields["moduleName"])
|
||||||
require.Equal(leaderAddress, logger.infos[0].fields["leaderAddress"],
|
require.Equal(subscriptionLeaderAddress, 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 := &loggerSpy{}
|
logger := &subscriptionLoggerSpy{}
|
||||||
rooms := etp.NewServer().Rooms()
|
rooms := etp.NewServer().Rooms()
|
||||||
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
||||||
service := newService(logger, rooms, &backendRepoSpy{
|
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
|
||||||
all: []entity.Backend{
|
all: []entity.Backend{
|
||||||
electedInstance(leaderConnId, leaderAddress),
|
subscriptionElectedInstance(subscriptionLeaderConnId, subscriptionLeaderAddress),
|
||||||
electedInstance(followerConnId, successorAddress),
|
subscriptionElectedInstance(subscriptionFollowerConnId, 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(testModuleName+"="+leaderAddress, logger.infos[0].fields["moduleLeaders"],
|
require.Equal(subscriptionTestModuleName+"="+subscriptionLeaderAddress, logger.infos[0].fields["moduleLeaders"],
|
||||||
"only the elected module and only its leader are published, the plain module is not listed")
|
"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 := &loggerSpy{}
|
logger := &subscriptionLoggerSpy{}
|
||||||
rooms := etp.NewServer().Rooms()
|
rooms := etp.NewServer().Rooms()
|
||||||
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
rooms.Join(&etp.Conn{}, subscription.RoutingChangingRoom())
|
||||||
service := newService(logger, rooms, &backendRepoSpy{
|
service := newService(logger, rooms, &subscriptionBackendRepoSpy{
|
||||||
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 electedInstance(connId string, address string) entity.Backend {
|
func subscriptionElectedInstance(connId string, address string) entity.Backend {
|
||||||
return entity.Backend{
|
return entity.Backend{
|
||||||
WsConnectionId: connId,
|
WsConnectionId: connId,
|
||||||
ModuleId: testModuleId,
|
ModuleId: subscriptionTestModuleId,
|
||||||
ModuleName: testModuleName,
|
ModuleName: subscriptionTestModuleName,
|
||||||
Address: address,
|
Address: address,
|
||||||
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
|
ModuleLeaderMode: cluster.ModuleLeaderModeRequestElection,
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
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}
|
||||||
|
}
|
||||||
|
|
||||||
|
// secretVar builds a SECRET variable named "s1" (the name is fixed for all
|
||||||
|
// the render cases below).
|
||||||
|
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[].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[].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()
|
||||||
|
|
||||||
|
// A variable that does not exist cannot be proven SECRET, so it is
|
||||||
|
// reported undefined instead of silently kept as a literal.
|
||||||
|
_, 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 TestRenderCompositeInUISubstituted(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
// a composite JSON string on a UI path is report-only: references are
|
||||||
|
// substituted, the secret policy does not apply
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
var m map[string]any
|
||||||
|
err = json.Unmarshal(out, &m)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unmarshal output: %v", err)
|
||||||
|
}
|
||||||
|
got, ok := m["secrets"].(string)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("$.secrets is not a string: %v", m["secrets"])
|
||||||
|
}
|
||||||
|
if !strings.Contains(got, "top") {
|
||||||
|
t.Fatalf("$.secrets = %s, want the secret value substituted", got)
|
||||||
|
}
|
||||||
|
// the simple leaf on a UI path still follows the policy
|
||||||
|
if got := m["plain"]; got != "_Var(s1)" {
|
||||||
|
t.Fatalf("$.plain = %v, want the literal placeholder", got)
|
||||||
|
}
|
||||||
|
if len(skipped) != 1 || skipped[0].Path != "$.plain" || skipped[0].Variable != "s1" {
|
||||||
|
t.Fatalf("skipped = %v, want [{$.plain s1}]", skipped)
|
||||||
|
}
|
||||||
|
if len(undefined) != 0 {
|
||||||
|
t.Fatalf("undefined = %v, want empty", 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)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user