LDAP: Interpolate env variable expressions in ldap.toml file (#20173)

* LDAP: Interpolate env variable expressions in ldap.toml file

* Removed comment
This commit is contained in:
Torkel Ödegaard 2019-11-06 21:41:21 +01:00 committed by GitHub
parent 51a0e5fdf9
commit 4ffff1a312
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 61 additions and 3 deletions

View File

@ -2,6 +2,7 @@ package ldap
import (
"fmt"
"io/ioutil"
"sync"
"github.com/BurntSushi/toml"
@ -118,7 +119,15 @@ func readConfig(configFile string) (*Config, error) {
logger.Info("LDAP enabled, reading config file", "file", configFile)
_, err := toml.DecodeFile(configFile, result)
fileBytes, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, errutil.Wrap("Failed to load LDAP config file", err)
}
// interpolate full toml string (it can contain ENV variables)
stringContent := setting.EvalEnvVarExpression(string(fileBytes))
_, err = toml.Decode(stringContent, result)
if err != nil {
return nil, errutil.Wrap("Failed to load LDAP config file", err)
}

View File

@ -0,0 +1,22 @@
package ldap
import (
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestReadingLDAPSettings(t *testing.T) {
config, err := readConfig("testdata/ldap.toml")
assert.Nil(t, err, "No error when reading ldap config")
assert.EqualValues(t, "127.0.0.1", config.Servers[0].Host)
}
func TestReadingLDAPSettingsWithEnvVariable(t *testing.T) {
os.Setenv("ENV_PASSWORD", "MySecret")
config, err := readConfig("testdata/ldap.toml")
assert.Nil(t, err, "No error when reading ldap config")
assert.EqualValues(t, "MySecret", config.Servers[0].BindPassword)
}

27
pkg/services/ldap/testdata/ldap.toml vendored Normal file
View File

@ -0,0 +1,27 @@
[[servers]]
host = "127.0.0.1"
port = 389
use_ssl = false
start_tls = false
ssl_skip_verify = false
bind_dn = "cn=admin,dc=grafana,dc=org"
bind_password = '${ENV_PASSWORD}'
search_filter = "(cn=%s)"
search_base_dns = ["dc=grafana,dc=org"]
[servers.attributes]
name = "givenName"
surname = "sn"
username = "cn"
member_of = "memberOf"
email = "email"
[[servers.group_mappings]]
group_dn = "cn=admins,ou=groups,dc=grafana,dc=org"
org_role = "Admin"
grafana_admin = true
[[servers.group_mappings]]
group_dn = "cn=users,ou=groups,dc=grafana,dc=org"
org_role = "Editor"

View File

@ -412,7 +412,7 @@ func makeAbsolute(path string, root string) string {
return filepath.Join(root, path)
}
func evalEnvVarExpression(value string) string {
func EvalEnvVarExpression(value string) string {
regex := regexp.MustCompile(`\${(\w+)}`)
return regex.ReplaceAllStringFunc(value, func(envVar string) string {
envVar = strings.TrimPrefix(envVar, "${")
@ -431,7 +431,7 @@ func evalEnvVarExpression(value string) string {
func evalConfigValues(file *ini.File) {
for _, section := range file.Sections() {
for _, key := range section.Keys() {
key.SetValue(evalEnvVarExpression(key.Value()))
key.SetValue(EvalEnvVarExpression(key.Value()))
}
}
}