| 1 |
package xmltransformer |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/xml" |
| 5 |
"fmt" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/DefangLabs/secret-detector/pkg/dataformat" |
| 9 |
|
| 10 |
"github.com/DefangLabs/secret-detector/pkg/secrets" |
| 11 |
) |
| 12 |
|
| 13 |
const ( |
| 14 |
Name = "xml" |
| 15 |
) |
| 16 |
|
| 17 |
var supportedFormats = []dataformat.DataFormat{dataformat.XML} |
| 18 |
|
| 19 |
func init() { |
| 20 |
secrets.GetTransformerFactory().Register(Name, NewTransformer) |
| 21 |
} |
| 22 |
|
| 23 |
type transformer struct { |
| 24 |
} |
| 25 |
|
| 26 |
func NewTransformer() secrets.Transformer { |
| 27 |
return &transformer{} |
| 28 |
} |
| 29 |
|
| 30 |
func (t *transformer) Transform(in string) (map[string]string, bool) { |
| 31 |
if !validateXML(in) { |
| 32 |
return nil, false |
| 33 |
} |
| 34 |
return t.xmlToMap(in), true |
| 35 |
} |
| 36 |
|
| 37 |
func (t *transformer) SupportedFormats() []dataformat.DataFormat { |
| 38 |
return supportedFormats |
| 39 |
} |
| 40 |
|
| 41 |
func (t *transformer) SupportFiles() bool { |
| 42 |
return true |
| 43 |
} |
| 44 |
|
| 45 |
func (t *transformer) xmlToMap(in string) map[string]string { |
| 46 |
res := make(map[string]string) |
| 47 |
s := newXMLStack() |
| 48 |
decoder := xml.NewDecoder(strings.NewReader(in)) |
| 49 |
for { |
| 50 |
tokenInterface, _ := decoder.Token() |
| 51 |
if tokenInterface == nil { |
| 52 |
break |
| 53 |
} |
| 54 |
|
| 55 |
switch token := tokenInterface.(type) { |
| 56 |
case xml.StartElement: |
| 57 |
s.Push(token) |
| 58 |
case xml.CharData: |
| 59 |
charData := strings.TrimSpace(string(token)) |
| 60 |
if len(charData) > 0 { |
| 61 |
if element := s.Peek(); element != nil { |
| 62 |
element.AppendCharData(charData) |
| 63 |
} |
| 64 |
} |
| 65 |
case xml.EndElement: |
| 66 |
element := s.Pop() |
| 67 |
for i, charData := range element.CharData() { |
| 68 |
if i == 0 { |
| 69 |
res[element.Path()] = charData |
| 70 |
} else { |
| 71 |
res[fmt.Sprintf("%v (ln. %v)", element.Path(), i+1)] = charData |
| 72 |
} |
| 73 |
} |
| 74 |
for k, v := range element.Attributes() { |
| 75 |
res[k] = v |
| 76 |
} |
| 77 |
case xml.Comment, xml.ProcInst, xml.Directive: |
| 78 |
|
| 79 |
} |
| 80 |
} |
| 81 |
return res |
| 82 |
} |
| 83 |
|
| 84 |
func validateXML(in string) bool { |
| 85 |
return xml.Unmarshal([]byte(in), new(interface{})) == nil |
| 86 |
} |