From cdf700b062149eff346ea361f5f22d21ba21d8c1 Mon Sep 17 00:00:00 2001 From: ziminis Date: Fri, 27 Nov 2026 16:53:36 +0700 Subject: [PATCH] MSP-8299 add new handling for SECRET type variables and sensitive fields in config --- assembly/locator.go | 5 +- conf/local.go | 1 + controller/api/config.go | 39 +++- entity/variable.go | 19 +- repository/variable.go | 34 +++- service/api/config.go | 46 ++++- service/module/service.go | 195 ++++++++++++++++-- service/module/service_test.go | 221 +++++++++++++++++++++ service/subscription/service.go | 4 +- service/variable/render.go | 74 +++++++ service/variable/render_test.go | 341 ++++++++++++++++++++++++++++++++ service/variable/service.go | 127 +++++++++--- tests/acceptance_test.go | 1 + tests/autodiscovery_test.go | 1 + tests/render_secret_test.go | 100 ++++++++++ tests/secret_policy_test.go | 308 +++++++++++++++++++++++++++++ 16 files changed, 1449 insertions(+), 67 deletions(-) create mode 100644 service/module/service_test.go create mode 100644 service/variable/render.go create mode 100644 service/variable/render_test.go create mode 100644 tests/render_secret_test.go create mode 100644 tests/secret_policy_test.go diff --git a/assembly/locator.go b/assembly/locator.go index 06a4e33..794e9be 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -96,7 +96,7 @@ func (l Locator) Config() *Config { configHistoryRepo := repository.NewConfigHistory(l.db) variableRepo := repository.NewVariable(l.db) - variableService := variable.NewService(variableRepo, configRepo, eventRepo) + variableService := variable.NewService(variableRepo, configRepo, eventRepo, configSchemaRepo, l.logger) variableController := api.NewVariable(variableService) etpSrv := etp.NewServer( @@ -134,6 +134,8 @@ func (l Locator) Config() *Config { subscriptionService, emitter, variableService, + variableRepo, + l.cfg.Local.ConfigWriteDeny, l.logger, ) moduleController := controller.NewModule(moduleService, l.logger) @@ -148,6 +150,7 @@ func (l Locator) Config() *Config { configApiService := apisvs.NewConfig( configRepo, moduleRepo, + moduleService, configSchemaRepo, eventRepo, configHistoryApiService, diff --git a/conf/local.go b/conf/local.go index 7b5063c..88a80b8 100644 --- a/conf/local.go +++ b/conf/local.go @@ -15,6 +15,7 @@ type Local struct { InternalClientCredential string `validate:"required"` Rqlite Rqlite Backup rqlite.Backup + ConfigWriteDeny bool } type Rqlite struct { diff --git a/controller/api/config.go b/controller/api/config.go index 2f354bf..a0f9047 100644 --- a/controller/api/config.go +++ b/controller/api/config.go @@ -5,12 +5,13 @@ import ( "context" "strconv" + "isp-config-service/domain" + "isp-config-service/entity" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/apierrors" "google.golang.org/grpc/metadata" - "isp-config-service/domain" - "isp-config-service/entity" ) type ConfigService interface { @@ -184,12 +185,24 @@ func (c Config) GetConfigById(ctx context.Context, req domain.IdRequest) (*domai // @Produce json // @Param body body domain.IdRequest true "id конфигурации для изменения" // @Success 200 -// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден
" +// @Failure 400 {object} apierrors.Error "`errorCode: 2002` - конфиг не найден
`errorCode: 2003` - конфигурация нарушает политику секретных переменных (детали по путям в `details`)
" // @Failure 500 {object} apierrors.Error // @Router /config/mark_config_as_active [POST] func (c Config) MarkConfigAsActive(ctx context.Context, identity domain.IdRequest) error { err := c.service.MarkConfigAsActive(ctx, identity.Id) + + var validationError domain.ConfigValidationError switch { + case errors.As(err, &validationError): + details := map[string]any{} + for key, value := range validationError.Details { + details[key] = value + } + return apierrors.NewBusinessError( + domain.ErrorCodeInvalidConfig, + "invalid config", + err, + ).WithDetails(details) case errors.Is(err, entity.ErrConfigNotFound): return apierrors.NewBusinessError( domain.ErrorCodeConfigNotFound, @@ -272,18 +285,36 @@ func (c Config) UpdateConfigName(ctx context.Context, req domain.UpdateConfigNam // @Produce json // @Param body body domain.SyncConfigRequest true "название модуля" // @Success 200 {object} domain.Config -// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден
`errorCode: 2002` - конфиг не найден" +// @Failure 400 {object} apierrors.Error "`errorCode: 2001` - модуль не найден
`errorCode: 2002` - конфиг не найден
`errorCode: 2003` - в UI-экспонируемых полях активная конфигурация ссылается на секретную переменную" // @Failure 500 {object} apierrors.Error // @Router /config/sync_config [POST] func (c Config) SyncConfig(ctx context.Context, req domain.SyncConfigRequest) error { err := c.service.SyncConfig(ctx, req.ModuleName) + + var validationError domain.ConfigValidationError switch { + case errors.As(err, &validationError): + details := map[string]any{} + for key, value := range validationError.Details { + details[key] = value + } + return apierrors.NewBusinessError( + domain.ErrorCodeInvalidConfig, + "invalid config", + err, + ).WithDetails(details) case errors.Is(err, entity.ErrModuleNotFound): return apierrors.NewBusinessError( domain.ErrorCodeModuleNotFound, "module not found", err, ) + case errors.Is(err, entity.ErrConfigNotFound): + return apierrors.NewBusinessError( + domain.ErrorCodeConfigNotFound, + "config not found", + err, + ) case err != nil: return apierrors.NewInternalServiceError(err) default: diff --git a/entity/variable.go b/entity/variable.go index aa4019d..63d569d 100644 --- a/entity/variable.go +++ b/entity/variable.go @@ -5,13 +5,20 @@ import ( "isp-config-service/entity/xtypes" ) +type VariableType = string + +var ( + SecretType VariableType = "SECRET" + TextType VariableType = "TEXT" +) + type Variable struct { - Name string `json:"name"` - Description string `json:"description"` - Type string `json:"type"` - Value string `json:"value"` - CreatedAt xtypes.Time `json:"created_at"` - UpdatedAt xtypes.Time `json:"updated_at"` + Name string `json:"name"` + Description string `json:"description"` + Type VariableType `json:"type"` + Value string `json:"value"` + CreatedAt xtypes.Time `json:"created_at"` + UpdatedAt xtypes.Time `json:"updated_at"` } type ConfigHasVariable struct { diff --git a/repository/variable.go b/repository/variable.go index 773f23a..fad070e 100644 --- a/repository/variable.go +++ b/repository/variable.go @@ -5,11 +5,12 @@ import ( "database/sql" "strings" - "github.com/Masterminds/squirrel" - "github.com/txix-open/isp-kit/errors" "isp-config-service/entity" "isp-config-service/middlewares/sql_metrics" "isp-config-service/service/rqlite/db" + + "github.com/Masterminds/squirrel" + "github.com/txix-open/isp-kit/errors" ) type Variable struct { @@ -66,6 +67,35 @@ func (r Variable) GetByName(ctx context.Context, name string) (*entity.Variable, return &result, nil } +func (r Variable) GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) { + ctx = sql_metrics.OperationLabelToContext(ctx, "Variables.GetObjectsByName") + + ns := make([]string, 0, len(names)) + for n := range names { + ns = append(ns, n) + } + + if len(ns) == 0 { + return []entity.Variable{}, nil + } + + query, args, err := squirrel.Select("name", "type"). + From(Table("variable")). + Where(squirrel.Eq{"name": ns}). + ToSql() + if err != nil { + return nil, errors.WithMessage(err, "build query") + } + + result := make([]entity.Variable, 0) + err = r.db.Select(ctx, &result, query, args...) + if err != nil { + return nil, errors.WithMessagef(err, "select: %s", query) + } + + return result, nil +} + func (r Variable) Insert(ctx context.Context, variable entity.Variable) error { ctx = sql_metrics.OperationLabelToContext(ctx, "Variable.Insert") diff --git a/service/api/config.go b/service/api/config.go index 6f8079c..6159d69 100644 --- a/service/api/config.go +++ b/service/api/config.go @@ -4,15 +4,16 @@ import ( "context" "time" + "isp-config-service/domain" + "isp-config-service/entity" + "isp-config-service/entity/xtypes" + "github.com/google/uuid" "github.com/txix-open/go-cmp/cmp" "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" "github.com/txix-open/isp-kit/log" "github.com/xeipuuv/gojsonschema" - "isp-config-service/domain" - "isp-config-service/entity" - "isp-config-service/entity/xtypes" ) type ConfigRepo interface { @@ -39,9 +40,14 @@ type VariableService interface { SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error } +type ModuleService interface { + FilterSecretParams(ctx context.Context, config json.RawMessage, moduleId string) error +} + type Config struct { configRepo ConfigRepo moduleRepo ModuleRepo + moduleService ModuleService schemaRepo SchemaRepo eventRepo EventRepo configHistoryService ConfigHistoryService @@ -52,6 +58,7 @@ type Config struct { func NewConfig( configRepo ConfigRepo, moduleRepo ModuleRepo, + moduleService ModuleService, schemaRepo SchemaRepo, eventRepo EventRepo, configHistoryService ConfigHistoryService, @@ -61,6 +68,7 @@ func NewConfig( return Config{ configRepo: configRepo, moduleRepo: moduleRepo, + moduleService: moduleService, schemaRepo: schemaRepo, eventRepo: eventRepo, configHistoryService: configHistoryService, @@ -121,8 +129,13 @@ func (c Config) CreateUpdateConfig( adminId int, req domain.CreateUpdateConfigRequest, ) (*domain.CreateUpdateConfigResponse, error) { + err := c.moduleService.FilterSecretParams(ctx, req.Data, req.ModuleId) + if err != nil { + return nil, errors.WithMessage(err, "filter secret params") + } + if !req.Unsafe { - err := c.validateConfigUpdate(ctx, req.ModuleId, req.Data) + err = c.validateConfigUpdate(ctx, req.ModuleId, req.Data) if err != nil { return nil, errors.WithMessage(err, "validate config") } @@ -220,6 +233,11 @@ func (c Config) MarkConfigAsActive(ctx context.Context, configId string) error { 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") @@ -277,6 +295,20 @@ func (c Config) SyncConfig(ctx context.Context, moduleName string) error { } 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") @@ -295,6 +327,12 @@ func (c Config) insertNewConfig(ctx context.Context, adminId int, req domain.Cre Active: false, 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. extractResult, err := c.extractAndCheckVariables(ctx, config.Id, config.Data) if err != nil { diff --git a/service/module/service.go b/service/module/service.go index 7f24341..7c1d19d 100644 --- a/service/module/service.go +++ b/service/module/service.go @@ -4,18 +4,25 @@ import ( "context" "crypto/sha256" "encoding/hex" + "fmt" + "sort" "strings" + "isp-config-service/domain" + "isp-config-service/entity" + "isp-config-service/entity/xtypes" + "isp-config-service/helpers" + + "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/txix-open/etp/v4" "github.com/txix-open/etp/v4/store" "github.com/txix-open/isp-kit/cluster" "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/log" - "isp-config-service/domain" - "isp-config-service/entity" - "isp-config-service/entity/xtypes" - "isp-config-service/helpers" ) const ( @@ -38,6 +45,7 @@ type BackendService interface { type ConfigSchemaRepo interface { Upsert(ctx context.Context, schema entity.ConfigSchema) error + GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) } type ConfigRepo interface { @@ -45,8 +53,12 @@ type ConfigRepo interface { GetActive(ctx context.Context, moduleId string) (*entity.Config, error) } +type VariableRepo interface { + GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) +} + type VariableService interface { - RenderConfig(ctx context.Context, input []byte) ([]byte, error) + RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) ExtractVariables(ctx context.Context, configId string, input []byte) (*domain.VariableExtractionResult, error) SaveVariableLinks(ctx context.Context, configId string, links []entity.ConfigHasVariable) error } @@ -65,6 +77,8 @@ type Service struct { subscriptionService SubscriptionService emitter Emitter variableService VariableService + variableRepo VariableRepo + configWriteDeny bool logger log.Logger } @@ -76,6 +90,8 @@ func NewService( subscriptionService SubscriptionService, emitter Emitter, variableService VariableService, + variableRepo VariableRepo, + ConfigWriteDeny bool, logger log.Logger, ) Service { return Service{ @@ -86,6 +102,8 @@ func NewService( subscriptionService: subscriptionService, emitter: emitter, variableService: variableService, + variableRepo: variableRepo, + configWriteDeny: ConfigWriteDeny, logger: logger, } } @@ -212,7 +230,26 @@ func (s Service) OnModuleConfigSchema( if err != nil { return errors.WithMessage(err, "get active config") } + + configSchema := entity.ConfigSchema{ + Id: uuid.NewString(), + ModuleId: moduleId, + Data: data.Schema, + ModuleVersion: data.Version, + } + err = s.configSchemaRepo.Upsert(ctx, configSchema) + if err != nil { + return errors.WithMessage(err, "upsert config schema in store") + } + 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) + if err != nil { + return errors.WithMessage(err, "filter secret params in store") + } + initialConfig := entity.Config{ Id: idByKey(moduleId), Name: helpers.ModuleName(conn), @@ -242,7 +279,7 @@ func (s Service) OnModuleConfigSchema( config = &initialConfig } - configData, err := s.variableService.RenderConfig(ctx, config.Data) + configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data) if err != nil { return errors.WithMessage(err, "render config") } @@ -250,17 +287,6 @@ func (s Service) OnModuleConfigSchema( s.subscriptionService.SubscribeToConfigChanges(conn, moduleId) - configSchema := entity.ConfigSchema{ - Id: uuid.NewString(), - ModuleId: moduleId, - Data: data.Schema, - ModuleVersion: data.Version, - } - err = s.configSchemaRepo.Upsert(ctx, configSchema) - if err != nil { - return errors.WithMessage(err, "upsert config schema in store") - } - return nil } @@ -268,3 +294,138 @@ func idByKey(key string) string { hash := sha256.Sum256([]byte(key)) 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 + } + + // Remember paths tagged `x-ui-exposed` and `x-sensitive` + uiPaths, err := schema.UIExposedPaths(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") + } + 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 := make(map[string][]string) + 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{}{} + } + } + + 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 + 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 := "variable" + if len(secrets) > 1 { + plural = "variables" + } + errorDetails[policyFieldPath(path)] = fmt.Sprintf("UI экспортируемое поле не должно ссылаться на переменную с типом SECRET %s %s", plural, strings.Join(secrets, ", ")) + } + + 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 + } + if rc.IsCompositeJSONString(value) { + continue + } + if name, ok := rc.SingleVariableRef(value); ok { + if t, known := variableTypes[name]; known && t != entity.SecretType { + errorDetails[policyFieldPath(path)] = fmt.Sprintf("sensitive поле должно ссылаться на переменную с типом SECRET в %s", name) + } + continue + } + errorDetails[policyFieldPath(path)] = "plain value in sensitive field" + } + } + + if len(errorDetails) == 0 { + return nil + } + + return errors.WithMessage(domain.NewConfigValidationError(errorDetails), "config violates the secret policy") +} + +// 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 + }) + return values, err +} + +func policyFieldPath(canonical string) string { + path := strings.TrimPrefix(canonical, "$.") + return strings.ReplaceAll(path, "[]", ".0") +} diff --git a/service/module/service_test.go b/service/module/service_test.go new file mode 100644 index 0000000..433fbad --- /dev/null +++ b/service/module/service_test.go @@ -0,0 +1,221 @@ +package module + +import ( + "context" + "encoding/json" + "errors" + "reflect" + "testing" + + "isp-config-service/domain" + "isp-config-service/entity" + + kitjson "github.com/txix-open/isp-kit/json" +) + +type fakeSchemaRepo struct { + schema *entity.ConfigSchema +} + +func (r fakeSchemaRepo) Upsert(ctx context.Context, schema entity.ConfigSchema) error { + return nil +} + +func (r fakeSchemaRepo) GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) { + return r.schema, nil +} + +type fakeVariableRepo struct { + variables []entity.Variable +} + +func (r fakeVariableRepo) GetVariablesByName(ctx context.Context, names map[string]struct{}) ([]entity.Variable, error) { + out := make([]entity.Variable, 0, len(names)) + for _, variable := range r.variables { + if _, ok := names[variable.Name]; ok { + out = append(out, variable) + } + } + return out, nil +} + +func 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 +} + +func TestFilterSecretParams(t *testing.T) { + const moduleId = "m1" + varRepo := fakeVariableRepo{variables: []entity.Variable{ + {Name: "sec_var", Type: entity.SecretType}, + {Name: "txt_var", Type: entity.TextType}, + }} + + tests := []struct { + name string + config string + wantErr bool + wantDetails map[string]string + }{ + { + name: "ui-exposed secret reference", + config: `{"secrets": "_Var(sec_var)"}`, + wantErr: true, + wantDetails: map[string]string{ + "secrets": "references SECRET variable sec_var", + }, + }, + { + name: "sensitive literal without any references", + config: `{"token": "plain-pass"}`, + wantErr: true, + wantDetails: map[string]string{"token": "plain value in sensitive field"}, + }, + { + name: "sensitive non-secret reference", + config: `{"token": "_Var(txt_var)"}`, + wantErr: true, + wantDetails: map[string]string{ + "token": "references non-SECRET variable txt_var", + }, + }, + { + 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{"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{ + "secrets": "references SECRET variable sec_var", + "token": "plain value in sensitive field", + }, + }, + { + name: "compliant config", + config: `{"secrets": "_Var(txt_var)", "token": "_Var(sec_var)"}`, + }, + } + for _, test := range tests { + 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, + } + + 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) { + const moduleId = "m1" + s := Service{ + ConfigWriteDeny: false, + configSchemaRepo: fakeSchemaRepo{ + schema: &entity.ConfigSchema{Id: "s1", ModuleId: moduleId, Data: policyTestSchema(t)}, + }, + variableRepo: fakeVariableRepo{}, + } + + err := s.FilterSecretParams(context.Background(), kitjson.RawMessage(`{"secrets": "_Var(sec_var)", "token": "plain-pass"}`), moduleId) + 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{}, + } + + 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) { + 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 := Service{ + ConfigWriteDeny: true, + configSchemaRepo: fakeSchemaRepo{ + schema: &entity.ConfigSchema{Id: "s1", ModuleId: "m1", Data: schemaData}, + }, + variableRepo: fakeVariableRepo{}, + } + + 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) + } +} diff --git a/service/subscription/service.go b/service/subscription/service.go index 245e745..4b4bbfd 100644 --- a/service/subscription/service.go +++ b/service/subscription/service.go @@ -32,7 +32,7 @@ type ConfigRepo interface { } type VariableService interface { - RenderConfig(ctx context.Context, input []byte) ([]byte, error) + RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) } type Emitter interface { @@ -84,7 +84,7 @@ func (s Service) NotifyConfigChanged(ctx context.Context, moduleId string) error if err != nil { return errors.WithMessage(err, "get active config") } - configData, err := s.variableService.RenderConfig(ctx, config.Data) + configData, err := s.variableService.RenderConfig(ctx, moduleId, config.Data) if err != nil { return errors.WithMessage(err, "render config") } diff --git a/service/variable/render.go b/service/variable/render.go new file mode 100644 index 0000000..0383b8a --- /dev/null +++ b/service/variable/render.go @@ -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 +} diff --git a/service/variable/render_test.go b/service/variable/render_test.go new file mode 100644 index 0000000..dd59c80 --- /dev/null +++ b/service/variable/render_test.go @@ -0,0 +1,341 @@ +package variable + +import ( + "encoding/json" + "strings" + "testing" + + "isp-config-service/entity" +) + +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} +} + +func TestRenderSubstitutesNonUI(t *testing.T) { + out, skipped, undefined, err := 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) { + out, skipped, undefined, err := Render( + []byte(`{"a":"_Var(s1)"}`), + []string{"$.a"}, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, skipped, _, err := Render( + []byte(`{"ui":"_Var(s1)","plain":"_Var(s1)"}`), + []string{"$.ui"}, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, skipped, _, err := Render( + []byte(`{"a":"p/_Var(t1)/_Var(s1)"}`), + []string{"$.a"}, + map[string]entity.Variable{"t1": textVar("t1", "tv"), "s1": secretVar("s1", "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) { + out, skipped, _, err := Render( + []byte(`{"a":"_Var(s1)"}`), + nil, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, skipped, _, err := Render( + []byte(`{"oauth":{"clients":[{"e":"_Var(s1)"},{"e":"x"}]}}`), + []string{"$.oauth.clients[].e"}, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, skipped, undefined, err := 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) { + // 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( + []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) { + out, _, _, err := 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) { + out, skipped, _, err := Render( + []byte(`{"n":"_ToInt(_Var(s1))"}`), + []string{"$.n"}, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, _, _, err := 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) { + _, skipped, _, err := Render( + []byte(`{"a":"_Var(s1)_Var(s1)"}`), + []string{"$.a"}, + map[string]entity.Variable{"s1": secretVar("s1", "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) { + out, skipped, _, err := 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) { + _, _, _, err := Render( + []byte(`{"a":`), + nil, + map[string]entity.Variable{}, + ) + if err == nil { + t.Fatal("Render: want an error for invalid JSON") + } +} + +func TestRenderEscapes(t *testing.T) { + out, _, _, err := 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) { + // 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 := Render( + doc, + []string{"$.secrets", "$.plain"}, + map[string]entity.Variable{"s1": secretVar("s1", "top")}, + ) + if err != nil { + t.Fatalf("Render: %v", err) + } + + var m map[string]any + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal output: %v", err) + } + if got := m["secrets"].(string); !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) { + 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 := Render( + doc, + []string{"$.secrets"}, + map[string]entity.Variable{}, + ) + if err != nil { + t.Fatalf("Render: %v", err) + } + var m map[string]any + if err := json.Unmarshal(out, &m); 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) + } +} diff --git a/service/variable/service.go b/service/variable/service.go index 30dd800..7d76c62 100644 --- a/service/variable/service.go +++ b/service/variable/service.go @@ -2,14 +2,19 @@ package variable import ( "context" - "regexp" "strings" + "sync" "time" - "github.com/txix-open/isp-kit/errors" "isp-config-service/domain" "isp-config-service/entity" "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 { @@ -30,28 +35,83 @@ type EventRepo interface { Insert(ctx context.Context, event entity.Event) error } +type SchemaRepo interface { + GetByModuleId(ctx context.Context, moduleId string) (*entity.ConfigSchema, error) +} + type Service struct { - repo Repo - configRepo ConfigRepo - eventRepo EventRepo - stringToIntRegexp *regexp.Regexp - variableRegexp *regexp.Regexp + repo Repo + configRepo ConfigRepo + eventRepo EventRepo + schemaRepo SchemaRepo + logger log.Logger + secretSkipped *prometheus.CounterVec + uiPathsCache *uiPathsCache } func NewService( repo Repo, configRepo ConfigRepo, eventRepo EventRepo, + schemaRepo SchemaRepo, + logger log.Logger, ) Service { return Service{ - repo: repo, - configRepo: configRepo, - eventRepo: eventRepo, - stringToIntRegexp: regexp.MustCompile(`"_ToInt\((\d+)\)"`), - variableRegexp: regexp.MustCompile(`_Var\((.*?)\)`), + repo: repo, + configRepo: configRepo, + eventRepo: eventRepo, + schemaRepo: schemaRepo, + logger: logger, + secretSkipped: metrics.GetOrRegister(metrics.DefaultRegistry, + prometheus.NewCounterVec(prometheus.CounterOpts{ + Subsystem: "config", + Name: "render_secret_skipped", + 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 +} + +// 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 { @@ -180,7 +240,7 @@ func (s Service) Delete(ctx context.Context, name string) error { } //nolint:funlen -func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) { +func (s Service) RenderConfig(ctx context.Context, moduleId string, input []byte) ([]byte, error) { variables, err := s.repo.All(ctx) if err != nil { return nil, errors.WithMessage(err, "get all variables") @@ -188,33 +248,38 @@ func (s Service) RenderConfig(ctx context.Context, input []byte) ([]byte, error) if len(variables) == 0 { return input, nil } - varsMap := make(map[string]string, len(variables)) + varsMap := make(map[string]entity.Variable, len(variables)) for _, variable := range variables { - varsMap[variable.Name] = variable.Value + varsMap[variable.Name] = variable } - undefinedVariables := make([]string, 0) - withReplacedVars := s.variableRegexp.ReplaceAllStringFunc(string(input), func(group string) string { - varName := s.variableRegexp.FindStringSubmatch(group)[1] - - value, ok := varsMap[varName] - if !ok { - undefinedVariables = append(undefinedVariables, varName) - return varName - } - return value - }) - if len(undefinedVariables) > 0 { - return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefinedVariables, ", ")) + uiPaths, err := s.uiPaths(ctx, moduleId) + if err != nil { + return nil, err } - result := s.stringToIntRegexp.ReplaceAll([]byte(withReplacedVars), []byte("$1")) + out, skipped, undefined, err := Render(input, uiPaths, varsMap) + if err != nil { + return nil, errors.WithMessage(err, "render config") + } + if len(undefined) > 0 { + return nil, errors.Errorf("undefined variables: [%s]", strings.Join(undefined, ", ")) + } - return result, nil + for _, ref := range skipped { + s.logger.Error(ctx, "secret variable not substituted in ui-exposed field", + log.String("moduleId", moduleId), + log.String("path", ref.Path), + log.String("variable", ref.Variable), + ) + s.secretSkipped.WithLabelValues(moduleId, ref.Variable).Inc() + } + + return out, nil } 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)) varNames := make([]string, 0, len(matches)) for _, match := range matches { diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go index b1da1ab..5d25fae 100644 --- a/tests/acceptance_test.go +++ b/tests/acceptance_test.go @@ -216,6 +216,7 @@ func setupTestApp(t *testing.T) (*require.Assertions, log.Logger, db.DB) { dataPath := dataDir(t) boot.App.Config().Set("rqlite.DataPath", dataPath) boot.App.Config().Set("backup.Enable", false) + boot.App.Config().Set("configWriteDeny", true) logger := boot.App.Logger() startup, err := startup.New(boot) diff --git a/tests/autodiscovery_test.go b/tests/autodiscovery_test.go index e2b1668..7ca8776 100644 --- a/tests/autodiscovery_test.go +++ b/tests/autodiscovery_test.go @@ -97,6 +97,7 @@ func setupTestWithAppRun(t *testing.T) (*require.Assertions, log.Logger) { dataPath := dataDir(t) boot.App.Config().Set("rqlite.DataPath", dataPath) boot.App.Config().Set("backup.Enable", false) + boot.App.Config().Set("configWriteDeny", true) logger := boot.App.Logger() startup, err := startup.New(boot) diff --git a/tests/render_secret_test.go b/tests/render_secret_test.go new file mode 100644 index 0000000..1d57666 --- /dev/null +++ b/tests/render_secret_test.go @@ -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 +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.NewRequest(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(), + ) +} diff --git a/tests/secret_policy_test.go b/tests/secret_policy_test.go new file mode 100644 index 0000000..3ab35da --- /dev/null +++ b/tests/secret_policy_test.go @@ -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 +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("references SECRET variable 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( + `{"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("references SECRET variable 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("references SECRET variable 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("references SECRET variable 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("references SECRET variable polText", be.Details["secrets"]) + require.Equal("references SECRET variable 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())) + + // 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("references SECRET variable polText", be.Details["secrets"]) + require.Equal("references SECRET variable 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) +}