Skip to content

Commit

Permalink
[Fleet] Improve error handling for invalid base64 token (#3056) (#3057)
Browse files Browse the repository at this point in the history
(cherry picked from commit 407dc9c)

Co-authored-by: Nicolas Chaulet <[email protected]>
  • Loading branch information
mergify[bot] and nchaulet authored Oct 25, 2023
1 parent 81bc850 commit 7660c8e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/pkg/apikey/apikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ type APIKey struct {
func NewAPIKeyFromToken(token string) (*APIKey, error) {
d, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return nil, err
return nil, fmt.Errorf("%w: %w", ErrInvalidToken, err)
}
if !utf8.Valid(d) {
return nil, ErrInvalidToken
Expand Down
39 changes: 39 additions & 0 deletions internal/pkg/apikey/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,42 @@ func TestMonitorLeadership(t *testing.T) {
assert.Equal(t, *apiKey, APIKey{" foo", "bar"})
assert.Equal(t, token, apiKey.Token())
}

func TestNewAPIKeyFromToken(t *testing.T) {
tests := []struct {
name string
apiKey string
expectError error
}{{
name: "Invalid base64",
apiKey: "invalidbase64",
expectError: ErrInvalidToken,
},
{
name: "malformed token",
apiKey: "dGVzdA==",
expectError: ErrMalformedToken,
},
{
name: "Invalid utf8",
apiKey: "dGVzdMlA",
expectError: ErrInvalidToken,
},
{
name: "Valid api key",
apiKey: "bURmODBZb0JrTU82QzJJaVVET1A6bmVRUnBsWEJRbmVTVFIwV3FtaVVFZw==",
expectError: nil,
}}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := NewAPIKeyFromToken(tc.apiKey)
if tc.expectError != nil {
assert.Error(t, err)
assert.ErrorIs(t, err, tc.expectError)
} else {
assert.NoError(t, err)
}
})
}
}

0 comments on commit 7660c8e

Please sign in to comment.