MSP-8299 linter fix

This commit is contained in:
ziminis committed 2026-11-27 18:36:41 +07:00
1 parent 3a191331a7
commit 0cf9de5629
8 files changed
+408 -282

No files matched your search

+1 -1
View File
@@ -7,7 +7,7 @@ import (
type VariableType = string
var (
const (
SecretType VariableType = "SECRET"
TextType VariableType = "TEXT"
)
+69 -63
View File
@@ -147,69 +147,7 @@ func (c Config) CreateUpdateConfig(
Config: newConfig, IsChanged: true}, err
}
variableExtractionResult, err := c.extractAndCheckVariables(ctx, req.Id, req.Data)
if err != nil {
return nil, errors.WithMessage(err, "extract variables")
}
oldConfig, err := c.configRepo.GetById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get old config")
}
if oldConfig == nil {
return nil, entity.ErrConfigNotFound
}
isMatch, err := isEqualConfigs(oldConfig, req)
if err != nil {
return nil, errors.WithMessage(err, "compare data configs")
}
if isMatch {
c.logger.Info(ctx, "no changes in config; skip update")
return &domain.CreateUpdateConfigResponse{Config: configToDto(*oldConfig, nil), IsChanged: false}, nil
}
config := entity.Config{
Id: req.Id,
Name: req.Name,
Data: req.Data,
Version: req.Version,
AdminId: adminId,
}
updated, err := c.configRepo.UpdateByVersion(ctx, config)
if err != nil {
return nil, errors.WithMessage(err, "update config")
}
if !updated {
return nil, entity.ErrConfigConflictUpdate
}
err = c.configHistoryService.OnUpdateConfig(ctx, *oldConfig)
if err != nil {
return nil, errors.WithMessage(err, "change config history")
}
err = c.variableService.SaveVariableLinks(ctx, config.Id, variableExtractionResult.VariableLinks)
if err != nil {
return nil, errors.WithMessage(err, "save variable links")
}
if oldConfig.Active {
err = c.emitChangeActiveConfigEvent(ctx, oldConfig.ModuleId)
if err != nil {
return nil, errors.WithMessage(err, "emit change active config event")
}
}
newConfig := entity.Config{
Id: req.Id,
Name: req.Name,
ModuleId: req.ModuleId,
Data: req.Data,
Version: req.Version + 1,
Active: oldConfig.Active,
}
return &domain.CreateUpdateConfigResponse{
Config: configToDto(newConfig, nil), IsChanged: true}, nil
return c.updateConfig(ctx, adminId, req)
}
func (c Config) GetConfigById(ctx context.Context, configId string) (*domain.Config, error) {
@@ -317,6 +255,74 @@ func (c Config) SyncConfig(ctx context.Context, moduleName string) error {
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)
if err != nil {
return nil, errors.WithMessage(err, "extract variables")
}
oldConfig, err := c.configRepo.GetById(ctx, req.Id)
if err != nil {
return nil, errors.WithMessage(err, "get old config")
}
if oldConfig == nil {
return nil, entity.ErrConfigNotFound
}
isMatch, err := isEqualConfigs(oldConfig, req)
if err != nil {
return nil, errors.WithMessage(err, "compare data configs")
}
if isMatch {
c.logger.Info(ctx, "no changes in config; skip update")
return &domain.CreateUpdateConfigResponse{Config: configToDto(*oldConfig, nil), IsChanged: false}, nil
}
config := entity.Config{
Id: req.Id,
Name: req.Name,
Data: req.Data,
Version: req.Version,
AdminId: adminId,
}
updated, err := c.configRepo.UpdateByVersion(ctx, config)
if err != nil {
return nil, errors.WithMessage(err, "update config")
}
if !updated {
return nil, entity.ErrConfigConflictUpdate
}
err = c.configHistoryService.OnUpdateConfig(ctx, *oldConfig)
if err != nil {
return nil, errors.WithMessage(err, "change config history")
}
err = c.variableService.SaveVariableLinks(ctx, config.Id, variableExtractionResult.VariableLinks)
if err != nil {
return nil, errors.WithMessage(err, "save variable links")
}
if oldConfig.Active {
err = c.emitChangeActiveConfigEvent(ctx, oldConfig.ModuleId)
if err != nil {
return nil, errors.WithMessage(err, "emit change active config event")
}
}
newConfig := entity.Config{
Id: req.Id,
Name: req.Name,
ModuleId: req.ModuleId,
Data: req.Data,
Version: req.Version + 1,
Active: oldConfig.Active,
}
return &domain.CreateUpdateConfigResponse{
Config: configToDto(newConfig, nil), IsChanged: true}, nil
}
func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.CreateUpdateConfigRequest) (domain.Config, error) {
config := entity.Config{
Id: uuid.NewString(),
+151 -91
View File
@@ -5,13 +5,13 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"sort"
"strings"
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/entity/xtypes"
"isp-config-service/helpers"
"maps"
"sort"
"strings"
"github.com/txix-open/isp-kit/json"
"github.com/txix-open/isp-kit/rc"
@@ -91,7 +91,7 @@ func NewService(
emitter Emitter,
variableService VariableService,
variableRepo VariableRepo,
ConfigWriteDeny bool,
configWriteDeny bool,
logger log.Logger,
) Service {
return Service{
@@ -103,7 +103,7 @@ func NewService(
emitter: emitter,
variableService: variableService,
variableRepo: variableRepo,
configWriteDeny: ConfigWriteDeny,
configWriteDeny: configWriteDeny,
logger: logger,
}
}
@@ -243,40 +243,10 @@ func (s Service) OnModuleConfigSchema(
}
if config == nil {
// Check the policy before the initial config is written, so a violating
// default config is never persisted on the first module connection.
err = s.FilterSecretParams(ctx, data.Config, moduleId)
config, err = s.storeInitialConfig(ctx, conn, moduleId, data)
if err != nil {
return errors.WithMessage(err, "filter secret params in store")
return err
}
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, moduleId, config.Data)
@@ -313,57 +283,136 @@ func (s Service) FilterSecretParams(ctx context.Context, config json.RawMessage,
return nil
}
// Remember paths tagged `x-ui-exposed` and `x-sensitive`
uiPaths, err := schema.UIExposedPaths(moduleSchema.Data)
uiPaths, sensitivePaths, err := policyPaths(moduleSchema.Data)
if err != nil {
return errors.WithMessage(err, "read schema params")
}
sensitivePaths, err := schema.SensitivePaths(moduleSchema.Data)
if err != nil {
return errors.WithMessage(err, "read schema params")
return err
}
if len(uiPaths) == 0 && len(sensitivePaths) == 0 {
return nil
}
// Remember paths to placeholders
placeholders, err := rc.PlaceHolderReader(config)
if err != nil {
return errors.WithMessage(err, "read config placeholders")
}
// Names of variables referenced on ui-exposed and sensitive paths;
// refsByPath keeps the ui-exposed references for the report
names := make(map[string]struct{})
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)
}
}
sensitiveSet := make(map[string]struct{}, len(sensitivePaths))
for _, path := range sensitivePaths {
sensitiveSet[path] = struct{}{}
for _, name := range placeholders[path] {
names[name] = struct{}{}
}
}
return refsByPath, names, sensitiveSet
}
variableTypes := make(map[string]entity.VariableType, len(names))
if len(names) > 0 {
variables, err := s.variableRepo.GetVariablesByName(ctx, names)
if err != nil {
return errors.WithMessage(err, "get variables")
}
for _, variable := range variables {
variableTypes[variable.Name] = variable.Type
}
}
errorDetails := make(map[string]string)
// ui-exposed fields must not reference SECRET variables
// 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 {
@@ -379,39 +428,47 @@ func (s Service) FilterSecretParams(ctx context.Context, config json.RawMessage,
if len(secrets) > 1 {
plural = "переменные"
}
msg := fmt.Sprintf("UI-экспортируемое поле не должно ссылаться на %s с типом SECRET: %s", plural, strings.Join(secrets, ", "))
errorDetails[policyFieldPath(path)] = msg
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
}
if len(sensitivePaths) > 0 {
values, err := leafValuesAt(config, sensitiveSet)
if err != nil {
return errors.WithMessage(err, "read config values")
for _, path := range sensitivePaths {
value, exists := values[path]
if !exists || value == "" {
continue
}
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 {
msg := fmt.Sprintf("sensitive-поле должно ссылаться только на переменные с типом SECRET: переменная %s имеет тип %s", name, t)
errorDetails[policyFieldPath(path)] = msg
}
continue
}
errorDetails[policyFieldPath(path)] = "plain value in sensitive field"
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"
}
if len(errorDetails) == 0 {
return nil
}
return errors.WithMessage(domain.NewConfigValidationError(errorDetails), "config violates the secret policy")
return details, nil
}
// leafValuesAt collects the raw values of the config's string leaves located
@@ -424,7 +481,10 @@ func leafValuesAt(data []byte, paths map[string]struct{}) (map[string]string, er
}
return value
})
return values, err
if err != nil {
return nil, errors.WithMessage(err, "read config leaf values")
}
return values, nil
}
func policyFieldPath(canonical string) string {
+69 -55
View File
@@ -1,4 +1,4 @@
package module
package module_test
import (
"context"
@@ -9,6 +9,7 @@ import (
"isp-config-service/domain"
"isp-config-service/entity"
"isp-config-service/service/module"
kitjson "github.com/txix-open/isp-kit/json"
)
@@ -39,6 +40,12 @@ func (r fakeVariableRepo) GetVariablesByName(ctx context.Context, names map[stri
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{
@@ -58,25 +65,20 @@ func policyTestSchema(t *testing.T) []byte {
return schemaData
}
func TestFilterSecretParams(t *testing.T) {
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},
}}
type policyTestCase struct {
name string
config string
wantErr bool
wantDetails map[string]string
}
tests := []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{
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
"secrets": "UI-экспортируемое поле не должно ссылаться на переменную с типом SECRET: sec_var",
},
},
@@ -84,21 +86,23 @@ func TestFilterSecretParams(t *testing.T) {
name: "ui-exposed multiple secret references",
config: `{"secrets": "_Var(sec_var) _Var(sec_var2)"}`,
wantErr: true,
wantDetails: map[string]string{
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{"token": "plain value in sensitive field"},
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{
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
"token": "sensitive-поле должно ссылаться только на переменные с типом SECRET: переменная txt_var имеет тип TEXT",
},
},
@@ -119,10 +123,12 @@ func TestFilterSecretParams(t *testing.T) {
config: `{"token": "{\"a\": 1}"}`,
},
{
name: "sensitive mixed value",
config: `{"token": "prefix _Var(sec_var)"}`,
wantErr: true,
wantDetails: map[string]string{"token": "plain value in sensitive field"},
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",
@@ -140,7 +146,7 @@ func TestFilterSecretParams(t *testing.T) {
name: "both violations at once",
config: `{"secrets": "_Var(sec_var)", "token": "plain-pass"}`,
wantErr: true,
wantDetails: map[string]string{
wantDetails: map[string]string{ //nolint:gosec // test fixture, not credentials
"secrets": "UI-экспортируемое поле не должно ссылаться на переменную с типом SECRET: sec_var",
"token": "plain value in sensitive field",
},
@@ -150,15 +156,26 @@ func TestFilterSecretParams(t *testing.T) {
config: `{"secrets": "_Var(txt_var)", "token": "_Var(sec_var)"}`,
},
}
for _, test := range tests {
}
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) {
s := Service{
configWriteDeny: true,
configSchemaRepo: fakeSchemaRepo{
schema: &entity.ConfigSchema{Id: "s1", ModuleId: moduleId, Data: policyTestSchema(t)},
},
variableRepo: varRepo,
}
t.Parallel()
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(test.config), moduleId)
if !test.wantErr {
@@ -179,27 +196,24 @@ func TestFilterSecretParams(t *testing.T) {
}
func TestFilterSecretParamsDisabled(t *testing.T) {
const moduleId = "m1"
s := Service{
configWriteDeny: false,
configSchemaRepo: fakeSchemaRepo{
schema: &entity.ConfigSchema{Id: "s1", ModuleId: moduleId, Data: policyTestSchema(t)},
},
variableRepo: fakeVariableRepo{},
}
t.Parallel()
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"secrets": "_Var(sec_var)", "token": "plain-pass"}`), moduleId)
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) {
s := Service{
configWriteDeny: true,
configSchemaRepo: fakeSchemaRepo{schema: nil},
variableRepo: fakeVariableRepo{},
}
t.Parallel()
s := policyService(nil, fakeVariableRepo{}, true)
err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"token": "plain-pass"}`), "m1")
if err != nil {
@@ -208,6 +222,8 @@ func TestFilterSecretParamsWithoutSchema(t *testing.T) {
}
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"}},
@@ -215,13 +231,11 @@ func TestFilterSecretParamsSchemaWithoutPolicyPaths(t *testing.T) {
if err != nil {
t.Fatalf("marshal schema: %v", err)
}
s := Service{
configWriteDeny: true,
configSchemaRepo: fakeSchemaRepo{
schema: &entity.ConfigSchema{Id: "s1", ModuleId: "m1", Data: schemaData},
},
variableRepo: fakeVariableRepo{},
}
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 {
+77 -31
View File
@@ -1,4 +1,4 @@
package variable
package variable_test
import (
"encoding/json"
@@ -6,18 +6,23 @@ import (
"testing"
"isp-config-service/entity"
"isp-config-service/service/variable"
)
func textVar(name, value string) entity.Variable {
return entity.Variable{Name: name, Type: entity.TextType, Value: value}
}
func secretVar(name, value string) entity.Variable {
return entity.Variable{Name: name, Type: entity.SecretType, 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) {
out, skipped, undefined, err := Render(
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
@@ -34,10 +39,12 @@ func TestRenderSubstitutesNonUI(t *testing.T) {
}
func TestRenderKeepsSecretInUI(t *testing.T) {
out, skipped, undefined, err := Render(
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(s1)"}`),
[]string{"$.a"},
map[string]entity.Variable{"s1": secretVar("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -57,10 +64,12 @@ func TestRenderKeepsSecretInUI(t *testing.T) {
}
func TestRenderSameVarUINonUI(t *testing.T) {
out, skipped, _, err := Render(
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"ui":"_Var(s1)","plain":"_Var(s1)"}`),
[]string{"$.ui"},
map[string]entity.Variable{"s1": secretVar("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -74,10 +83,12 @@ func TestRenderSameVarUINonUI(t *testing.T) {
}
func TestRenderMixedUILeaf(t *testing.T) {
out, skipped, _, err := Render(
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("s1", "top")},
map[string]entity.Variable{"t1": textVar("t1", "tv"), "s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -91,10 +102,12 @@ func TestRenderMixedUILeaf(t *testing.T) {
}
func TestRenderSecretOutsideUI(t *testing.T) {
out, skipped, _, err := Render(
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"a":"_Var(s1)"}`),
nil,
map[string]entity.Variable{"s1": secretVar("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -108,10 +121,12 @@ func TestRenderSecretOutsideUI(t *testing.T) {
}
func TestRenderArrayPath(t *testing.T) {
out, skipped, _, err := Render(
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("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -125,7 +140,9 @@ func TestRenderArrayPath(t *testing.T) {
}
func TestRenderUndefined(t *testing.T) {
out, skipped, undefined, err := Render(
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(ghost)"}`),
nil,
map[string]entity.Variable{},
@@ -145,9 +162,11 @@ func TestRenderUndefined(t *testing.T) {
}
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 := Render(
_, skipped, undefined, err := variable.Render(
[]byte(`{"a":"_Var(ghost)"}`),
[]string{"$.a"},
map[string]entity.Variable{},
@@ -164,7 +183,9 @@ func TestRenderUndefinedInUI(t *testing.T) {
}
func TestRenderToInt(t *testing.T) {
out, _, _, err := Render(
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"n":"_ToInt(_Var(n1))"}`),
nil,
map[string]entity.Variable{"n1": textVar("n1", "42")},
@@ -178,10 +199,12 @@ func TestRenderToInt(t *testing.T) {
}
func TestRenderToIntSecretInUI(t *testing.T) {
out, skipped, _, err := Render(
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"n":"_ToInt(_Var(s1))"}`),
[]string{"$.n"},
map[string]entity.Variable{"s1": secretVar("s1", "42")},
map[string]entity.Variable{"s1": secretVar("42")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -195,7 +218,9 @@ func TestRenderToIntSecretInUI(t *testing.T) {
}
func TestRenderKeysUntouched(t *testing.T) {
out, _, _, err := Render(
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"_Var(k)":"_Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
@@ -209,10 +234,12 @@ func TestRenderKeysUntouched(t *testing.T) {
}
func TestRenderSkippedDeduped(t *testing.T) {
_, skipped, _, err := Render(
t.Parallel()
_, skipped, _, err := variable.Render(
[]byte(`{"a":"_Var(s1)_Var(s1)"}`),
[]string{"$.a"},
map[string]entity.Variable{"s1": secretVar("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
@@ -223,7 +250,9 @@ func TestRenderSkippedDeduped(t *testing.T) {
}
func TestRenderNonStringUILeaf(t *testing.T) {
out, skipped, _, err := Render(
t.Parallel()
out, skipped, _, err := variable.Render(
[]byte(`{"n":5}`),
[]string{"$.n"},
map[string]entity.Variable{},
@@ -240,7 +269,9 @@ func TestRenderNonStringUILeaf(t *testing.T) {
}
func TestRenderInvalidJSON(t *testing.T) {
_, _, _, err := Render(
t.Parallel()
out, skipped, undefined, err := variable.Render(
[]byte(`{"a":`),
nil,
map[string]entity.Variable{},
@@ -248,10 +279,15 @@ func TestRenderInvalidJSON(t *testing.T) {
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) {
out, _, _, err := Render(
t.Parallel()
out, _, _, err := variable.Render(
[]byte(`{"a":"line1\nline2 _Var(v1)"}`),
nil,
map[string]entity.Variable{"v1": textVar("v1", "x")},
@@ -265,6 +301,8 @@ func TestRenderEscapes(t *testing.T) {
}
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)"})
@@ -279,20 +317,25 @@ func TestRenderCompositeInUISubstituted(t *testing.T) {
t.Fatalf("marshal document: %v", err)
}
out, skipped, undefined, err := Render(
out, skipped, undefined, err := variable.Render(
doc,
[]string{"$.secrets", "$.plain"},
map[string]entity.Variable{"s1": secretVar("s1", "top")},
map[string]entity.Variable{"s1": secretVar("top")},
)
if err != nil {
t.Fatalf("Render: %v", err)
}
var m map[string]any
if err := json.Unmarshal(out, &m); err != nil {
err = json.Unmarshal(out, &m)
if err != nil {
t.Fatalf("unmarshal output: %v", err)
}
if got := m["secrets"].(string); !strings.Contains(got, "top") {
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
@@ -308,6 +351,8 @@ func TestRenderCompositeInUISubstituted(t *testing.T) {
}
func TestRenderCompositeUndefinedCollected(t *testing.T) {
t.Parallel()
composite, err := json.Marshal([]any{"_Var(ghost)"})
if err != nil {
t.Fatalf("marshal composite: %v", err)
@@ -317,7 +362,7 @@ func TestRenderCompositeUndefinedCollected(t *testing.T) {
t.Fatalf("marshal document: %v", err)
}
out, skipped, undefined, err := Render(
out, skipped, undefined, err := variable.Render(
doc,
[]string{"$.secrets"},
map[string]entity.Variable{},
@@ -326,7 +371,8 @@ func TestRenderCompositeUndefinedCollected(t *testing.T) {
t.Fatalf("Render: %v", err)
}
var m map[string]any
if err := json.Unmarshal(out, &m); err != nil {
err = json.Unmarshal(out, &m)
if err != nil {
t.Fatalf("unmarshal output: %v", err)
}
if got, want := m["secrets"], string(composite); got != want {
+28 -28
View File
@@ -65,7 +65,7 @@ func NewService(
secretSkipped: metrics.GetOrRegister(metrics.DefaultRegistry,
prometheus.NewCounterVec(prometheus.CounterOpts{
Subsystem: "config",
Name: "render_secret_skipped",
Name: "render_secret_skipped_total",
Help: "Secret variables left unrendered in UI-exposed config leaves",
}, []string{"module", "variable"}),
),
@@ -85,33 +85,6 @@ type uiPathsCache struct {
entries map[string]cachedUIPaths
}
// 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) All(ctx context.Context) ([]domain.Variable, error) {
variables, err := s.repo.All(ctx)
if err != nil {
@@ -334,6 +307,33 @@ func (s Service) SaveVariableLinks(ctx context.Context, configId string, links [
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 {
value := variable.Value
if variable.Type == "SECRET" {
+2 -2
View File
@@ -22,7 +22,7 @@ type renderPolicyConfig struct {
Plain string
}
//nolint:funlen,paralleltest
//nolint:funlen,paralleltest,noctx
func TestRenderSecretSkip(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
@@ -92,7 +92,7 @@ func TestRenderSecretSkip(t *testing.T) {
// The skip is observable: a positive counter for the module and the variable.
recorder := httptest.NewRecorder()
metrics.DefaultRegistry.MetricsHandler().ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/internal/metrics", nil))
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(),
+11 -11
View File
@@ -55,7 +55,7 @@ func requireBusinessError(require *require.Assertions, err error, code int) busi
return businessError{}
}
//nolint:funlen,paralleltest
//nolint:funlen,paralleltest,testifylint
func TestSecretPolicy(t *testing.T) {
require := require.New(t)
logger := setupTest(t)
@@ -113,14 +113,14 @@ func TestSecretPolicy(t *testing.T) {
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polSecret", be.Details["secrets"])
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.EqualValues(
require.JSONEq(
`{"secrets":"_Var(polText)","plain":"p","oauth":{"clients":[{"clientId":"a","loginEndpoint":"_Var(polText)"}]}}`,
string(active.Data))
@@ -137,7 +137,7 @@ func TestSecretPolicy(t *testing.T) {
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polSecret", be.Details["secrets"])
require.Equal("UI-экспортируемое поле не должно ссылаться на переменную с типом SECRET: polSecret", be.Details["secrets"])
// 3) Insert path (empty Id): the new config is not created.
be = requireBusinessError(require,
@@ -149,7 +149,7 @@ func TestSecretPolicy(t *testing.T) {
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polSecret", be.Details["secrets"])
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.
@@ -164,7 +164,7 @@ func TestSecretPolicy(t *testing.T) {
}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polSecret", be.Details["oauth.clients.0.loginEndpoint"])
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").
@@ -223,12 +223,12 @@ func TestSecretPolicy(t *testing.T) {
JsonRequestBody(domain.SyncConfigRequest{ModuleName: "SecretPolicyA"}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polText", be.Details["secrets"])
require.Equal("references SECRET variable polText", be.Details["oauth.clients.0.loginEndpoint"])
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.Equal(pushedBefore+1, len(eventHandler.ReceivedConfigs()))
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.
@@ -295,8 +295,8 @@ func TestSecretPolicy(t *testing.T) {
JsonRequestBody(domain.IdRequest{Id: active.Id}).
Do(t.Context()),
domain.ErrorCodeInvalidConfig)
require.Equal("references SECRET variable polText", be.Details["secrets"])
require.Equal("references SECRET variable polText", be.Details["oauth.clients.0.loginEndpoint"])
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").