package configcmd import ( "encoding/json" "fmt" "io" "reflect" "regexp" "sort" "strings" ) // Value is one leaf of a merged configuration, as "config show" reports // it. type Value struct { Key string `json:"key"` Value any `json:"value"` Source string `json:"source"` // Used reports whether the program reads this option; an option in a // shared file that only other programs read has Used false. Used bool `json:"used"` } // DefaultOrigin is the origin of a leaf no layer set (a value a loader // filled in). const DefaultOrigin = "default" // Values returns every leaf of e, sorted by key, with its origin. // used reports whether the program reads a key (nil: every key); a // default it does not read is left out. Secret values (keys secrets, // secret, token, password, and e.SecretKeys) are replaced by "" unless // showSecrets; a reference that only says where a secret is (env:, // file:, secret://) is shown. A leaf that is a list is printed as one // value, so the same rule is applied inside it: a field of a list entry // is secret by its name or by its key without the index ("admins.password" // for the field password of every entry of the list admins). func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value { var out []Value walkLeaves("", e.Merged, func(key string, v any) { source := e.Origins[key] if source == "" { source = DefaultOrigin } u := used == nil || used(key) if !u && source == DefaultOrigin { return } if !showSecrets { if e.isSecret(key) { v = redact(v) } else { v = e.redactWithin(key, v) } } out = append(out, Value{Key: key, Value: v, Source: source, Used: u}) }) return out } // Show writes the merged configuration: indented YAML with every // value's origin as a comment, or with asJSON a JSON array of Values. func (e *Effective) Show(w io.Writer, used func(string) bool, asJSON, showSecrets bool) error { values := e.Values(used, showSecrets) if asJSON { enc := json.NewEncoder(w) enc.SetEscapeHTML(false) enc.SetIndent("", " ") return enc.Encode(values) } fmt.Fprintf(w, "# %s: effective configuration\n# layers, lowest priority first: %s\n", e.Name, e.Describe()) var printed []string // the parent path last printed, by depth for _, v := range values { parts := strings.Split(v.Key, ".") for depth, name := range parts[:len(parts)-1] { if depth < len(printed) && printed[depth] == name { continue } printed = append(printed[:depth], name) fmt.Fprintf(w, "%s%s:\n", strings.Repeat(" ", depth), name) } printed = printed[:len(parts)-1] line := fmt.Sprintf("%s%s: %s", strings.Repeat(" ", len(parts)-1), parts[len(parts)-1], renderValue(v.Value)) note := v.Source if !v.Used { note += ", not used by " + e.Name } fmt.Fprintf(w, "%s%s# %s\n", line, strings.Repeat(" ", max(44-len(line), 1)), note) } return nil } func walkLeaves(prefix string, m map[string]any, fn func(string, any)) { keys := make([]string, 0, len(m)) for k := range m { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { key := k if prefix != "" { key = prefix + "." + k } if sub, ok := m[k].(map[string]any); ok && len(sub) > 0 { walkLeaves(key, sub, fn) continue } fn(key, m[k]) } } // renderValue formats a leaf as a single-line YAML value (JSON is a subset // of YAML's flow style). func renderValue(v any) string { var b strings.Builder enc := json.NewEncoder(&b) enc.SetEscapeHTML(false) if err := enc.Encode(v); err != nil { return fmt.Sprint(v) } return strings.TrimSuffix(b.String(), "\n") } var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true, "password": true} func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] } // isSecret: a default secret name, or one of e.SecretKeys or a key below // one. func (e *Effective) isSecret(key string) bool { if isSecretKey(key) { return true } for _, k := range e.SecretKeys { if key == k || strings.HasPrefix(key, k+".") { return true } } return false } // redactWithin redacts the secret fields of the maps inside a list (or // a map) leaf at key, by the same rule as isSecret. A list entry adds no // segment to the key. v is copied, never changed. func (e *Effective) redactWithin(key string, v any) any { switch x := v.(type) { case []any: out := make([]any, len(x)) for i, el := range x { out[i] = e.redactWithin(key, el) } return out case map[string]any: out := make(map[string]any, len(x)) for k, el := range x { if sub := key + "." + k; e.isSecret(sub) { out[k] = redact(el) } else { out[k] = e.redactWithin(sub, el) } } return out } return v } // redact replaces secret values, keeping references that only say where // the secret is. func redact(v any) any { switch x := v.(type) { case string: for _, ref := range []string{"env:", "file:", "secret://"} { if strings.HasPrefix(x, ref) { return x } } return "" case []any: out := make([]any, len(x)) for i, e := range x { out[i] = redact(e) } return out } return "" } // listIndex matches the "[n]" (or "[]") of a list entry in a dotted key. var listIndex = regexp.MustCompile(`\[\d*\]`) // KnownKey reports whether the dotted option key ("storage.inbound.root", // "listen[0].address") exists in schema (a configuration struct) by its // yaml tags. A map accepts any key; a list, an interface or a type that // decodes itself accepts everything below it; an embedded ",inline" // struct contributes its fields. func KnownKey(schema any, key string) bool { if schema == nil { return false } return knownPath(reflect.TypeOf(schema), strings.Split(listIndex.ReplaceAllString(key, ""), ".")) } func knownPath(t reflect.Type, path []string) bool { t = deref(t) if len(path) == 0 { return true } if t.Implements(unmarshalerType) || reflect.PointerTo(t).Implements(unmarshalerType) { return true } switch t.Kind() { case reflect.Struct: ft, ok := fieldType(t, path[0]) return ok && knownPath(ft, path[1:]) case reflect.Map: return knownPath(t.Elem(), path[1:]) case reflect.Interface, reflect.Slice, reflect.Array: return true } return false }