Skip to content

Commit

Permalink
Merge pull request #487 from GiedriusS/allow_exposing_real_value
Browse files Browse the repository at this point in the history
config: allow exposing real secret value through marshal
  • Loading branch information
roidelapluie committed Apr 15, 2024
2 parents ea817bb + 5ad26bf commit de5ed88
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
11 changes: 11 additions & 0 deletions config/config.go
Expand Up @@ -27,8 +27,16 @@ const secretToken = "<secret>"
// Secret special type for storing secrets.
type Secret string

// MarshalSecretValue if set to true will expose Secret type
// through the marshal interfaces. Useful for outside projects
// that load and marshal the Prometheus config.
var MarshalSecretValue bool = false

// MarshalYAML implements the yaml.Marshaler interface for Secrets.
func (s Secret) MarshalYAML() (interface{}, error) {
if MarshalSecretValue {
return string(s), nil
}
if s != "" {
return secretToken, nil
}
Expand All @@ -43,6 +51,9 @@ func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {

// MarshalJSON implements the json.Marshaler interface for Secret.
func (s Secret) MarshalJSON() ([]byte, error) {
if MarshalSecretValue {
return json.Marshal(string(s))
}
if len(s) == 0 {
return json.Marshal("")
}
Expand Down
32 changes: 28 additions & 4 deletions config/config_test.go
Expand Up @@ -28,9 +28,11 @@ func TestJSONMarshalSecret(t *testing.T) {
S Secret
}
for _, tc := range []struct {
desc string
data tmp
expected string
desc string
data tmp
expected string
trueValue bool
testYAML bool
}{
{
desc: "inhabited",
Expand All @@ -39,14 +41,36 @@ func TestJSONMarshalSecret(t *testing.T) {
data: tmp{"test"},
expected: "{\"S\":\"\\u003csecret\\u003e\"}",
},
{
desc: "true value in JSON",
data: tmp{"test"},
expected: `{"S":"test"}`,
trueValue: true,
},
{
desc: "true value in YAML",
data: tmp{"test"},
expected: `s: test
`,
trueValue: true,
testYAML: true,
},
{
desc: "empty",
data: tmp{},
expected: "{\"S\":\"\"}",
},
} {
t.Run(tc.desc, func(t *testing.T) {
c, err := json.Marshal(tc.data)
MarshalSecretValue = tc.trueValue

var marshalFN func(any) ([]byte, error)
if tc.testYAML {
marshalFN = yaml.Marshal
} else {
marshalFN = json.Marshal
}
c, err := marshalFN(tc.data)
if err != nil {
t.Fatal(err)
}
Expand Down

0 comments on commit de5ed88

Please sign in to comment.