Created
September 18, 2019 19:58
-
-
Save abraithwaite/60a0674122710f4c152bc6f37261609f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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