From c7914bc2452b8d7e3cc343d4d0413926fb86d3de Mon Sep 17 00:00:00 2001 From: kolaente Date: Mon, 4 Nov 2024 16:47:39 +0100 Subject: [PATCH] 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 --- pkg/config/config.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/pkg/config/config.go b/pkg/config/config.go index 4f5105216..aa38a4856 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -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()) }