Skip to content

Commit

Permalink
fix multiple secret ref replace (#3206) (#3207)
Browse files Browse the repository at this point in the history
(cherry picked from commit 339e0dc)

Co-authored-by: Julia Bardi <[email protected]>
  • Loading branch information
mergify[bot] and juliaElastic authored Jan 5, 2024
1 parent 5e328bd commit 174e548
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
10 changes: 7 additions & 3 deletions internal/pkg/policy/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
)

var (
secretRegex = regexp.MustCompile(`\$co\.elastic\.secret{(.*)}`)
secretRegex = regexp.MustCompile(`\$co\.elastic\.secret{([^}]*)}`)
)

// read secret values that belong to the agent policy's secret references, returns secrets as id:value map
Expand Down Expand Up @@ -177,13 +177,17 @@ func ProcessOutputSecret(ctx context.Context, output smap.Map, bulker bulk.Bulk)
}

// replaceStringRef replaces values matching a secret ref regex, e.g. $co.elastic.secret{<secret ref>} -> <secret value>
// and does this for multiple matches
func replaceStringRef(ref string, secretValues map[string]string) string {
matches := secretRegex.FindStringSubmatch(ref)
if len(matches) > 1 {
for len(matches) > 1 {
secretRef := matches[1]
if val, ok := secretValues[secretRef]; ok {
return strings.Replace(ref, matches[0], val, 1)
ref = strings.Replace(ref, matches[0], val, 1)
matches = secretRegex.FindStringSubmatch(ref)
continue
}
break
}
return ref
}
17 changes: 17 additions & 0 deletions internal/pkg/policy/secret_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ func TestReplaceStringRefPartial2(t *testing.T) {
assert.Equal(t, "http://localhost/services", val)
}

func TestReplaceStringRefMultiple(t *testing.T) {
secretRefs := map[string]string{
"secret1": "value1",
"secret2": "value2",
}
val := replaceStringRef("partial \"$co.elastic.secret{secret1}\" \"$co.elastic.secret{secret2}\"", secretRefs)
assert.Equal(t, "partial \"value1\" \"value2\"", val)
}

func TestReplaceStringRefMultipleOneNotFound(t *testing.T) {
secretRefs := map[string]string{
"secret2": "value2",
}
val := replaceStringRef("partial \"$co.elastic.secret{secret1}\" \"$co.elastic.secret{secret2}\"", secretRefs)
assert.Equal(t, "partial \"$co.elastic.secret{secret1}\" \"$co.elastic.secret{secret2}\"", val)
}

func TestReplaceStringRefNotASecret(t *testing.T) {
secretRefs := map[string]string{
"abcd": "value1",
Expand Down

0 comments on commit 174e548

Please sign in to comment.