MSP-8299 add new handling for SECRET type variables and sensitive fields in config

This commit is contained in:
ziminis committed 2026-11-27 18:31:34 +07:00
1 parent f7a141d25e
commit cdf700b062
16 files changed
+1449 -67

No files matched your search

+74
View File
@@ -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
}
+341
View File
@@ -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)
}
}
+96 -31
View File
@@ -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 {