From 14ac6afd4fbd36e8546c222c3f3389ebf6b89cd3 Mon Sep 17 00:00:00 2001 From: Oleg Kovalov Date: Tue, 7 Nov 2023 13:56:18 +0100 Subject: [PATCH] Validate JWT header field (#144) --- errors.go | 3 +++ parse.go | 3 +++ parse_test.go | 12 +++++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/errors.go b/errors.go index 0755091..c032d13 100644 --- a/errors.go +++ b/errors.go @@ -13,6 +13,9 @@ var ( // ErrUnsupportedAlg indicates that given algorithm is not supported. ErrUnsupportedAlg = errors.New("algorithm is not supported") + // ErrNotJWTType indicates that JWT token type is not JWT. + ErrNotJWTType = errors.New("token of not JWT type") + // ErrInvalidFormat indicates that token format is not valid. ErrInvalidFormat = errors.New("token format is not valid") diff --git a/parse.go b/parse.go index cc5f29a..fa575aa 100644 --- a/parse.go +++ b/parse.go @@ -77,6 +77,9 @@ func parse(token []byte) (*Token, error) { header: header, claims: claims, } + if !constTimeEqual(tk.header.Type, "JWT") { + return nil, ErrNotJWTType + } return tk, nil } diff --git a/parse_test.go b/parse_test.go index b9c4d87..d3017c3 100644 --- a/parse_test.go +++ b/parse_test.go @@ -67,6 +67,16 @@ func TestParseAnotherAlgorithm(t *testing.T) { } } +func TestParseWrongType(t *testing.T) { + tokenHS256 := `eyJhbGciOiJIUzI1NiIsInR5cCI6IkJPTUJPTSJ9.eyJqdGkiOiJqdXN0IGFuIGlkIiwiYXVkIjoiYXVkaWVuY2UifQ.t5oEdZGp0Qbth7lo5fZlV_o4-r9gMoYBSktXbarjWoo` + verifier := mustVerifier(NewVerifierHS(HS256, []byte("key"))) + + _, err := Parse([]byte(tokenHS256), verifier) + if err == nil { + t.Fatal() + } +} + func TestParseMalformed(t *testing.T) { f := func(got string) { t.Helper() @@ -81,7 +91,7 @@ func TestParseMalformed(t *testing.T) { f(`eyJ.xyz`) f(`eyJ!.x!yz.e30`) f(`eyJ.xyz.xyz`) - f(`eyJhIjoxMjN9.x!yz.e30`) // `e30` is JSON `{}` in base64 + f(`eyJhIjoxMjN9.x!yz.e30`) // `e30` is JSON `{}` in base64. f(`eyJhIjoxMjN9.e30.x!yz`) }