summaryrefslogtreecommitdiff
path: root/internal/configuration/helpers.go
blob: 57e00fa431be8fbb3bc6b85edbdb14129a4614cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package configuration

import (
	"os"
	"strings"

	"github.com/authelia/authelia/v4/internal/utils"
)

func getEnvConfigMap(keys []string, prefix, delimiter string) (keyMap map[string]string, ignoredKeys []string) {
	keyMap = make(map[string]string)

	for _, key := range keys {
		if strings.Contains(key, delimiter) {
			keyMap[ToEnvironmentKey(key, prefix, delimiter)] = key
		}

		// Secret envs should be ignored by the env parser.
		if IsSecretKey(key) {
			ignoredKeys = append(ignoredKeys, ToEnvironmentSecretKey(key, prefix, delimiter))
		}
	}

	for _, deprecation := range deprecations {
		if !deprecation.AutoMap {
			continue
		}

		keyMap[ToEnvironmentKey(deprecation.Key, prefix, delimiter)] = deprecation.Key
	}

	return keyMap, ignoredKeys
}

func getSecretConfigMap(keys []string, prefix, delimiter string) (keyMap map[string]string) {
	keyMap = make(map[string]string)

	for _, key := range keys {
		if IsSecretKey(key) {
			originalKey := strings.ToUpper(strings.ReplaceAll(key, constDelimiter, delimiter)) + constSecretSuffix

			keyMap[prefix+originalKey] = key
		}
	}

	return keyMap
}

// ToEnvironmentKey converts a key into the environment variable name.
func ToEnvironmentKey(key, prefix, delimiter string) string {
	return prefix + strings.ToUpper(strings.ReplaceAll(key, constDelimiter, delimiter))
}

// ToEnvironmentSecretKey converts a key into the environment variable name.
func ToEnvironmentSecretKey(key, prefix, delimiter string) string {
	return prefix + strings.ToUpper(strings.ReplaceAll(key, constDelimiter, delimiter)) + constSecretSuffix
}

// IsSecretKey returns true if the provided key is a secret enabled key.
func IsSecretKey(key string) (isSecretKey bool) {
	if strings.Contains(key, "[]") {
		return false
	}

	if strings.Contains(key, ".*.") {
		return false
	}

	if utils.IsStringInSlice(key, secretExclusionExact) {
		return false
	}

	if utils.IsStringInSliceF(key, secretExclusionPrefix, strings.HasPrefix) {
		return false
	}

	return utils.IsStringInSliceF(key, secretSuffix, strings.HasSuffix)
}

func loadSecret(path string) (value string, err error) {
	content, err := os.ReadFile(path)
	if err != nil {
		return "", err
	}

	return strings.TrimRight(string(content), "\n"), err
}