Skip to content

Commit b0453b9

Browse files
fix: basic auth invalid base64 string (#2191)
* fix: basic auth returns 400 on invalid base64 string
1 parent d5f8837 commit b0453b9

File tree

2 files changed

+11
-1
lines changed

2 files changed

+11
-1
lines changed

middleware/basic_auth.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"encoding/base64"
55
"strconv"
66
"strings"
7+
"net/http"
78

89
"github.com/labstack/echo/v4"
910
)
@@ -74,10 +75,13 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
7475
l := len(basic)
7576

7677
if len(auth) > l+1 && strings.EqualFold(auth[:l], basic) {
78+
// Invalid base64 shouldn't be treated as error
79+
// instead should be treated as invalid client input
7780
b, err := base64.StdEncoding.DecodeString(auth[l+1:])
7881
if err != nil {
79-
return err
82+
return echo.NewHTTPError(http.StatusBadRequest).SetInternal(err)
8083
}
84+
8185
cred := string(b)
8286
for i := 0; i < len(cred); i++ {
8387
if cred[i] == ':' {

middleware/basic_auth_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,12 @@ func TestBasicAuth(t *testing.T) {
5858
assert.Equal(http.StatusUnauthorized, he.Code)
5959
assert.Equal(basic+` realm="someRealm"`, res.Header().Get(echo.HeaderWWWAuthenticate))
6060

61+
// Invalid base64 string
62+
auth = basic + " invalidString"
63+
req.Header.Set(echo.HeaderAuthorization, auth)
64+
he = h(c).(*echo.HTTPError)
65+
assert.Equal(http.StatusBadRequest, he.Code)
66+
6167
// Missing Authorization header
6268
req.Header.Del(echo.HeaderAuthorization)
6369
he = h(c).(*echo.HTTPError)

0 commit comments

Comments
 (0)