MSP-8299 - add new command - config audit

This commit is contained in:
ziminis committed 2026-11-27 17:07:39 +07:00
1 parent 7670e2bfe8
commit af75a06f9e
8 files changed
+586 -6

No files matched your search

+50
View File
@@ -15,6 +15,7 @@
- [ispctl schema](#ispctl-schema)
- [ispctl merge](#ispctl-merge)
- [ispctl gitget](#ispctl-gitget)
- [ispctl config audit](#ispctl-config-audit)
- [ispctl vars](#ispctl-vars)
- [ispctl vars get](#ispctl-vars-get)
- [ispctl vars list](#ispctl-vars-list)
@@ -37,6 +38,7 @@ ispctl [flag...] get module_name property_path [local_flag]
ispctl [flag...] set module_name property_path [new_object]
ispctl [flag...] delete module_name property_path
ispctl [flag...] schema module_name [local_flag]
ispctl [flag...] config audit [local_flag]
ispctl [flag...] vars get variable_name
ispctl [flag...] vars list
ispctl [flag...] vars set [local_flag] variable_name variable_value
@@ -55,6 +57,7 @@ ispctl [flag...] vars upload csv_filepath
| `merge` | поблочно производит слияние конфигурации модуля с json конфигом через stdin |
| `gitget` | скачивает из репозитория указанный файлы с указанного комита |
| `schema` | возвращает схему конфигурации указанного модуля |
| `config audit` | находит в активных конфигурациях SECRET-переменные, referenced в UI-экспонируемых полях (теги `x-ui-exposed` в схеме); код выхода `1`, если нарушения найдены |
| `vars get` | выводит информацию о переменной в json формате |
| `vars list` | выводит список переменных в виде ASCII-таблицы |
| `vars set` | изменяет значение переменной |
@@ -81,6 +84,7 @@ ispctl [flag...] vars upload csv_filepath
| Локальные флаги | Параметры | Команды | Описание |
| --------------- | --------- | -------- |------------------------------------------------------------------------------------------------------------------------------- |
| `-o` | string | schema | определяет формат вывода схемы в stdout; по умолчанию `json`; возможные значения `json`, `html` |
| `-o` | string | config audit | определяет формат вывода аудита в stdout; возможные значения `json` |
| `-full` | bool | get | осуществляет взаимодействие с объектами конфигурации модуля с учетом объектом общих конфигураций, которые имеют связь с модулем |
| `-secret` | bool | vars set | устанавливает тип переменной в SECRET |
| | | | |
@@ -389,6 +393,52 @@ ispctl merge example < example.json
ispctl gitget git@github.com:integration-system/ispctl.git main.go d4d7c679aad47ae204c2b3a4587b032a723fe315
```
### ispctl config audit
`ispctl [flag...] config audit [local_flag]`
Проверяет активные конфигурации всех модулей: находит UI-экспонируемые поля (тег `x-ui-exposed` в схеме модуля), в которых активная конфигурация ссылается на SECRET-переменные. Такие значения уже рендерились в браузеры модулей, поэтому найденные переменные нужно ротировать.
`[local_flag]` - локальный флаг `-o` определяет формат вывода. Доступные значения: `json`.
По умолчанию вывод осуществляется в виде таблицы.
Если нарушения найдены, код выхода `1`, иначе `0`.
Запрос
```bash
ispctl config audit
```
Ответ
```bash
MODULE | PATH | VARIABLES
isp-admin-service | $.oauth.clients[].clientSecret | oauth_secret
isp-admin-service | $.secrets | legacy_token
found 2 violation(s); affected values were already rendered into module browsers, rotate the variables
```
Запрос
```bash
ispctl config audit -o json
```
Ответ
```json
[
{
"Module": "isp-admin-service",
"Path": "$.oauth.clients[].clientSecret",
"Variables": [
"oauth_secret"
]
},
{
"Module": "isp-admin-service",
"Path": "$.secrets",
"Variables": [
"legacy_token"
]
}
]
```
### ispctl vars
#### ispctl vars get
+81
View File
@@ -0,0 +1,81 @@
package command
import (
"fmt"
"os"
"strings"
"ispctl/command/utils"
"ispctl/model"
"github.com/olekukonko/tablewriter"
"github.com/urfave/cli/v2"
)
const (
tableHeaderAuditModule = "MODULE"
tableHeaderAuditPath = "PATH"
tableHeaderAuditVariables = "VARIABLES"
tableHeaderAuditReason = "REASON"
auditExitCode = 1
)
var outPrintAuditUsage = fmt.Sprintf("out print for audit; %s", OutPrintJsonValue)
type AuditService interface {
Audit() ([]model.AuditViolation, error)
}
type Audit struct {
service AuditService
}
func NewAudit(service AuditService) Audit {
return Audit{service: service}
}
func (c Audit) Command() *cli.Command {
return &cli.Command{
Name: "config",
Usage: "config commands",
Subcommands: []*cli.Command{
{
Name: "audit",
Usage: "report secret policy violations in active configs: SECRET references in ui-exposed fields and plain or non-SECRET values in sensitive fields",
Flags: []cli.Flag{
&cli.StringFlag{Name: OutPrintFlagName, Usage: outPrintAuditUsage},
},
Action: c.audit,
},
},
}
}
func (c Audit) audit(ctx *cli.Context) error {
violations, err := c.service.Audit()
if err != nil {
return err
}
switch ctx.String(OutPrintFlagName) {
case OutPrintJsonValue:
err = utils.PrintAnswer(violations)
default:
table := tablewriter.NewWriter(os.Stdout)
table.SetBorders(tablewriter.Border{Left: false, Top: false, Right: false, Bottom: false})
table.SetHeader([]string{tableHeaderAuditModule, tableHeaderAuditPath, tableHeaderAuditVariables, tableHeaderAuditReason})
for _, violation := range violations {
table.Append([]string{violation.Module, violation.Path, strings.Join(violation.Variables, ", "), violation.Reason})
}
table.Render()
fmt.Printf("found %d violation(s); rotate the affected SECRET variables and move sensitive values to SECRET variable references\n", len(violations))
}
if err != nil {
return err
}
if len(violations) > 0 {
return cli.Exit("secret policy violations found in active configs", auditExitCode)
}
return nil
}
+3
View File
@@ -13,6 +13,7 @@ type AutoComplete interface {
}
type ConfigService interface {
Audit() ([]model.AuditViolation, error)
CreateUpdateConfig(stringToChange string, configuration *model.Config) (map[string]any, error)
CreateUpdateConfigV2(configuration *model.Config) (map[string]any, error)
DeleteVariable(variableName string) error
@@ -37,6 +38,7 @@ func AllCommands(configService ConfigService, autoComplete AutoComplete) []*cli.
merge := NewMerge(configService, autoComplete)
gitGet := NewGitGet()
variables := NewVariables(configService, autoComplete)
audit := NewAudit(configService)
return []*cli.Command{
status.Command(),
get.Command(),
@@ -46,6 +48,7 @@ func AllCommands(configService ConfigService, autoComplete AutoComplete) []*cli.
merge.Command(),
gitGet.Command(),
variables.Command(),
audit.Command(),
}
}
+21
View File
@@ -0,0 +1,21 @@
package model
import "encoding/json"
// AuditModule is a module with its raw config schema; the raw form keeps the
// x-ui-exposed keyword that a typed unmarshal may drop.
type AuditModule struct {
Id string
Name string
ConfigSchema json.RawMessage
}
// AuditViolation names a config field that violates the secret policy in the
// module's active config: a UI-exposed field referencing a SECRET variable,
// or a sensitive field holding a plain value or a non-SECRET reference.
type AuditViolation struct {
Module string
Path string
Variables []string
Reason string
}
+2
View File
@@ -11,6 +11,8 @@ const (
SecretVariableType = "SECRET"
TextVariableType = "TEXT"
ErrCodeModuleNotFound = 2001
ErrCodeConfigNotFound = 2002
ErrCodeVariableNotFound = 2006
)
+18 -6
View File
@@ -50,6 +50,17 @@ func (c Config) GetAvailableConfigs() ([]model.ModuleInfo, error) {
return response, nil
}
func (c Config) GetAuditModules() ([]model.AuditModule, error) {
response := make([]model.AuditModule, 0)
err := c.cli.Invoke(getAvailableConfigs).
JsonResponseBody(&response).
Do(c.baseCtx)
if err != nil {
return nil, errors.WithMessagef(err, "call %s", getAvailableConfigs)
}
return response, nil
}
func (c Config) GetConfigByModuleName(name string) (*model.Config, error) {
request := &model.GetModuleByUuidAndNameRequest{ModuleName: name}
response := new(model.Config)
@@ -57,14 +68,15 @@ func (c Config) GetConfigByModuleName(name string) (*model.Config, error) {
JsonRequestBody(request).
JsonResponseBody(&response).
Do(c.baseCtx)
switch {
case status.Code(err) == codes.NotFound:
return nil, model.ErrModuleNotFound
case err != nil:
return nil, errors.WithMessagef(err, "call %s", getConfigByModuleName)
default:
if err == nil {
return response, nil
}
if apiError := apierrors.FromError(err); apiError != nil {
if apiError.ErrorCode == model.ErrCodeModuleNotFound || apiError.ErrorCode == model.ErrCodeConfigNotFound {
return nil, model.ErrModuleNotFound
}
}
return nil, errors.WithMessagef(err, "call %s", getConfigByModuleName)
}
func (c Config) CreateUpdateConfig(request model.Config) (*model.Config, error) {
+167
View File
@@ -0,0 +1,167 @@
package service
import (
"encoding/json"
"fmt"
"sort"
"ispctl/model"
"github.com/pkg/errors"
"github.com/txix-open/isp-kit/rc"
"github.com/txix-open/isp-kit/rc/schema"
)
// Audit reports the active configs that reference SECRET variables on
// UI-exposed fields. Those values were already rendered into module browsers,
// so the variables must be rotated.
func (c Config) Audit() ([]model.AuditViolation, error) {
modules, err := c.configRepo.GetAuditModules()
if err != nil {
return nil, err
}
variables, err := c.configRepo.GetAllVariables()
if err != nil {
return nil, err
}
secrets := make(map[string]struct{}, len(variables))
for _, variable := range variables {
if variable.Type == model.SecretVariableType {
secrets[variable.Name] = struct{}{}
}
}
violations := make([]model.AuditViolation, 0)
for _, module := range modules {
configuration, err := c.configRepo.GetConfigByModuleName(module.Name)
if err != nil {
if errors.Is(err, model.ErrModuleNotFound) {
continue // no active config — nothing to audit
}
return nil, err
}
moduleViolations, err := auditModule(module.Name, module.ConfigSchema, configuration.Data, secrets)
if err != nil {
return nil, errors.WithMessagef(err, "module [%s]", module.Name)
}
violations = append(violations, moduleViolations...)
}
sort.Slice(violations, func(i, j int) bool {
if violations[i].Module != violations[j].Module {
return violations[i].Module < violations[j].Module
}
return violations[i].Path < violations[j].Path
})
return violations, nil
}
// auditModule returns the violations of a single module: UI-exposed paths whose
// config references SECRET variables, and sensitive paths whose config value
// is not a single reference to a SECRET variable. The schema and the config
// are read with the shared isp-kit readers, in the same currency as the
// config-service secret policy. The reference report covers every string
// leaf, including composite JSON strings (report-only in stage 1).
func auditModule(moduleName string, schemaData json.RawMessage, configData map[string]any, secrets map[string]struct{}) ([]model.AuditViolation, error) {
var uiPaths, sensitivePaths []string
if len(schemaData) > 0 {
var err error
uiPaths, err = schema.UIExposedPaths(schemaData)
if err != nil {
return nil, err
}
sensitivePaths, err = schema.SensitivePaths(schemaData)
if err != nil {
return nil, err
}
}
uiSet := make(map[string]struct{}, len(uiPaths))
for _, path := range uiPaths {
uiSet[path] = struct{}{}
}
configBytes, err := json.Marshal(configData)
if err != nil {
return nil, errors.WithMessage(err, "marshal config data")
}
refs, err := rc.VariableRefReport(configBytes)
if err != nil {
return nil, err
}
violations := make([]model.AuditViolation, 0)
for path, names := range refs {
if _, isUI := uiSet[path]; !isUI {
continue
}
secretNames := make([]string, 0, len(names))
for _, name := range names {
if _, isSecret := secrets[name]; isSecret {
secretNames = append(secretNames, name)
}
}
if len(secretNames) == 0 {
continue
}
sort.Strings(secretNames)
violations = append(violations, model.AuditViolation{
Module: moduleName,
Path: path,
Variables: secretNames,
Reason: "secret variable in ui-exposed field",
})
}
if len(sensitivePaths) > 0 {
sensitiveSet := make(map[string]struct{}, len(sensitivePaths))
for _, path := range sensitivePaths {
sensitiveSet[path] = struct{}{}
}
values, err := leafValues(configBytes, sensitiveSet)
if err != nil {
return nil, err
}
for _, path := range sensitivePaths {
value, exists := values[path]
if !exists || value == "" {
continue // absent or empty field
}
if name, isRef := rc.SingleVariableRef(value); isRef {
if _, isSecret := secrets[name]; isSecret {
continue // a reference to a SECRET variable is compliant
}
violations = append(violations, model.AuditViolation{
Module: moduleName,
Path: path,
Variables: []string{name},
Reason: fmt.Sprintf("references non-SECRET variable %s", name),
})
continue
}
// A plain value, including composite JSON strings, is reported
// (report-only in stage 1, the write policy does not apply to
// composite strings).
violations = append(violations, model.AuditViolation{
Module: moduleName,
Path: path,
Variables: []string{},
Reason: "plain value in sensitive field",
})
}
}
return violations, nil
}
// leafValues collects the raw values of the config's string leaves located at
// the given canonical paths.
func leafValues(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
}
+244
View File
@@ -0,0 +1,244 @@
package service
import (
"encoding/json"
"reflect"
"testing"
"ispctl/model"
)
func TestAuditModuleIntersection(t *testing.T) {
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"ui": map[string]any{"type": "string", "x-ui-exposed": true},
"plain": map[string]any{"type": "string"},
},
})
if err != nil {
t.Fatal(err)
}
configData := map[string]any{
"ui": "_Var(s1) _Var(t1)",
"plain": "_Var(s1)",
}
secrets := map[string]struct{}{"s1": {}}
violations, err := auditModule("m1", schema, configData, secrets)
if err != nil {
t.Fatalf("auditModule: %v", err)
}
// Only the UI leaf with the secret reference is reported; the same
// reference in the plain leaf and the TEXT reference in the UI leaf are
// not.
want := []model.AuditViolation{{
Module: "m1",
Path: "$.ui",
Variables: []string{"s1"},
Reason: "secret variable in ui-exposed field",
}}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}
func TestAuditModuleSecretOutsideUI(t *testing.T) {
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"plain": map[string]any{"type": "string"},
},
})
if err != nil {
t.Fatal(err)
}
violations, err := auditModule(
"m1",
schema,
map[string]any{"plain": "_Var(s1)"},
map[string]struct{}{"s1": {}},
)
if err != nil {
t.Fatalf("auditModule: %v", err)
}
if len(violations) != 0 {
t.Fatalf("violations = %v, want none: a secret outside ui-exposed fields is not a violation", violations)
}
}
func TestAuditModuleArrayPath(t *testing.T) {
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"clients": map[string]any{
"type": "array",
"items": map[string]any{"type": "string", "x-ui-exposed": true},
},
},
})
if err != nil {
t.Fatal(err)
}
configData := map[string]any{
"clients": []any{"_Var(s1)", "nope"},
}
violations, err := auditModule("m1", schema, configData, map[string]struct{}{"s1": {}})
if err != nil {
t.Fatalf("auditModule: %v", err)
}
want := []model.AuditViolation{{Module: "m1", Path: "$.clients[]", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"}}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}
func TestAuditModuleCompositeReported(t *testing.T) {
// the report covers references hidden inside composite JSON strings
// (report-only in stage 1, the policy itself does not apply to them)
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"secrets": map[string]any{"type": "string", "x-ui-exposed": true},
},
})
if err != nil {
t.Fatal(err)
}
composite, err := json.Marshal(map[string]any{"a": "_Var(s1)"})
if err != nil {
t.Fatal(err)
}
configData := map[string]any{
"secrets": string(composite),
}
violations, err := auditModule("m1", schema, configData, map[string]struct{}{"s1": {}})
if err != nil {
t.Fatalf("auditModule: %v", err)
}
want := []model.AuditViolation{{Module: "m1", Path: "$.secrets", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"}}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}
func TestAuditModuleEmptySchema(t *testing.T) {
violations, err := auditModule("m1", nil, map[string]any{"a": "_Var(s1)"}, map[string]struct{}{"s1": {}})
if err != nil {
t.Fatalf("auditModule: %v", err)
}
if len(violations) != 0 {
t.Fatalf("violations = %v, want none: an empty schema exposes no fields", violations)
}
}
func sensitiveTestSchema(t *testing.T) json.RawMessage {
t.Helper()
schema, err := json.Marshal(map[string]any{
"type": "object",
"properties": map[string]any{
"token": map[string]any{"type": "string", "x-sensitive": true},
},
})
if err != nil {
t.Fatal(err)
}
return schema
}
func TestAuditModuleSensitiveLiteral(t *testing.T) {
violations, err := auditModule(
"m1",
sensitiveTestSchema(t),
map[string]any{"token": "legacy-pass-123"},
map[string]struct{}{"s1": {}},
)
if err != nil {
t.Fatalf("auditModule: %v", err)
}
want := []model.AuditViolation{{
Module: "m1",
Path: "$.token",
Variables: []string{},
Reason: "plain value in sensitive field",
}}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}
func TestAuditModuleSensitiveNonSecretRef(t *testing.T) {
violations, err := auditModule(
"m1",
sensitiveTestSchema(t),
map[string]any{"token": "_Var(t1)"},
map[string]struct{}{"s1": {}},
)
if err != nil {
t.Fatalf("auditModule: %v", err)
}
want := []model.AuditViolation{{
Module: "m1",
Path: "$.token",
Variables: []string{"t1"},
Reason: "references non-SECRET variable t1",
}}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}
func TestAuditModuleSensitiveCompliant(t *testing.T) {
for name, config := range map[string]string{
"secret reference": `{"token": "_Var(s1)"}`,
"empty value": `{"token": ""}`,
"absent field": `{}`,
} {
t.Run(name, func(t *testing.T) {
var configData map[string]any
if err := json.Unmarshal([]byte(config), &configData); err != nil {
t.Fatal(err)
}
violations, err := auditModule("m1", sensitiveTestSchema(t), configData, map[string]struct{}{"s1": {}})
if err != nil {
t.Fatalf("auditModule: %v", err)
}
if len(violations) != 0 {
t.Fatalf("violations = %v, want none", violations)
}
})
}
}
func TestAuditModuleBothClasses(t *testing.T) {
schema, 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},
},
})
if err != nil {
t.Fatal(err)
}
violations, err := auditModule(
"m1",
schema,
map[string]any{"secrets": "_Var(s1)", "token": "plain-pass"},
map[string]struct{}{"s1": {}},
)
if err != nil {
t.Fatalf("auditModule: %v", err)
}
want := []model.AuditViolation{
{Module: "m1", Path: "$.secrets", Variables: []string{"s1"}, Reason: "secret variable in ui-exposed field"},
{Module: "m1", Path: "$.token", Variables: []string{}, Reason: "plain value in sensitive field"},
}
if !reflect.DeepEqual(violations, want) {
t.Fatalf("violations = %v, want %v", violations, want)
}
}