|
| 1 | +package mcpgrafana |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/url" |
| 5 | + "testing" |
| 6 | + |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | +) |
| 9 | + |
| 10 | +// TestBasicAuthHeaderEncoding verifies that basicAuthHeader produces the |
| 11 | +// same bytes as (*http.Request).SetBasicAuth — base64(username ":" password) |
| 12 | +// with raw bytes per RFC 7617. Regression test for the bug where |
| 13 | +// url.Userinfo.String() was used, which percent-escapes reserved characters |
| 14 | +// per RFC 3986 and breaks Basic Auth for passwords containing ':', '@', |
| 15 | +// '/', '%', or space. |
| 16 | +func TestBasicAuthHeaderEncoding(t *testing.T) { |
| 17 | + cases := []struct { |
| 18 | + name, username, password, want string |
| 19 | + }{ |
| 20 | + { |
| 21 | + name: "plain ASCII", |
| 22 | + username: "admin", |
| 23 | + password: "password", |
| 24 | + want: "Basic YWRtaW46cGFzc3dvcmQ=", |
| 25 | + }, |
| 26 | + { |
| 27 | + name: "colon in password", |
| 28 | + username: "admin", |
| 29 | + password: "p:w0rd", |
| 30 | + want: "Basic YWRtaW46cDp3MHJk", |
| 31 | + }, |
| 32 | + { |
| 33 | + name: "at sign in password", |
| 34 | + username: "admin", |
| 35 | + password: "p@ssw0rd", |
| 36 | + want: "Basic YWRtaW46cEBzc3cwcmQ=", |
| 37 | + }, |
| 38 | + { |
| 39 | + name: "percent in password", |
| 40 | + username: "admin", |
| 41 | + password: "p%w0rd", |
| 42 | + want: "Basic YWRtaW46cCV3MHJk", |
| 43 | + }, |
| 44 | + { |
| 45 | + name: "space in password", |
| 46 | + username: "admin", |
| 47 | + password: "pw 0rd", |
| 48 | + want: "Basic YWRtaW46cHcgMHJk", |
| 49 | + }, |
| 50 | + { |
| 51 | + name: "slash in password", |
| 52 | + username: "admin", |
| 53 | + password: "p/w0rd", |
| 54 | + want: "Basic YWRtaW46cC93MHJk", |
| 55 | + }, |
| 56 | + { |
| 57 | + name: "empty password", |
| 58 | + username: "admin", |
| 59 | + password: "", |
| 60 | + want: "Basic YWRtaW46", |
| 61 | + }, |
| 62 | + } |
| 63 | + for _, tc := range cases { |
| 64 | + t.Run(tc.name, func(t *testing.T) { |
| 65 | + u := url.UserPassword(tc.username, tc.password) |
| 66 | + got := basicAuthHeader(u) |
| 67 | + assert.Equal(t, tc.want, got, |
| 68 | + "basicAuthHeader must produce raw base64(user:password) per RFC 7617, not percent-encoded userinfo") |
| 69 | + }) |
| 70 | + } |
| 71 | +} |
0 commit comments