Skip to content

Commit

Permalink
decryptor: detect format of Secret data field
Browse files Browse the repository at this point in the history
Signed-off-by: Hidde Beydals <hello@hidde.co>
  • Loading branch information
hiddeco committed Apr 29, 2022
1 parent a7639c6 commit 83e3e33
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
16 changes: 14 additions & 2 deletions controllers/kustomization_decryptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ var (
formats.Json: []byte("\"mac\": \"ENC["),
formats.Yaml: []byte("mac: ENC["),
}
// unsupportedFormat is used to signal no sopsFormatToMarkerBytes format was
// detected by detectFormatFromMarkerBytes.
unsupportedFormat = formats.Format(-1)
)

// KustomizeDecryptor performs decryption operations for a
Expand Down Expand Up @@ -334,9 +337,9 @@ func (d *KustomizeDecryptor) DecryptResource(res *resource.Resource) (*resource.
continue
}

if bytes.Contains(data, sopsFormatToMarkerBytes[formats.Yaml]) || bytes.Contains(data, sopsFormatToMarkerBytes[formats.Json]) {
if inF := detectFormatFromMarkerBytes(data); inF != unsupportedFormat {
outF := formatForPath(key)
out, err := d.SopsDecryptWithFormat(data, formats.Yaml, outF)
out, err := d.SopsDecryptWithFormat(data, inF, outF)
if err != nil {
return nil, fmt.Errorf("failed to decrypt and format '%s/%s' Secret field '%s': %w",
res.GetNamespace(), res.GetName(), key, err)
Expand Down Expand Up @@ -740,3 +743,12 @@ func formatForPath(path string) formats.Format {
return formats.FormatForPath(path)
}
}

func detectFormatFromMarkerBytes(b []byte) formats.Format {
for k, v := range sopsFormatToMarkerBytes {
if bytes.Contains(b, v) {
return k
}
}
return unsupportedFormat
}
26 changes: 26 additions & 0 deletions controllers/kustomization_decryptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1725,3 +1725,29 @@ func Test_formatForPath(t *testing.T) {
})
}
}

func Test_detectFormatFromMarkerBytes(t *testing.T) {
tests := []struct {
name string
b []byte
want formats.Format
}{
{
name: "detects format",
b: bytes.Join([][]byte{[]byte("random other bytes"), sopsFormatToMarkerBytes[formats.Yaml], []byte("more random bytes")}, []byte(" ")),
want: formats.Yaml,
},
{
name: "returns unsupported format",
b: []byte("no marker bytes present"),
want: unsupportedFormat,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := detectFormatFromMarkerBytes(tt.b); got != tt.want {
t.Errorf("detectFormatFromMarkerBytes() = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 83e3e33

Please sign in to comment.