feat: load any config value from file

This change allows to read any config value from a file, when the path to that file is specified in the config with the target config value suffixed with _file. This works with environment variables as well.
For example, setting database.password_file=/path/to/password will load the value from /path/to/password and set it as the config value of database.password.

Resolves https://kolaente.dev/vikunja/vikunja/issues/704
Resolves https://kolaente.dev/vikunja/vikunja/pulls/1621
This commit is contained in:
kolaente
2024-11-04 16:47:39 +01:00
parent 4556cfb057
commit c7914bc245

View File

@@ -421,6 +421,44 @@ func InitDefaultConfig() {
AutoTLSRenewBefore.setDefault("720h") // 30days in hours
}
func getConfigValueFromFile(configKey string) string {
var valuePath = viper.GetString(configKey)
if valuePath == "" {
return ""
}
if !strings.HasPrefix(valuePath, "/") {
valuePath = path.Join(ServiceRootpath.GetString(), valuePath)
}
contents, err := os.ReadFile(valuePath)
if err == nil {
return string(contents)
}
log.Fatalf("Failed to read the config file at %s for key %s: %v", valuePath, configKey, err)
return ""
}
func readConfigvaluesFromFiles() {
keys := viper.AllKeys()
for _, key := range keys {
if strings.HasSuffix(key, "_file") {
value := getConfigValueFromFile(key)
if value != "" {
viper.Set(strings.TrimSuffix(key, "_file"), value)
}
continue
}
// Env is evaluated manually at runtime, so we need to check this for each key
value := getConfigValueFromFile(key + ".file")
if value != "" {
viper.Set(strings.TrimSuffix(key, ".file"), value)
}
}
}
// InitConfig initializes the config, sets defaults etc.
func InitConfig() {
@@ -465,6 +503,8 @@ func InitConfig() {
log.Info("No config file found, using default or config from environment variables.")
}
readConfigvaluesFromFiles()
if RateLimitStore.GetString() == "keyvalue" {
RateLimitStore.Set(KeyvalueType.GetString())
}