Skip to content

Instantly share code, notes, and snippets.

@abraithwaite
Created September 18, 2019 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abraithwaite/60a0674122710f4c152bc6f37261609f to your computer and use it in GitHub Desktop.
Save abraithwaite/60a0674122710f4c152bc6f37261609f to your computer and use it in GitHub Desktop.
package dsn
type DSN string
func (d DSN) String() string {
i := strings.Index(string(d), "&password=")
if i == -1 {
return string(d)
}
ret := []byte(d)
for i += len("&password="); i < len(d) && ret[i] != '&'; i++ {
ret[i] = '*'
}
return string(ret)
}
package dsn
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestDSN(t *testing.T) {
var tc = []struct {
Name string
Input string
Expect string
}{
{
Name: "sanity",
Input: "asdf&password=werweq",
Expect: "asdf&password=******",
},
{
Name: "middle",
Input: "asdf&password=werweq&count=4",
Expect: "asdf&password=******&count=4",
},
{
Name: "empty pw",
Input: "asdf&password=&asdf=qwer",
Expect: "asdf&password=&asdf=qwer",
},
{
Name: "start of string",
Input: "&password=werweq&count=4",
Expect: "&password=******&count=4",
},
{
Name: "only contents",
Input: "&password=werweq",
Expect: "&password=******",
},
{
Name: "empty string",
Input: "",
Expect: "",
},
{
Name: "no password",
Input: "asdf/&adfwe=werw",
Expect: "asdf/&adfwe=werw",
},
}
for _, c := range tc {
t.Run(c.Name, func(t *testing.T) {
x := DSN(c.Input)
assert.Equal(t, c.Input, string(x), "string cast should keep original")
assert.Equal(t, c.Expect, x.String(), "should obfuscate password")
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment