mirror of
https://github.com/gtsteffaniak/filebrowser.git
synced 2026-11-26 08:29:41 -05:00
1597 lines
48 KiB
Go
1597 lines
48 KiB
Go
// WARNING: the vast majority of generator.go is ai generated
|
|
// troubleshooting is best done with ai agent assistance
|
|
package settings
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"go/ast"
|
|
"go/parser"
|
|
"go/token"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
|
|
"golang.org/x/tools/go/packages"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// CommentsMap[typeName][fieldName] = combined doc+inline comment text
|
|
type CommentsMap map[string]map[string]string
|
|
|
|
// SecretFieldsMap[typeName][fieldName] = true if field should be redacted
|
|
type SecretFieldsMap map[string]map[string]bool
|
|
|
|
// DeprecatedFieldsMap[typeName][fieldName] = true if field is deprecated
|
|
type DeprecatedFieldsMap map[string]map[string]bool
|
|
|
|
var (
|
|
collectCommentsCacheMu sync.RWMutex
|
|
collectCommentsCache = map[string]collectCommentsCacheEntry{}
|
|
)
|
|
|
|
type collectCommentsCacheEntry struct {
|
|
comments CommentsMap
|
|
secrets SecretFieldsMap
|
|
deprecated DeprecatedFieldsMap
|
|
}
|
|
|
|
func cloneCommentsMap(src CommentsMap) CommentsMap {
|
|
if src == nil {
|
|
return nil
|
|
}
|
|
out := make(CommentsMap, len(src))
|
|
for typeName, fieldMap := range src {
|
|
out[typeName] = make(map[string]string, len(fieldMap))
|
|
for fieldName, comment := range fieldMap {
|
|
out[typeName][fieldName] = comment
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func cloneBoolFieldMap(src map[string]map[string]bool) map[string]map[string]bool {
|
|
if src == nil {
|
|
return nil
|
|
}
|
|
out := make(map[string]map[string]bool, len(src))
|
|
for typeName, fieldMap := range src {
|
|
out[typeName] = make(map[string]bool, len(fieldMap))
|
|
for fieldName, v := range fieldMap {
|
|
out[typeName][fieldName] = v
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// getStringStyle determines whether a string should be quoted in YAML
|
|
func getStringStyle(value string) yaml.Style {
|
|
// Always quote all strings for consistency
|
|
return yaml.DoubleQuotedStyle
|
|
}
|
|
|
|
// CollectComments parses all Go source in the directory of srcPath and returns CommentsMap.
|
|
func CollectComments(srcPath string) (CommentsMap, error) {
|
|
comments, _, _, err := CollectCommentsAndSecrets(srcPath)
|
|
return comments, err
|
|
}
|
|
|
|
// CollectCommentsAndSecrets parses all Go source and returns comments, secrets, and deprecated field mappings
|
|
func CollectCommentsAndSecrets(srcPath string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) {
|
|
dir := srcPath
|
|
if fi, err := os.Stat(srcPath); err == nil && !fi.IsDir() {
|
|
dir = filepath.Dir(srcPath)
|
|
}
|
|
settingsDir, err := filepath.Abs(dir)
|
|
if err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
|
|
collectCommentsCacheMu.RLock()
|
|
if cached, ok := collectCommentsCache[settingsDir]; ok && shouldCacheCollectComments(settingsDir) {
|
|
collectCommentsCacheMu.RUnlock()
|
|
return cloneCommentsMap(cached.comments), cloneBoolFieldMap(cached.secrets), cloneBoolFieldMap(cached.deprecated), nil
|
|
}
|
|
collectCommentsCacheMu.RUnlock()
|
|
|
|
// settings lives at backend/pkg/settings; users at backend/internal/database/users
|
|
dirsToparse := []string{
|
|
settingsDir,
|
|
filepath.Join(settingsDir, "..", "..", "internal", "database", "users"),
|
|
}
|
|
|
|
comments := make(CommentsMap)
|
|
secrets := make(SecretFieldsMap)
|
|
deprecated := make(DeprecatedFieldsMap)
|
|
|
|
for _, parseDir := range dirsToparse {
|
|
if _, err := os.Stat(parseDir); err != nil {
|
|
continue
|
|
}
|
|
dirComments, dirSecrets, dirDeprecated, err := parseDirectoryComments(parseDir)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
|
|
// Merge results
|
|
for typeName, fieldMap := range dirComments {
|
|
if comments[typeName] == nil {
|
|
comments[typeName] = make(map[string]string)
|
|
}
|
|
for fieldName, comment := range fieldMap {
|
|
comments[typeName][fieldName] = comment
|
|
}
|
|
}
|
|
|
|
for typeName, fieldMap := range dirSecrets {
|
|
if secrets[typeName] == nil {
|
|
secrets[typeName] = make(map[string]bool)
|
|
}
|
|
for fieldName, isSecret := range fieldMap {
|
|
secrets[typeName][fieldName] = isSecret
|
|
}
|
|
}
|
|
|
|
for typeName, fieldMap := range dirDeprecated {
|
|
if deprecated[typeName] == nil {
|
|
deprecated[typeName] = make(map[string]bool)
|
|
}
|
|
for fieldName, isDeprecated := range fieldMap {
|
|
deprecated[typeName][fieldName] = isDeprecated
|
|
}
|
|
}
|
|
}
|
|
|
|
entry := collectCommentsCacheEntry{
|
|
comments: cloneCommentsMap(comments),
|
|
secrets: cloneBoolFieldMap(secrets),
|
|
deprecated: cloneBoolFieldMap(deprecated),
|
|
}
|
|
collectCommentsCacheMu.Lock()
|
|
if shouldCacheCollectComments(settingsDir) {
|
|
collectCommentsCache[settingsDir] = entry
|
|
}
|
|
collectCommentsCacheMu.Unlock()
|
|
|
|
return cloneCommentsMap(comments), cloneBoolFieldMap(secrets), cloneBoolFieldMap(deprecated), nil
|
|
}
|
|
|
|
// shouldCacheCollectComments avoids caching parses of ephemeral test fixture dirs under os.TempDir().
|
|
func shouldCacheCollectComments(settingsDir string) bool {
|
|
if _, err := os.Stat(filepath.Join(settingsDir, "structs.go")); err == nil {
|
|
return true
|
|
}
|
|
return !strings.HasPrefix(settingsDir, os.TempDir())
|
|
}
|
|
|
|
// parseDirectoryComments parses a single directory for comments, secrets, and deprecated fields.
|
|
func parseDirectoryComments(dir string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) {
|
|
absDir, err := filepath.Abs(dir)
|
|
if err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
if _, err = os.Stat(absDir); err != nil {
|
|
return nil, nil, nil, err
|
|
}
|
|
|
|
var files []*ast.File
|
|
cfg := &packages.Config{
|
|
Mode: packages.NeedSyntax | packages.NeedFiles,
|
|
Dir: absDir,
|
|
ParseFile: func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
|
|
return parser.ParseFile(fset, filename, src, parser.ParseComments)
|
|
},
|
|
}
|
|
pkgs, err := packages.Load(cfg, ".")
|
|
if err == nil && len(pkgs) > 0 {
|
|
for _, pkg := range pkgs {
|
|
files = append(files, pkg.Syntax...)
|
|
}
|
|
}
|
|
if len(files) == 0 {
|
|
// Fallback for directories outside a module (e.g. test temp dirs): parse .go files directly
|
|
files, err = parseDirGoFiles(absDir)
|
|
if err != nil || len(files) == 0 {
|
|
return nil, nil, nil, err
|
|
}
|
|
}
|
|
|
|
comments := make(CommentsMap)
|
|
secrets := make(SecretFieldsMap)
|
|
deprecated := make(DeprecatedFieldsMap)
|
|
|
|
for _, file := range files {
|
|
for _, decl := range file.Decls {
|
|
gen, ok := decl.(*ast.GenDecl)
|
|
if !ok || gen.Tok != token.TYPE {
|
|
continue
|
|
}
|
|
for _, spec := range gen.Specs {
|
|
ts, ok := spec.(*ast.TypeSpec)
|
|
if !ok {
|
|
continue
|
|
}
|
|
st, ok := ts.Type.(*ast.StructType)
|
|
if !ok {
|
|
continue
|
|
}
|
|
typeName := ts.Name.Name
|
|
commentMap := make(map[string]string)
|
|
secretMap := make(map[string]bool)
|
|
deprecatedMap := make(map[string]bool)
|
|
comments[typeName] = commentMap
|
|
secrets[typeName] = secretMap
|
|
deprecated[typeName] = deprecatedMap
|
|
|
|
for _, field := range st.Fields.List {
|
|
if len(field.Names) == 0 {
|
|
continue
|
|
}
|
|
name := field.Names[0].Name
|
|
var parts []string
|
|
var fullComment string
|
|
|
|
if field.Doc != nil {
|
|
docText := strings.TrimSpace(field.Doc.Text())
|
|
parts = append(parts, docText)
|
|
fullComment += docText + " "
|
|
}
|
|
if field.Comment != nil {
|
|
commentText := strings.TrimSpace(field.Comment.Text())
|
|
parts = append(parts, commentText)
|
|
fullComment += commentText
|
|
}
|
|
|
|
if len(parts) > 0 {
|
|
commentMap[name] = strings.Join(parts, " : ")
|
|
}
|
|
|
|
// Check if field should be treated as secret
|
|
if strings.Contains(strings.ToLower(fullComment), "secret:") {
|
|
secretMap[name] = true
|
|
}
|
|
|
|
// Check if field should be treated as deprecated
|
|
if strings.Contains(strings.ToLower(fullComment), "deprecated:") {
|
|
deprecatedMap[name] = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return comments, secrets, deprecated, nil
|
|
}
|
|
|
|
// parseDirGoFiles parses all .go files in dir and returns their ASTs. Used when the directory
|
|
// is not inside a Go module (e.g. test temp dirs) so packages.Load would fail.
|
|
func parseDirGoFiles(dir string) ([]*ast.File, error) {
|
|
entries, err := os.ReadDir(dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
fset := token.NewFileSet()
|
|
var files []*ast.File
|
|
for _, e := range entries {
|
|
if e.IsDir() || !strings.HasSuffix(e.Name(), ".go") {
|
|
continue
|
|
}
|
|
path := filepath.Join(dir, e.Name())
|
|
f, err := parser.ParseFile(fset, path, nil, parser.ParseComments)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
files = append(files, f)
|
|
}
|
|
return files, nil
|
|
}
|
|
|
|
// PathToTypeField represents a mapping from YAML path to Go type and field info
|
|
type PathToTypeField struct {
|
|
TypeName string
|
|
FieldName string
|
|
}
|
|
|
|
// buildStructPathMap builds a dynamic mapping from YAML paths to Go struct types/fields using reflection
|
|
func buildStructPathMap(config *Settings) map[string]PathToTypeField {
|
|
pathMap := make(map[string]PathToTypeField)
|
|
|
|
// Start with the root Settings struct
|
|
buildPathMapRecursive(reflect.TypeOf(config).Elem(), reflect.ValueOf(config).Elem(), "", "Settings", pathMap)
|
|
|
|
return pathMap
|
|
}
|
|
|
|
// buildPathMapRecursive recursively builds the path mapping using reflection
|
|
func buildPathMapRecursive(structType reflect.Type, structValue reflect.Value, currentPath string, typeName string, pathMap map[string]PathToTypeField) {
|
|
for i := 0; i < structType.NumField(); i++ {
|
|
field := structType.Field(i)
|
|
|
|
// Skip unexported fields
|
|
if field.PkgPath != "" {
|
|
continue
|
|
}
|
|
|
|
// Skip fields marked to ignore
|
|
if yamlTag := field.Tag.Get("yaml"); yamlTag == "-" {
|
|
continue
|
|
}
|
|
if jsonTag := field.Tag.Get("json"); jsonTag == "-" {
|
|
continue
|
|
}
|
|
|
|
// Determine the YAML field name from struct tags
|
|
yamlFieldName := getYamlFieldName(field)
|
|
|
|
// Build the full path
|
|
var fullPath string
|
|
if currentPath == "" {
|
|
fullPath = yamlFieldName
|
|
} else {
|
|
fullPath = currentPath + "." + yamlFieldName
|
|
}
|
|
|
|
// Add this field to the path map
|
|
pathMap[fullPath] = PathToTypeField{
|
|
TypeName: typeName,
|
|
FieldName: field.Name,
|
|
}
|
|
|
|
// If this field is a struct, recurse into it
|
|
fieldValue := structValue.Field(i)
|
|
fieldType := field.Type
|
|
|
|
// Handle pointers
|
|
if fieldType.Kind() == reflect.Pointer {
|
|
if fieldValue.IsNil() {
|
|
// Skip nil pointers
|
|
continue
|
|
}
|
|
fieldValue = fieldValue.Elem()
|
|
fieldType = fieldType.Elem()
|
|
}
|
|
|
|
// Recurse into structs (but not slices of structs for now - those are handled differently)
|
|
if fieldType.Kind() == reflect.Struct {
|
|
// Skip certain types that shouldn't be recursed into
|
|
if isSkippableStructType(fieldType) {
|
|
continue
|
|
}
|
|
|
|
buildPathMapRecursive(fieldType, fieldValue, fullPath, fieldType.Name(), pathMap)
|
|
} else if fieldType.Kind() == reflect.Slice && fieldType.Elem().Kind() == reflect.Struct {
|
|
// For slices of structs, we map to the element type
|
|
elemType := fieldType.Elem()
|
|
if !isSkippableStructType(elemType) {
|
|
// Create a zero value of the element type to recurse into
|
|
zeroValue := reflect.Zero(elemType)
|
|
buildPathMapRecursive(elemType, zeroValue, fullPath, elemType.Name(), pathMap)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// getYamlFieldName determines the YAML field name from struct tags
|
|
func getYamlFieldName(field reflect.StructField) string {
|
|
// Check yaml tag first
|
|
if yamlTag := field.Tag.Get("yaml"); yamlTag != "" && yamlTag != "-" {
|
|
return strings.Split(yamlTag, ",")[0]
|
|
}
|
|
|
|
// Check json tag second
|
|
if jsonTag := field.Tag.Get("json"); jsonTag != "" && jsonTag != "-" {
|
|
return strings.Split(jsonTag, ",")[0]
|
|
}
|
|
|
|
// Default to field name
|
|
return field.Name
|
|
}
|
|
|
|
// isSkippableStructType checks if a struct type should be skipped during recursion
|
|
func isSkippableStructType(t reflect.Type) bool {
|
|
// Skip types from other packages that we don't want to recurse into
|
|
pkgPath := t.PkgPath()
|
|
|
|
// Skip external packages
|
|
if pkgPath != "" && !strings.Contains(pkgPath, "filebrowser/backend") {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
// CollectCommentsFromEmbeddedYaml parses comments from embedded YAML content and returns CommentsMap, SecretFieldsMap, and DeprecatedFieldsMap
|
|
func CollectCommentsFromEmbeddedYaml(yamlContent string) (CommentsMap, SecretFieldsMap, DeprecatedFieldsMap, error) {
|
|
comments := make(CommentsMap)
|
|
secrets := make(SecretFieldsMap)
|
|
deprecated := make(DeprecatedFieldsMap)
|
|
|
|
// Build the dynamic path mapping from the actual Config struct
|
|
pathMap := buildStructPathMap(&Config)
|
|
|
|
lines := strings.Split(yamlContent, "\n")
|
|
|
|
// Track the current path in the YAML structure and array context
|
|
var currentPath []string
|
|
var arrayDepth = -1 // Track the depth where we encountered an array element
|
|
|
|
for _, line := range lines {
|
|
// Skip empty lines and lines that are just comments
|
|
trimmed := strings.TrimSpace(line)
|
|
if trimmed == "" || strings.HasPrefix(trimmed, "#") {
|
|
continue
|
|
}
|
|
|
|
// Find the key and comment in the line
|
|
if !strings.Contains(line, ":") {
|
|
continue
|
|
}
|
|
|
|
// Split on the first colon to get key part
|
|
colonIndex := strings.Index(line, ":")
|
|
keyPart := line[:colonIndex]
|
|
restPart := line[colonIndex+1:]
|
|
|
|
// Calculate indentation
|
|
indent := 0
|
|
for i, char := range keyPart {
|
|
if char == ' ' {
|
|
indent++
|
|
} else {
|
|
keyPart = keyPart[i:]
|
|
break
|
|
}
|
|
}
|
|
depth := indent / 2
|
|
|
|
// Get the key name
|
|
key := strings.TrimSpace(keyPart)
|
|
if key == "" {
|
|
continue
|
|
}
|
|
|
|
// Handle YAML array elements that start with "- "
|
|
isArrayElement := strings.HasPrefix(key, "- ")
|
|
if isArrayElement {
|
|
key = strings.TrimSpace(key[2:]) // Remove "- " prefix
|
|
arrayDepth = depth // Track that we're in an array element at this depth
|
|
} else {
|
|
// If we're processing a field that's part of an array element,
|
|
// keep it at the array element depth
|
|
if arrayDepth >= 0 && depth > arrayDepth {
|
|
depth = arrayDepth
|
|
} else if arrayDepth >= 0 && depth <= arrayDepth {
|
|
// We've moved out of the array element context
|
|
arrayDepth = -1
|
|
}
|
|
}
|
|
|
|
// Adjust the current path based on depth
|
|
if depth < len(currentPath) {
|
|
currentPath = currentPath[:depth]
|
|
}
|
|
|
|
// Add current key to path
|
|
if depth < len(currentPath) {
|
|
currentPath[depth] = key
|
|
currentPath = currentPath[:depth+1]
|
|
} else {
|
|
currentPath = append(currentPath, key)
|
|
}
|
|
|
|
// Look for comment in the rest of the line
|
|
var comment string
|
|
if strings.Contains(restPart, "#") {
|
|
// Find the comment part (not inside quotes)
|
|
inQuotes := false
|
|
for i, char := range restPart {
|
|
if char == '"' && (i == 0 || restPart[i-1] != '\\') {
|
|
inQuotes = !inQuotes
|
|
} else if char == '#' && !inQuotes {
|
|
comment = strings.TrimSpace(restPart[i+1:])
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
// Store comment if it exists
|
|
if comment != "" {
|
|
// Build the full path string
|
|
fullPath := strings.Join(currentPath, ".")
|
|
|
|
// Look up the type and field name from our dynamic mapping
|
|
if pathInfo, exists := pathMap[fullPath]; exists {
|
|
typeName := pathInfo.TypeName
|
|
fieldName := pathInfo.FieldName
|
|
|
|
// Initialize maps if they don't exist
|
|
if comments[typeName] == nil {
|
|
comments[typeName] = make(map[string]string)
|
|
}
|
|
if secrets[typeName] == nil {
|
|
secrets[typeName] = make(map[string]bool)
|
|
}
|
|
if deprecated[typeName] == nil {
|
|
deprecated[typeName] = make(map[string]bool)
|
|
}
|
|
|
|
comments[typeName][fieldName] = comment
|
|
|
|
// Check for secret and deprecated markers
|
|
commentLower := strings.ToLower(comment)
|
|
if strings.Contains(commentLower, "secret:") {
|
|
secrets[typeName][fieldName] = true
|
|
}
|
|
if strings.Contains(commentLower, "deprecated:") {
|
|
deprecated[typeName][fieldName] = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return comments, secrets, deprecated, nil
|
|
}
|
|
|
|
// parseDefaultsFromEmbeddedYaml creates a default config by parsing the embedded YAML template
|
|
func parseDefaultsFromEmbeddedYaml(embeddedYaml string) (*Settings, error) {
|
|
// Start with baseline defaults from setDefaults to ensure all fields are initialized
|
|
defaultConfig := SetDefaults(true)
|
|
defaultConfig.Server.Sources = []*Source{{Path: "."}}
|
|
|
|
// Parse the embedded YAML to overlay the documented defaults
|
|
if err := yaml.Unmarshal([]byte(embeddedYaml), &defaultConfig); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal embedded YAML into config: %v", err)
|
|
}
|
|
|
|
return &defaultConfig, nil
|
|
}
|
|
|
|
// embeddedGeneratedConfigYAMLCandidates lists on-disk template paths for config.generated.yaml.
|
|
var embeddedGeneratedConfigYAMLCandidates = []string{
|
|
"internal/web/dist/config.generated.yaml",
|
|
"backend/internal/web/dist/config.generated.yaml",
|
|
"dist/config.generated.yaml",
|
|
}
|
|
|
|
// ReadFirstExistingFile returns the content of the first candidate path that exists and is non-empty.
|
|
func ReadFirstExistingFile(candidates []string) (string, error) {
|
|
for _, path := range candidates {
|
|
content, err := os.ReadFile(path)
|
|
if err == nil && len(content) > 0 {
|
|
return string(content), nil
|
|
}
|
|
}
|
|
return "", fmt.Errorf("no readable file among %d candidate path(s)", len(candidates))
|
|
}
|
|
|
|
// readEmbeddedYaml attempts to read the embedded config.generated.yaml file
|
|
func readEmbeddedYaml() (string, error) {
|
|
content, err := ReadFirstExistingFile(embeddedGeneratedConfigYAMLCandidates)
|
|
if err != nil {
|
|
return "", fmt.Errorf("could not read embedded YAML from any path: %w", err)
|
|
}
|
|
return content, nil
|
|
}
|
|
|
|
// BuildNode constructs a yaml.Node for any Go value, injecting comments on struct fields.
|
|
func BuildNode(v reflect.Value, comm CommentsMap) (*yaml.Node, error) {
|
|
return buildNodeWithDefaults(v, comm, reflect.Value{}, SecretFieldsMap{}, DeprecatedFieldsMap{})
|
|
}
|
|
|
|
func conditionalRulesAreUnset(rules []ConditionalRule) bool {
|
|
if len(rules) == 0 {
|
|
return true
|
|
}
|
|
for _, rule := range rules {
|
|
if rule != (ConditionalRule{}) {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// buildNodeWithDefaults constructs a yaml.Node for any Go value, skipping fields that match defaults, redacting secrets, and filtering deprecated fields
|
|
func buildNodeWithDefaults(v reflect.Value, comm CommentsMap, defaults reflect.Value, secrets SecretFieldsMap, deprecated DeprecatedFieldsMap) (*yaml.Node, error) {
|
|
// Dereference pointers
|
|
if v.Kind() == reflect.Pointer {
|
|
if v.IsNil() {
|
|
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: "null"}, nil
|
|
}
|
|
var defaultsElem reflect.Value
|
|
if defaults.IsValid() && !defaults.IsNil() {
|
|
defaultsElem = defaults.Elem()
|
|
}
|
|
return buildNodeWithDefaults(v.Elem(), comm, defaultsElem, secrets, deprecated)
|
|
}
|
|
|
|
switch v.Kind() {
|
|
case reflect.String:
|
|
value := v.String()
|
|
return &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Tag: "!!str",
|
|
Value: value,
|
|
Style: getStringStyle(value),
|
|
}, nil
|
|
case reflect.Struct:
|
|
rt := v.Type()
|
|
typeName := rt.Name()
|
|
mapNode := &yaml.Node{Kind: yaml.MappingNode}
|
|
for i := 0; i < rt.NumField(); i++ {
|
|
sf := rt.Field(i)
|
|
|
|
// skip unexported or omitted fields
|
|
if sf.PkgPath != "" {
|
|
continue
|
|
}
|
|
if yamlTag := sf.Tag.Get("yaml"); yamlTag == "-" {
|
|
continue
|
|
}
|
|
if jsonTag := sf.Tag.Get("json"); jsonTag == "-" {
|
|
continue
|
|
}
|
|
|
|
// Skip deprecated fields if filtering is enabled
|
|
if len(deprecated) > 0 && deprecated[typeName][sf.Name] {
|
|
continue
|
|
}
|
|
|
|
currentField := v.Field(i)
|
|
|
|
// Unset source display names are derived at startup; omit from minimal YAML export.
|
|
if defaults.IsValid() && typeName == "Source" && sf.Name == "Name" && currentField.Kind() == reflect.String && currentField.String() == "" {
|
|
continue
|
|
}
|
|
|
|
// Empty conditional rules are omitted from minimal YAML (template may include a sample row).
|
|
if defaults.IsValid() && typeName == "SourceConfig" && sf.Name == "Rules" {
|
|
if rules, ok := currentField.Interface().([]ConditionalRule); ok && conditionalRulesAreUnset(rules) {
|
|
continue
|
|
}
|
|
}
|
|
|
|
// Check if this is an inline/embedded field
|
|
yamlTag := sf.Tag.Get("yaml")
|
|
jsonTag := sf.Tag.Get("json")
|
|
isInline := strings.Contains(yamlTag, ",inline") || strings.Contains(jsonTag, ",inline") || sf.Anonymous
|
|
|
|
// If field is inline, merge its content directly into parent
|
|
if isInline && sf.Type.Kind() == reflect.Struct {
|
|
// Get the embedded struct's fields and add them directly to this level
|
|
embeddedType := sf.Type
|
|
embeddedValue := currentField
|
|
embeddedTypeName := embeddedType.Name()
|
|
|
|
for j := 0; j < embeddedType.NumField(); j++ {
|
|
embeddedField := embeddedType.Field(j)
|
|
|
|
// Skip unexported fields
|
|
if embeddedField.PkgPath != "" {
|
|
continue
|
|
}
|
|
if embeddedYamlTag := embeddedField.Tag.Get("yaml"); embeddedYamlTag == "-" {
|
|
continue
|
|
}
|
|
if embeddedJsonTag := embeddedField.Tag.Get("json"); embeddedJsonTag == "-" {
|
|
continue
|
|
}
|
|
|
|
// Skip deprecated fields
|
|
if len(deprecated) > 0 && deprecated[embeddedTypeName][embeddedField.Name] {
|
|
continue
|
|
}
|
|
|
|
embeddedFieldValue := embeddedValue.Field(j)
|
|
|
|
// If we have defaults, compare and skip if values match
|
|
if defaults.IsValid() && i < defaults.NumField() {
|
|
defaultInlineField := defaults.Field(i)
|
|
if defaultInlineField.Kind() == reflect.Struct && j < defaultInlineField.NumField() {
|
|
defaultEmbeddedField := defaultInlineField.Field(j)
|
|
embeddedCurrentValue := embeddedFieldValue.Interface()
|
|
embeddedDefaultValue := defaultEmbeddedField.Interface()
|
|
|
|
if reflect.DeepEqual(embeddedCurrentValue, embeddedDefaultValue) {
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
// Determine key name for embedded field
|
|
embeddedYamlTag := embeddedField.Tag.Get("yaml")
|
|
embeddedJsonTag := embeddedField.Tag.Get("json")
|
|
var embeddedKeyName string
|
|
if embeddedYamlTag != "" && embeddedYamlTag != "-" {
|
|
embeddedKeyName = strings.Split(embeddedYamlTag, ",")[0]
|
|
} else if embeddedJsonTag != "" && embeddedJsonTag != "-" {
|
|
embeddedKeyName = strings.Split(embeddedJsonTag, ",")[0]
|
|
} else {
|
|
embeddedKeyName = embeddedField.Name
|
|
}
|
|
|
|
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: embeddedKeyName}
|
|
|
|
// Attach comments for embedded field
|
|
var parts []string
|
|
var comment string
|
|
if cm := comm[embeddedTypeName][embeddedField.Name]; cm != "" {
|
|
comment = cm
|
|
}
|
|
|
|
if comment != "" {
|
|
parts = append(parts, comment)
|
|
}
|
|
if len(comm) > 0 {
|
|
if vt := embeddedField.Tag.Get("validate"); vt != "" {
|
|
parts = append(parts, fmt.Sprintf(" validate:%s", vt))
|
|
}
|
|
}
|
|
|
|
if len(parts) > 0 {
|
|
keyNode.LineComment = strings.Join(parts, " ")
|
|
}
|
|
|
|
// Build value node for embedded field
|
|
var valNode *yaml.Node
|
|
var err error
|
|
generateConfig := os.Getenv("FILEBROWSER_GENERATE_CONFIG") == "true"
|
|
if secrets[embeddedTypeName][embeddedField.Name] && !generateConfig {
|
|
fieldValue := embeddedFieldValue.Interface()
|
|
if str, ok := fieldValue.(string); ok && str == "" {
|
|
valNode = &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Tag: "!!str",
|
|
Value: "",
|
|
Style: yaml.DoubleQuotedStyle,
|
|
}
|
|
} else {
|
|
valNode = &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Tag: "!!str",
|
|
Value: "**hidden**",
|
|
Style: yaml.DoubleQuotedStyle,
|
|
}
|
|
}
|
|
} else {
|
|
var defaultEmbeddedField reflect.Value
|
|
if defaults.IsValid() && i < defaults.NumField() {
|
|
defaultInlineField := defaults.Field(i)
|
|
if defaultInlineField.Kind() == reflect.Struct && j < defaultInlineField.NumField() {
|
|
defaultEmbeddedField = defaultInlineField.Field(j)
|
|
}
|
|
}
|
|
|
|
valNode, err = buildNodeWithDefaults(embeddedFieldValue, comm, defaultEmbeddedField, secrets, deprecated)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
mapNode.Content = append(mapNode.Content, keyNode, valNode)
|
|
}
|
|
|
|
// Skip adding the embedded struct itself as a field
|
|
continue
|
|
}
|
|
|
|
// If we have defaults, compare and skip if values match
|
|
if defaults.IsValid() && i < defaults.NumField() {
|
|
defaultField := defaults.Field(i)
|
|
currentValue := currentField.Interface()
|
|
defaultValue := defaultField.Interface()
|
|
|
|
isEqual := reflect.DeepEqual(currentValue, defaultValue)
|
|
|
|
if isEqual {
|
|
continue // Skip this field as it matches the default
|
|
}
|
|
}
|
|
|
|
// determine key: yaml tag > json tag > field name
|
|
var keyName string
|
|
if yamlTag != "" && yamlTag != "-" {
|
|
keyName = strings.Split(yamlTag, ",")[0]
|
|
} else if jsonTag != "" && jsonTag != "-" {
|
|
keyName = strings.Split(jsonTag, ",")[0]
|
|
} else {
|
|
keyName = sf.Name
|
|
}
|
|
|
|
keyNode := &yaml.Node{Kind: yaml.ScalarNode, Value: keyName}
|
|
|
|
// attach validate and comments inline (only when comments are enabled)
|
|
var parts []string
|
|
|
|
// Try to find comment - first by current type, then by field's actual type
|
|
var comment string
|
|
if cm := comm[typeName][sf.Name]; cm != "" {
|
|
comment = cm
|
|
} else {
|
|
// Try the field's actual type name (for embedded structs)
|
|
fieldTypeName := sf.Type.Name()
|
|
if fieldTypeName != "" && comm[fieldTypeName][sf.Name] != "" {
|
|
comment = comm[fieldTypeName][sf.Name]
|
|
}
|
|
}
|
|
|
|
if comment != "" {
|
|
parts = append(parts, comment)
|
|
}
|
|
// Only add validation tags if comments map is not empty (meaning comments are enabled)
|
|
if len(comm) > 0 {
|
|
if vt := sf.Tag.Get("validate"); vt != "" {
|
|
parts = append(parts, fmt.Sprintf(" validate:%s", vt))
|
|
}
|
|
}
|
|
|
|
if len(parts) > 0 {
|
|
keyNode.LineComment = strings.Join(parts, " ")
|
|
}
|
|
|
|
// Check if this field should be redacted as a secret
|
|
var valNode *yaml.Node
|
|
var err error
|
|
generateConfig := os.Getenv("FILEBROWSER_GENERATE_CONFIG") == "true"
|
|
if secrets[typeName][sf.Name] && !generateConfig {
|
|
// Check if the secret value is empty
|
|
fieldValue := currentField.Interface()
|
|
if str, ok := fieldValue.(string); ok && str == "" {
|
|
// Show empty string for empty secret values
|
|
valNode = &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Tag: "!!str",
|
|
Value: "",
|
|
Style: yaml.DoubleQuotedStyle,
|
|
}
|
|
} else {
|
|
// Show **hidden** for non-empty secret values
|
|
valNode = &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Tag: "!!str",
|
|
Value: "**hidden**",
|
|
Style: yaml.DoubleQuotedStyle, // Keep secrets quoted for clarity
|
|
}
|
|
}
|
|
} else {
|
|
// Pass through the corresponding default field for recursive comparison
|
|
var defaultField reflect.Value
|
|
if defaults.IsValid() && i < defaults.NumField() {
|
|
defaultField = defaults.Field(i)
|
|
}
|
|
|
|
valNode, err = buildNodeWithDefaults(currentField, comm, defaultField, secrets, deprecated)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
mapNode.Content = append(mapNode.Content, keyNode, valNode)
|
|
}
|
|
return mapNode, nil
|
|
|
|
case reflect.Slice, reflect.Array:
|
|
// For empty arrays, return a null node so only the key with comment appears
|
|
if v.Len() == 0 {
|
|
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!null", Value: ""}, nil
|
|
}
|
|
|
|
seq := &yaml.Node{Kind: yaml.SequenceNode}
|
|
// for non-struct slices, render inline [] via flow style
|
|
elemType := v.Type().Elem()
|
|
// Check if element is a struct or pointer to struct
|
|
isStructSlice := elemType.Kind() == reflect.Struct ||
|
|
(elemType.Kind() == reflect.Pointer && elemType.Elem().Kind() == reflect.Struct)
|
|
if !isStructSlice && elemType.Kind() != reflect.String {
|
|
seq.Style = yaml.FlowStyle
|
|
}
|
|
for i := 0; i < v.Len(); i++ {
|
|
var defaultElem reflect.Value
|
|
if defaults.IsValid() && i < defaults.Len() {
|
|
defaultElem = defaults.Index(i)
|
|
}
|
|
n, err := buildNodeWithDefaults(v.Index(i), comm, defaultElem, secrets, deprecated)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
seq.Content = append(seq.Content, n)
|
|
}
|
|
return seq, nil
|
|
|
|
case reflect.Map:
|
|
if v.Len() == 0 {
|
|
// Return an empty string node for empty maps, which renders as a blank value.
|
|
return &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: ""}, nil
|
|
}
|
|
mapNode := &yaml.Node{Kind: yaml.MappingNode}
|
|
|
|
// Get and sort map keys alphabetically for consistent output
|
|
mapKeys := v.MapKeys()
|
|
keyStrings := make([]string, len(mapKeys))
|
|
keyMap := make(map[string]reflect.Value)
|
|
for i, key := range mapKeys {
|
|
keyStr := fmt.Sprintf("%v", key.Interface())
|
|
keyStrings[i] = keyStr
|
|
keyMap[keyStr] = key
|
|
}
|
|
|
|
// Sort alphabetically
|
|
sort.Strings(keyStrings)
|
|
|
|
for _, keyStr := range keyStrings {
|
|
key := keyMap[keyStr]
|
|
|
|
// Handle key
|
|
keyNode := &yaml.Node{
|
|
Kind: yaml.ScalarNode,
|
|
Value: keyStr,
|
|
}
|
|
|
|
// Handle value recursively
|
|
mapVal := v.MapIndex(key)
|
|
var defaultVal reflect.Value
|
|
if defaults.IsValid() {
|
|
defaultVal = defaults.MapIndex(key)
|
|
}
|
|
|
|
valNode, err := buildNodeWithDefaults(mapVal, comm, defaultVal, secrets, deprecated)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
mapNode.Content = append(mapNode.Content, keyNode, valNode)
|
|
}
|
|
return mapNode, nil
|
|
|
|
default:
|
|
n := &yaml.Node{}
|
|
if err := n.Encode(v.Interface()); err != nil {
|
|
return nil, err
|
|
}
|
|
return n, nil
|
|
}
|
|
}
|
|
|
|
func GenerateYaml() {
|
|
_ = loadConfigWithDefaults("", true)
|
|
Config.Server.Sources = []*Source{
|
|
{
|
|
Path: ".",
|
|
Config: SourceConfig{
|
|
Rules: []ConditionalRule{
|
|
{}, // Add empty sample rule to show all fields in generated YAML
|
|
},
|
|
},
|
|
},
|
|
}
|
|
|
|
setupLogging()
|
|
setupFs()
|
|
setupAuth(true)
|
|
setupSources(true)
|
|
setupUrls()
|
|
setupMedia()
|
|
setupFrontend(true)
|
|
|
|
output := "../frontend/public/config.generated.yaml" // "output YAML file"
|
|
|
|
// Generate YAML with comments enabled, full config, and deprecated fields filtered
|
|
// Use multi-directory comment parsing to get comments from all packages
|
|
yamlContent, err := GenerateConfigYamlWithSource(&Config, true, true, true, "pkg/settings")
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "error generating YAML: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
existing, readErr := os.ReadFile(output)
|
|
if readErr == nil && string(existing) == yamlContent {
|
|
return
|
|
}
|
|
if err := os.WriteFile(output, []byte(yamlContent), 0644); err != nil {
|
|
fmt.Fprintf(os.Stderr, "error writing YAML: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
if !isGoTest() {
|
|
fmt.Printf("Generated YAML with comments (deprecated fields filtered): %s\n", output)
|
|
}
|
|
}
|
|
|
|
// GenerateConfigYaml generates YAML from a given config with options for comments and filtering
|
|
func GenerateConfigYaml(config *Settings, showComments bool, showFull bool, filterDeprecated bool) (string, error) {
|
|
// Try different source paths to handle both runtime and test scenarios
|
|
sourcePaths := []string{
|
|
".", // When running tests from settings directory
|
|
"../pkg/settings", // When running from backend directory
|
|
"pkg/settings", // Alternative path
|
|
}
|
|
|
|
for _, sourcePath := range sourcePaths {
|
|
yamlOutput, err := GenerateConfigYamlWithSource(config, showComments, showFull, filterDeprecated, sourcePath)
|
|
if err == nil {
|
|
return yamlOutput, nil
|
|
}
|
|
// If it's not a file not found error, return immediately
|
|
if !strings.Contains(err.Error(), "no such file or directory") && !strings.Contains(err.Error(), "cannot find") {
|
|
return "", err
|
|
}
|
|
}
|
|
|
|
// If all paths failed, try with empty maps to at least generate basic YAML
|
|
return GenerateConfigYamlWithEmptyMaps(config, showFull)
|
|
}
|
|
|
|
// GenerateConfigYamlWithEmbedded generates YAML from a given config using embedded YAML content as comment source
|
|
func GenerateConfigYamlWithEmbedded(config *Settings, showComments bool, showFull bool, filterDeprecated bool, embeddedYaml string) (string, error) {
|
|
var comm CommentsMap
|
|
var secrets SecretFieldsMap
|
|
var deprecated DeprecatedFieldsMap
|
|
var err error
|
|
|
|
if embeddedYaml != "" {
|
|
// Always parse the embedded YAML to get secrets and deprecated fields
|
|
comm, secrets, deprecated, err = CollectCommentsFromEmbeddedYaml(embeddedYaml)
|
|
if err != nil {
|
|
return "", fmt.Errorf("error parsing embedded YAML comments: %w", err)
|
|
}
|
|
|
|
// If not showing comments, clear the comments map but keep secrets and deprecated
|
|
if !showComments {
|
|
comm = make(CommentsMap)
|
|
}
|
|
} else {
|
|
// Create empty maps only if no embedded YAML is available
|
|
comm = make(CommentsMap)
|
|
secrets = make(SecretFieldsMap)
|
|
deprecated = make(DeprecatedFieldsMap)
|
|
}
|
|
|
|
// If not filtering deprecated fields, clear the deprecated map
|
|
if !filterDeprecated {
|
|
deprecated = make(DeprecatedFieldsMap)
|
|
}
|
|
|
|
// The embedded YAML omits deprecated fields entirely, so the marker map has no entry for a
|
|
// deprecated field that is also a secret (e.g. the top-level auth.adminUsername/adminPassword).
|
|
// Union in the field-name fallback so those are redacted too.
|
|
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
|
|
|
|
var node *yaml.Node
|
|
|
|
if showFull {
|
|
// Show the full current config
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
|
|
} else {
|
|
// Show only non-default values by comparing with defaults from embedded YAML
|
|
defaultConfig, parseErr := parseDefaultsFromEmbeddedYaml(embeddedYaml)
|
|
if parseErr != nil {
|
|
return "", fmt.Errorf("failed to parse defaults from embedded YAML: %v", parseErr)
|
|
}
|
|
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
|
|
}
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Create document
|
|
doc := &yaml.Node{Kind: yaml.DocumentNode}
|
|
doc.Content = []*yaml.Node{node}
|
|
|
|
// Encode to YAML
|
|
var rawBuf bytes.Buffer
|
|
enc := yaml.NewEncoder(&rawBuf)
|
|
enc.SetIndent(2)
|
|
if err := enc.Encode(doc); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Apply comment alignment if comments are enabled
|
|
yamlOutput := rawBuf.String()
|
|
if showComments {
|
|
yamlOutput = AlignComments(yamlOutput)
|
|
}
|
|
|
|
return yamlOutput, nil
|
|
}
|
|
|
|
// redactPlaceholder replaces secret values in API responses without revealing the original.
|
|
const redactPlaceholder = "**hidden**"
|
|
|
|
// RedactedSettingsCopy returns a deep copy of the given config with every secret-marked field
|
|
// replaced by the redaction placeholder. The live config is never modified, so callers can
|
|
// render the result to an API response without disabling authentication (a mutated
|
|
// settings.Config would break JWT signing/verification and the OIDC/LDAP/OnlyOffice integrations
|
|
// until restart). See GHSA-892f-9h5p-mfc8.
|
|
func RedactedSettingsCopy(conf *Settings) *Settings {
|
|
if conf == nil {
|
|
return nil
|
|
}
|
|
cpVal := deepCopyValue(reflect.ValueOf(conf))
|
|
cp, ok := cpVal.Interface().(*Settings)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
secrets := buildSecretFieldsFor(conf)
|
|
redactSecretsValue(reflect.ValueOf(cp), "Settings", secrets)
|
|
return cp
|
|
}
|
|
|
|
// RedactAuthSecrets returns a copy of the auth section with secret fields replaced by the
|
|
// redaction placeholder, leaving the live config untouched.
|
|
func RedactAuthSecrets(auth Auth) Auth {
|
|
cp := auth
|
|
secrets := buildSecretFieldsFor(&Settings{Auth: Config.Auth})
|
|
redactSecretsValue(reflect.ValueOf(&cp), "Auth", secrets)
|
|
return cp
|
|
}
|
|
|
|
// deepCopyValue returns a deep copy of v, preserving the exact field values (including unexported
|
|
// fields) rather than round-tripping through JSON, which would run custom unmarshalers and change
|
|
// semantics (e.g. users.Permissions.UnmarshalJSON sets Configured).
|
|
func deepCopyValue(v reflect.Value) reflect.Value {
|
|
switch v.Kind() {
|
|
case reflect.Pointer:
|
|
if v.IsNil() {
|
|
return v
|
|
}
|
|
cp := reflect.New(v.Type().Elem())
|
|
cp.Elem().Set(deepCopyValue(v.Elem()))
|
|
return cp
|
|
case reflect.Interface:
|
|
if v.IsNil() {
|
|
return v
|
|
}
|
|
cp := deepCopyValue(v.Elem())
|
|
out := reflect.New(v.Type()).Elem()
|
|
out.Set(cp)
|
|
return out
|
|
case reflect.Struct:
|
|
out := reflect.New(v.Type()).Elem()
|
|
t := v.Type()
|
|
for i := 0; i < t.NumField(); i++ {
|
|
dst := out.Field(i)
|
|
if dst.CanSet() {
|
|
dst.Set(deepCopyValue(v.Field(i)))
|
|
}
|
|
}
|
|
return out
|
|
case reflect.Slice:
|
|
if v.IsNil() {
|
|
return v
|
|
}
|
|
out := reflect.MakeSlice(v.Type(), v.Len(), v.Len())
|
|
for i := 0; i < v.Len(); i++ {
|
|
out.Index(i).Set(deepCopyValue(v.Index(i)))
|
|
}
|
|
return out
|
|
case reflect.Array:
|
|
out := reflect.New(v.Type()).Elem()
|
|
for i := 0; i < v.Len(); i++ {
|
|
out.Index(i).Set(deepCopyValue(v.Index(i)))
|
|
}
|
|
return out
|
|
case reflect.Map:
|
|
if v.IsNil() {
|
|
return v
|
|
}
|
|
out := reflect.MakeMapWithSize(v.Type(), v.Len())
|
|
iter := v.MapRange()
|
|
for iter.Next() {
|
|
out.SetMapIndex(deepCopyValue(iter.Key()), deepCopyValue(iter.Value()))
|
|
}
|
|
return out
|
|
default:
|
|
return v
|
|
}
|
|
}
|
|
|
|
// SecretFieldNames are struct field names treated as secret regardless of comment markers.
|
|
// Used both for YAML redaction and for redacting GET /api/settings responses.
|
|
var SecretFieldNames = map[string]bool{
|
|
"Key": true,
|
|
"AdminUsername": true,
|
|
"AdminPassword": true,
|
|
"TotpSecret": true,
|
|
"ClientID": true,
|
|
"ClientSecret": true,
|
|
"Secret": true,
|
|
"UserPassword": true,
|
|
"Password": true,
|
|
"ApiKey": true,
|
|
"APIKey": true,
|
|
"BearerToken": true,
|
|
"PrivateKey": true,
|
|
}
|
|
|
|
// SecretHintYaml holds the embedded config.generated.yaml text used to discover `secret:`
|
|
// comment markers at runtime. The web layer sets it from the running binary's asset
|
|
// filesystem; the settings sources are not present in a deployed binary.
|
|
var SecretHintYaml string
|
|
|
|
// ActiveSecretFields returns the struct type -> field name -> is secret mapping for the running
|
|
// config. It combines the explicit `secret:` comment markers (from the embedded YAML when
|
|
// available, otherwise the Go sources) with the SecretFieldNames reflection fallback, so a new
|
|
// field named ApiKey/Secret/etc. is caught even without a marker.
|
|
func ActiveSecretFields() SecretFieldsMap {
|
|
return buildSecretFieldsFor(&Config)
|
|
}
|
|
|
|
func buildSecretFieldsFor(conf *Settings) SecretFieldsMap {
|
|
var secrets SecretFieldsMap
|
|
|
|
// Prefer the embedded YAML: it is the only marker source available in a deployed binary,
|
|
// and the generator fixes the comments for every field real users configure.
|
|
if SecretHintYaml != "" {
|
|
if _, s, _, err := CollectCommentsFromEmbeddedYaml(SecretHintYaml); err == nil && hasAnySecret(s) {
|
|
secrets = s
|
|
}
|
|
}
|
|
if !hasAnySecret(secrets) {
|
|
// Fall back to the Go sources (repo layout / tests). CollectCommentsAndSecrets also
|
|
// unions in the reflection fallback, so this path never under-reports.
|
|
// Try each candidate directory until one parses with markers, so a missing or
|
|
// unparsable first candidate does not skip a valid later one.
|
|
for _, srcPath := range settingsSourcePaths() {
|
|
if !isSettingsSourceDir(srcPath) {
|
|
continue
|
|
}
|
|
if _, s, _, err := CollectCommentsAndSecrets(srcPath); err == nil && hasAnySecret(s) {
|
|
secrets = s
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if secrets == nil {
|
|
secrets = make(SecretFieldsMap)
|
|
}
|
|
// Always apply the reflection fallback so the map is complete even when only the embedded
|
|
// YAML was consulted (it covers the deprecated-but-secret auth.adminUsername/adminPassword
|
|
// fields, which the filtered generated YAML omits entirely).
|
|
identifySecretFieldsByReflection(reflect.ValueOf(conf), "Settings", secrets)
|
|
return secrets
|
|
}
|
|
|
|
// redactSecretsValue walks a settings value and replaces every field marked secret with the
|
|
// redaction placeholder, preserving the original structure for the JSON response.
|
|
func redactSecretsValue(v reflect.Value, typeName string, secrets SecretFieldsMap) {
|
|
switch v.Kind() {
|
|
case reflect.Pointer, reflect.Interface:
|
|
if v.IsNil() {
|
|
return
|
|
}
|
|
redactSecretsValue(v.Elem(), typeName, secrets)
|
|
case reflect.Slice, reflect.Array:
|
|
for i := 0; i < v.Len(); i++ {
|
|
redactSecretsValue(v.Index(i), typeName, secrets)
|
|
}
|
|
case reflect.Map:
|
|
for _, key := range v.MapKeys() {
|
|
redactSecretsValue(v.MapIndex(key), typeName, secrets)
|
|
}
|
|
case reflect.Struct:
|
|
t := v.Type()
|
|
for i := 0; i < t.NumField(); i++ {
|
|
field := t.Field(i)
|
|
if field.PkgPath != "" {
|
|
continue
|
|
}
|
|
fieldValue := v.Field(i)
|
|
if !fieldValue.CanSet() {
|
|
continue
|
|
}
|
|
fieldTypeName := fieldTypeNameFor(field)
|
|
switch {
|
|
case isSecretField(typeName, field.Name, secrets):
|
|
redactStringValue(fieldValue)
|
|
case field.Anonymous && jsonTagIsInline(field):
|
|
// encoding/json flattens embedded inline structs into the parent object.
|
|
redactSecretsValue(fieldValue, fieldTypeName, secrets)
|
|
case fieldValue.Kind() == reflect.Struct:
|
|
redactSecretsValue(fieldValue, fieldTypeName, secrets)
|
|
case fieldValue.Kind() == reflect.Pointer && !fieldValue.IsNil() && fieldValue.Elem().Kind() == reflect.Struct:
|
|
redactSecretsValue(fieldValue, fieldTypeName, secrets)
|
|
case fieldValue.Kind() == reflect.Slice && fieldValue.Type().Elem().Kind() == reflect.Struct:
|
|
redactSecretsValue(fieldValue, fieldTypeName, secrets)
|
|
case fieldValue.Kind() == reflect.Map && fieldValue.Type().Elem().Kind() == reflect.Struct:
|
|
redactSecretsValue(fieldValue, fieldTypeName, secrets)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func isSecretField(typeName, fieldName string, secrets SecretFieldsMap) bool {
|
|
if secrets != nil && secrets[typeName][fieldName] {
|
|
return true
|
|
}
|
|
return SecretFieldNames[fieldName]
|
|
}
|
|
|
|
func fieldTypeNameFor(field reflect.StructField) string {
|
|
t := field.Type
|
|
if t.Kind() == reflect.Pointer {
|
|
t = t.Elem()
|
|
}
|
|
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array || t.Kind() == reflect.Map {
|
|
t = t.Elem()
|
|
}
|
|
if t.Kind() == reflect.Pointer {
|
|
t = t.Elem()
|
|
}
|
|
return t.Name()
|
|
}
|
|
|
|
func jsonTagIsInline(field reflect.StructField) bool {
|
|
tag := field.Tag.Get("json")
|
|
return strings.Contains(tag, "inline") || tag == ""
|
|
}
|
|
|
|
// redactStringValue replaces a string-ish secret field's value with the placeholder. Non-empty
|
|
// values are replaced; already-empty values are left empty so an unset secret does not appear set.
|
|
func redactStringValue(v reflect.Value) {
|
|
if v.Kind() == reflect.Pointer {
|
|
if v.IsNil() {
|
|
return
|
|
}
|
|
v = v.Elem()
|
|
}
|
|
if v.Kind() != reflect.String || v.String() == "" {
|
|
return
|
|
}
|
|
v.SetString(redactPlaceholder)
|
|
}
|
|
|
|
// settingsSourcePaths returns candidate directories holding the settings Go sources, used as a
|
|
// fallback when the embedded YAML is unavailable during secret detection.
|
|
func settingsSourcePaths() []string {
|
|
return []string{".", "pkg/settings", "../pkg/settings", "../../pkg/settings"}
|
|
}
|
|
|
|
// hasAnySecret reports whether the map holds at least one field marked secret. Parsers create
|
|
// an entry for every struct they see, so a non-empty map alone does not mean markers were found.
|
|
func hasAnySecret(secrets SecretFieldsMap) bool {
|
|
for _, fields := range secrets {
|
|
for _, secret := range fields {
|
|
if secret {
|
|
return true
|
|
}
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// isSettingsSourceDir reports whether dir looks like the settings package sources, so an
|
|
// unrelated Go package earlier in the candidate list (e.g. the working directory) is skipped.
|
|
func isSettingsSourceDir(dir string) bool {
|
|
info, err := os.Stat(filepath.Join(dir, "generator.go"))
|
|
if err != nil || info.IsDir() {
|
|
return false
|
|
}
|
|
info, err = os.Stat(filepath.Join(dir, "structs.go"))
|
|
return err == nil && !info.IsDir()
|
|
}
|
|
|
|
// identifySecretFieldsByReflection identifies secret fields by known field names
|
|
func identifySecretFieldsByReflection(v reflect.Value, typeName string, secrets SecretFieldsMap) {
|
|
if v.Kind() == reflect.Pointer {
|
|
if v.IsNil() {
|
|
return
|
|
}
|
|
v = v.Elem()
|
|
}
|
|
|
|
if v.Kind() != reflect.Struct {
|
|
return
|
|
}
|
|
|
|
t := v.Type()
|
|
if secrets[typeName] == nil {
|
|
secrets[typeName] = make(map[string]bool)
|
|
}
|
|
|
|
for i := 0; i < t.NumField(); i++ {
|
|
field := t.Field(i)
|
|
if SecretFieldNames[field.Name] {
|
|
secrets[typeName][field.Name] = true
|
|
}
|
|
|
|
// Recursively check nested structs
|
|
fieldValue := v.Field(i)
|
|
if fieldValue.Kind() == reflect.Struct || (fieldValue.Kind() == reflect.Pointer && !fieldValue.IsNil() && fieldValue.Elem().Kind() == reflect.Struct) {
|
|
nestedTypeName := field.Type.Name()
|
|
if field.Type.Kind() == reflect.Pointer {
|
|
nestedTypeName = field.Type.Elem().Name()
|
|
}
|
|
identifySecretFieldsByReflection(fieldValue, nestedTypeName, secrets)
|
|
}
|
|
}
|
|
}
|
|
|
|
// GenerateConfigYamlWithEmptyMaps generates YAML without comment parsing when source files are unavailable
|
|
func GenerateConfigYamlWithEmptyMaps(config *Settings, showFull bool) (string, error) {
|
|
// Create empty maps
|
|
comm := make(CommentsMap)
|
|
secrets := make(SecretFieldsMap)
|
|
deprecated := make(DeprecatedFieldsMap)
|
|
|
|
// Identify secret fields by reflection since we can't parse source files
|
|
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
|
|
|
|
var node *yaml.Node
|
|
var err error
|
|
|
|
if showFull {
|
|
// Show the full current config
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
|
|
} else {
|
|
// Show only non-default values by comparing with defaults during node building
|
|
// Try to use embedded YAML defaults for consistency, fallback to setDefaults
|
|
var defaultConfig *Settings
|
|
embeddedYaml, readErr := readEmbeddedYaml()
|
|
if readErr == nil {
|
|
defaultConfig, err = parseDefaultsFromEmbeddedYaml(embeddedYaml)
|
|
}
|
|
if err != nil || readErr != nil {
|
|
// Fallback to setDefaults
|
|
defaultConfigValue := SetDefaults(true)
|
|
defaultConfigValue.Server.Sources = []*Source{{Path: "."}}
|
|
defaultConfig = &defaultConfigValue
|
|
}
|
|
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
|
|
}
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Convert to YAML
|
|
doc := &yaml.Node{Kind: yaml.DocumentNode}
|
|
doc.Content = []*yaml.Node{node}
|
|
|
|
var rawBuf bytes.Buffer
|
|
enc := yaml.NewEncoder(&rawBuf)
|
|
enc.SetIndent(2)
|
|
if err := enc.Encode(doc); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return AlignComments(rawBuf.String()), nil
|
|
}
|
|
|
|
// GenerateConfigYamlWithSource generates YAML from a given config with options for comments and filtering, using a custom source path
|
|
func GenerateConfigYamlWithSource(config *Settings, showComments bool, showFull bool, filterDeprecated bool, sourcePath string) (string, error) {
|
|
var comm CommentsMap
|
|
var secrets SecretFieldsMap
|
|
var deprecated DeprecatedFieldsMap
|
|
var err error
|
|
|
|
if showComments {
|
|
// Collect comments, secrets, and deprecated fields from the settings source files
|
|
comm, secrets, deprecated, err = CollectCommentsAndSecrets(sourcePath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
} else {
|
|
// Still need to collect secrets and deprecated fields even if not showing comments
|
|
_, secrets, deprecated, err = CollectCommentsAndSecrets(sourcePath)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
// Create empty comments map
|
|
comm = make(CommentsMap)
|
|
}
|
|
|
|
// If secrets map is empty (directory parsing failed), use reflection to identify secrets
|
|
secretsEmpty := true
|
|
for typeName := range secrets {
|
|
if len(secrets[typeName]) > 0 {
|
|
secretsEmpty = false
|
|
break
|
|
}
|
|
}
|
|
if secretsEmpty {
|
|
identifySecretFieldsByReflection(reflect.ValueOf(config), "Settings", secrets)
|
|
}
|
|
|
|
// If not filtering deprecated fields, clear the deprecated map
|
|
if !filterDeprecated {
|
|
deprecated = make(DeprecatedFieldsMap)
|
|
}
|
|
|
|
var node *yaml.Node
|
|
|
|
if showFull {
|
|
// Show the full current config
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.Value{}, secrets, deprecated)
|
|
} else {
|
|
// Show only non-default values by comparing with defaults during node building
|
|
// Try to use embedded YAML defaults for consistency, fallback to setDefaults
|
|
var defaultConfig *Settings
|
|
embeddedYaml, readErr := readEmbeddedYaml()
|
|
if readErr == nil {
|
|
defaultConfig, err = parseDefaultsFromEmbeddedYaml(embeddedYaml)
|
|
}
|
|
if err != nil || readErr != nil {
|
|
// Fallback to setDefaults
|
|
defaultConfigValue := SetDefaults(true)
|
|
defaultConfigValue.Server.Sources = []*Source{{Path: "."}}
|
|
defaultConfig = &defaultConfigValue
|
|
}
|
|
|
|
node, err = buildNodeWithDefaults(reflect.ValueOf(config), comm, reflect.ValueOf(defaultConfig), secrets, deprecated)
|
|
}
|
|
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Create document
|
|
doc := &yaml.Node{Kind: yaml.DocumentNode}
|
|
doc.Content = []*yaml.Node{node}
|
|
|
|
// Encode to YAML
|
|
var rawBuf bytes.Buffer
|
|
enc := yaml.NewEncoder(&rawBuf)
|
|
enc.SetIndent(2)
|
|
if err := enc.Encode(doc); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
// Apply comment alignment if comments are enabled
|
|
yamlOutput := rawBuf.String()
|
|
if showComments {
|
|
yamlOutput = AlignComments(yamlOutput)
|
|
}
|
|
|
|
return yamlOutput, nil
|
|
}
|
|
|
|
// formatLine applies padding to a single line so its comment starts at a target column.
|
|
func formatLine(line string) string {
|
|
const targetCol = 42
|
|
const defaultPadding = 1
|
|
|
|
// Find the first # character that is NOT inside double or single quotes.
|
|
inSingle, inDouble := false, false
|
|
for i := 0; i < len(line); i++ {
|
|
c := line[i]
|
|
switch c {
|
|
case '\'':
|
|
if !inDouble {
|
|
inSingle = !inSingle
|
|
}
|
|
case '"':
|
|
if !inSingle {
|
|
inDouble = !inDouble
|
|
}
|
|
case '#':
|
|
if !inSingle && !inDouble {
|
|
// found a comment
|
|
contentPart := line[:i]
|
|
commentPart := line[i:]
|
|
trimmedContent := strings.TrimRight(contentPart, " ")
|
|
if len(trimmedContent) >= targetCol {
|
|
return trimmedContent + strings.Repeat(" ", defaultPadding) + commentPart
|
|
}
|
|
paddingNeeded := targetCol - len(trimmedContent)
|
|
return trimmedContent + strings.Repeat(" ", paddingNeeded) + commentPart
|
|
}
|
|
}
|
|
}
|
|
// No comment found
|
|
return line
|
|
}
|
|
|
|
// AlignComments formats each line of the YAML string independently.
|
|
func AlignComments(input string) string {
|
|
lines := strings.Split(input, "\n")
|
|
outputLines := make([]string, len(lines))
|
|
|
|
for i, line := range lines {
|
|
outputLines[i] = formatLine(line)
|
|
}
|
|
|
|
return strings.Join(outputLines, "\n")
|
|
}
|