Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion key.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,25 @@ func (k *Key) NestedValues() []string {
return k.nestedValues
}

func hasVisitedKey(visited []*Key, k *Key) bool {
for _, v := range visited {
if v == k {
return true
}
}
return false
}

// transformValue takes a raw value and transforms to its final string.
func (k *Key) transformValue(val string) string {
return k.transformValueWithVisited(val, []*Key{k})
}

func (k *Key) transformValueWithVisited(val string, visited []*Key) string {
if len(visited) > depthValues {
return val
}

if k.s.f.ValueMapper != nil {
val = k.s.f.ValueMapper(val)
}
Expand Down Expand Up @@ -169,8 +186,16 @@ func (k *Key) transformValue(val string) string {
}
}

if hasVisitedKey(visited, nk) {
break
}

// Substitute by new value and take off leading '%(' and trailing ')s'.
val = strings.ReplaceAll(val, vr, nk.String())
res := nk.transformValueWithVisited(nk.value, append(visited, nk))
val = strings.ReplaceAll(val, vr, res)
if strings.Contains(res, vr) {
break
}
}
return val
}
Expand Down
38 changes: 38 additions & 0 deletions key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -654,4 +654,42 @@ ENDPOINT = https://%(ACCOUNT_ID)s.r2.cloudflarestorage.com

assert.Equal(t, "https://abc123.r2.cloudflarestorage.com", f.Section("").Key("ENDPOINT").String())
})

t.Run("circular reference between keys should not stack overflow", func(t *testing.T) {
f, err := Load([]byte(`
[s]
a = %(b)s
b = %(a)s
`))
require.NoError(t, err)
require.NotNil(t, f)

assert.Equal(t, "%(a)s", f.Section("s").Key("a").String())
assert.Equal(t, "%(b)s", f.Section("s").Key("b").String())
})

t.Run("self-reference in default section should not stack overflow", func(t *testing.T) {
f, err := Load([]byte(`
a = %(a)s
`))
require.NoError(t, err)
require.NotNil(t, f)

assert.Equal(t, "%(a)s", f.Section("").Key("a").String())
})

t.Run("three-way circular reference should not stack overflow", func(t *testing.T) {
f, err := Load([]byte(`
[s]
a = %(b)s
b = %(c)s
c = %(a)s
`))
require.NoError(t, err)
require.NotNil(t, f)

assert.Equal(t, "%(a)s", f.Section("s").Key("a").String())
assert.Equal(t, "%(b)s", f.Section("s").Key("b").String())
assert.Equal(t, "%(c)s", f.Section("s").Key("c").String())
})
}