-
Notifications
You must be signed in to change notification settings - Fork 356
/
secure_string.go
60 lines (52 loc) · 1.4 KB
/
secure_string.go
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
package actions
import (
"fmt"
"os"
"strings"
"regexp"
)
// SecureString is a string that may be populated from an environment variable.
// If constructed with a string of the form {{ ENV.EXAMPLE_VARIABLE }}, the value is populated from EXAMPLE_VARIABLE and
// is considered a secret. Otherwise the value is taken from the string as-is, and is not considered a secret.
type SecureString struct {
val string
secret bool
}
// Returns the string for non-secrets, or asterisks otherwise.
func (s SecureString) String() string {
if s.secret {
return "*******"
}
return s.val
}
var envVarRegex = regexp.MustCompile(`{{ ?ENV\..*? ?}}`)
// NewSecureString creates a new SecureString, reading env var if needed.
func NewSecureString(s string) (SecureString, error) {
matches := 0
var err error
ret := envVarRegex.ReplaceAllStringFunc(s, func(origin string) string {
if err != nil {
return ""
}
matches++
raw := strings.Trim(origin, "{} ")
parts := strings.SplitN(raw, ".", 2) //nolint: gomnd
if len(parts) != 2 || parts[0] != "ENV" {
return origin
}
envVarName := parts[1]
val, ok := os.LookupEnv(envVarName)
if !ok {
err = fmt.Errorf("%s not found: %w", envVarName, errMissingEnvVar)
return ""
}
return val
})
if err != nil {
return SecureString{}, err
}
if matches == 0 {
return SecureString{val: s, secret: false}, nil
}
return SecureString{val: ret, secret: true}, nil
}