Skip to content

Commit de5ed88

Browse files
author
Julien
authored
Merge pull request #487 from GiedriusS/allow_exposing_real_value
config: allow exposing real secret value through marshal
2 parents ea817bb + 5ad26bf commit de5ed88

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

config/config.go

+11
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,16 @@ const secretToken = "<secret>"
2727
// Secret special type for storing secrets.
2828
type Secret string
2929

30+
// MarshalSecretValue if set to true will expose Secret type
31+
// through the marshal interfaces. Useful for outside projects
32+
// that load and marshal the Prometheus config.
33+
var MarshalSecretValue bool = false
34+
3035
// MarshalYAML implements the yaml.Marshaler interface for Secrets.
3136
func (s Secret) MarshalYAML() (interface{}, error) {
37+
if MarshalSecretValue {
38+
return string(s), nil
39+
}
3240
if s != "" {
3341
return secretToken, nil
3442
}
@@ -43,6 +51,9 @@ func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
4351

4452
// MarshalJSON implements the json.Marshaler interface for Secret.
4553
func (s Secret) MarshalJSON() ([]byte, error) {
54+
if MarshalSecretValue {
55+
return json.Marshal(string(s))
56+
}
4657
if len(s) == 0 {
4758
return json.Marshal("")
4859
}

config/config_test.go

+28-4
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,11 @@ func TestJSONMarshalSecret(t *testing.T) {
2828
S Secret
2929
}
3030
for _, tc := range []struct {
31-
desc string
32-
data tmp
33-
expected string
31+
desc string
32+
data tmp
33+
expected string
34+
trueValue bool
35+
testYAML bool
3436
}{
3537
{
3638
desc: "inhabited",
@@ -39,14 +41,36 @@ func TestJSONMarshalSecret(t *testing.T) {
3941
data: tmp{"test"},
4042
expected: "{\"S\":\"\\u003csecret\\u003e\"}",
4143
},
44+
{
45+
desc: "true value in JSON",
46+
data: tmp{"test"},
47+
expected: `{"S":"test"}`,
48+
trueValue: true,
49+
},
50+
{
51+
desc: "true value in YAML",
52+
data: tmp{"test"},
53+
expected: `s: test
54+
`,
55+
trueValue: true,
56+
testYAML: true,
57+
},
4258
{
4359
desc: "empty",
4460
data: tmp{},
4561
expected: "{\"S\":\"\"}",
4662
},
4763
} {
4864
t.Run(tc.desc, func(t *testing.T) {
49-
c, err := json.Marshal(tc.data)
65+
MarshalSecretValue = tc.trueValue
66+
67+
var marshalFN func(any) ([]byte, error)
68+
if tc.testYAML {
69+
marshalFN = yaml.Marshal
70+
} else {
71+
marshalFN = json.Marshal
72+
}
73+
c, err := marshalFN(tc.data)
5074
if err != nil {
5175
t.Fatal(err)
5276
}

0 commit comments

Comments
 (0)