Debian Codegraph @

pkg/transformers/initransformer/ini_transformer.go

raw symbols SCIP
1 // Package initransformer supports transformation from configuration file format (like .ini, .properties .cnf or .cfg)
2 package initransformer
3
4 import (
5 "fmt"
6 "strings"
7
8 "github.com/DefangLabs/secret-detector/pkg/dataformat"
9
10 "gopkg.in/ini.v1"
11
12 "github.com/DefangLabs/secret-detector/pkg/secrets"
13 )
14
15 const (
16 Name = "ini"
17 )
18
19 var supportedFormats = []dataformat.DataFormat{dataformat.INI, dataformat.CNF, dataformat.CFG, dataformat.ENV, dataformat.Properties}
20
21 func init() {
22 secrets.GetTransformerFactory().Register(Name, NewTransformer)
23 }
24
25 type transformer struct {
26 }
27
28 func NewTransformer() secrets.Transformer {
29 return &transformer{}
30 }
31
32 func (t *transformer) Transform(in string) (map[string]string, bool) {
33 // Try parse twice, because nested values option and allow multiline options overlaps
34 // (when using both options together nested values are treated as multiline values)
35 iniFile, err := ini.LoadSources(ini.LoadOptions{AllowNestedValues: true}, []byte(in))
36 if err != nil {
37 iniFile, err = ini.LoadSources(ini.LoadOptions{AllowPythonMultilineValues: true}, []byte(in))
38 if err != nil {
39 return nil, false
40 }
41 }
42
43 iniMap := convertToMap(iniFile)
44 if len(iniMap) <= 1 {
45 if strings.Index(in, "=") >= len(in)-2 {
46 // make sure that the file with a single key is not base64 strings might end with == that might mistakenly parse
47 return nil, false
48
49 }
50 }
51 return iniMap, true
52 }
53
54 func (t *transformer) SupportedFormats() []dataformat.DataFormat {
55 return supportedFormats
56 }
57
58 func (t *transformer) SupportFiles() bool {
59 return true
60 }
61
62 func convertToMap(iniFile *ini.File) map[string]string {
63 iniMap := make(map[string]string)
64 for _, section := range iniFile.Sections() {
65 var path string
66 if section.Name() != ini.DefaultSection {
67 path = section.Name()
68 }
69
70 for _, key := range section.Keys() {
71 path := concatPath(path, key.Name())
72 if len(key.NestedValues()) == 0 {
73 iniMap[path] = key.Value()
74 }
75
76 for _, nestedKeyValue := range key.NestedValues() {
77 nestedKey, nestedValue := extractKeyAndValue(nestedKeyValue)
78 iniMap[concatPath(path, nestedKey)] = nestedValue
79 }
80 }
81 }
82
83 return iniMap
84 }
85
86 func extractKeyAndValue(keyValue string) (key, value string) {
87 separatorIndex := strings.IndexAny(keyValue, "=:")
88 if separatorIndex == -1 {
89 key = strings.TrimSpace(keyValue)
90 return
91 }
92
93 key = strings.TrimSpace(keyValue[:separatorIndex])
94 value = strings.TrimSpace(keyValue[separatorIndex+1:])
95 return
96 }
97
98 func concatPath(part1, part2 string) string {
99 if len(part1) == 0 {
100 return part2
101 }
102 return fmt.Sprintf("%s.%s", part1, part2)
103 }