Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

config: allow exposing real secret value through marshal #487

Merged
merged 1 commit into from
Apr 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"trueValue" isn't a very descriptive name. How about:

Suggested change
trueValue bool
marshalSecret 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