From e0e3b433f52c711b97710c859142dafafa88df9f Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Thu, 14 Jan 2016 14:09:27 -0800 Subject: [PATCH 1/4] WIP on migrating request parsing stuff --- parser_test.go | 33 --------------------------------- request/request.go | 30 ++++++++++++++++++++++++++++++ request/request_test.go | 34 ++++++++++++++++++++++++++++++++++ token.go | 25 ------------------------- 4 files changed, 64 insertions(+), 58 deletions(-) create mode 100644 request/request.go create mode 100644 request/request_test.go diff --git a/parser_test.go b/parser_test.go index 9115017..0d7f229 100644 --- a/parser_test.go +++ b/parser_test.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/dgrijalva/jwt-go" "io/ioutil" - "net/http" "reflect" "testing" "time" @@ -192,38 +191,6 @@ func TestParser_Parse(t *testing.T) { } } -func TestParseRequest(t *testing.T) { - // Bearer token request - for _, data := range jwtTestData { - // FIXME: custom parsers are not supported by this helper. skip tests that require them - if data.parser != nil { - t.Logf("Skipping [%v]. Custom parsers are not supported by ParseRequest", data.name) - continue - } - - if data.tokenString == "" { - data.tokenString = makeSample(data.claims) - } - - r, _ := http.NewRequest("GET", "/", nil) - r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString)) - token, err := jwt.ParseFromRequest(r, data.keyfunc) - - if token == nil { - t.Errorf("[%v] Token was not found: %v", data.name, err) - continue - } - if !reflect.DeepEqual(data.claims, token.Claims) { - t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) - } - if data.valid && err != nil { - t.Errorf("[%v] Error while verifying token: %v", data.name, err) - } - if !data.valid && err == nil { - t.Errorf("[%v] Invalid token passed validation", data.name) - } - } -} // Helper method for benchmarking various methods func benchmarkSigning(b *testing.B, method jwt.SigningMethod, key interface{}) { diff --git a/request/request.go b/request/request.go new file mode 100644 index 0000000..33fc5fb --- /dev/null +++ b/request/request.go @@ -0,0 +1,30 @@ +package request + +import ( + "github.com/dgrijalva/jwt-go" + "strings" + "net/http" +) + +// Try to find the token in an http.Request. +// This method will call ParseMultipartForm if there's no token in the header. +// Currently, it looks in the Authorization header as well as +// looking for an 'access_token' request parameter in req.Form. +func ParseFromRequest(req *http.Request, keyFunc jwt.Keyfunc) (token *jwt.Token, err error) { + + // Look for an Authorization header + if ah := req.Header.Get("Authorization"); ah != "" { + // Should be a bearer token + if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" { + return jwt.Parse(ah[7:], keyFunc) + } + } + + // Look for "access_token" parameter + req.ParseMultipartForm(10e6) + if tokStr := req.Form.Get("access_token"); tokStr != "" { + return jwt.Parse(tokStr, keyFunc) + } + + return nil, jwt.ErrNoTokenInRequest +} diff --git a/request/request_test.go b/request/request_test.go new file mode 100644 index 0000000..6e6ff6c --- /dev/null +++ b/request/request_test.go @@ -0,0 +1,34 @@ +package request + +// func TestParseRequest(t *testing.T) { +// // Bearer token request +// for _, data := range jwtTestData { +// // FIXME: custom parsers are not supported by this helper. skip tests that require them +// if data.parser != nil { +// t.Logf("Skipping [%v]. Custom parsers are not supported by ParseRequest", data.name) +// continue +// } +// +// if data.tokenString == "" { +// data.tokenString = makeSample(data.claims) +// } +// +// r, _ := http.NewRequest("GET", "/", nil) +// r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString)) +// token, err := jwt.ParseFromRequest(r, data.keyfunc) +// +// if token == nil { +// t.Errorf("[%v] Token was not found: %v", data.name, err) +// continue +// } +// if !reflect.DeepEqual(data.claims, token.Claims) { +// t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) +// } +// if data.valid && err != nil { +// t.Errorf("[%v] Error while verifying token: %v", data.name, err) +// } +// if !data.valid && err == nil { +// t.Errorf("[%v] Invalid token passed validation", data.name) +// } +// } +// } diff --git a/token.go b/token.go index d35aaa4..9cd59bf 100644 --- a/token.go +++ b/token.go @@ -3,7 +3,6 @@ package jwt import ( "encoding/base64" "encoding/json" - "net/http" "strings" "time" ) @@ -87,30 +86,6 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { return new(Parser).Parse(tokenString, keyFunc) } -// Try to find the token in an http.Request. -// This method will call ParseMultipartForm if there's no token in the header. -// Currently, it looks in the Authorization header as well as -// looking for an 'access_token' request parameter in req.Form. -func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) { - - // Look for an Authorization header - if ah := req.Header.Get("Authorization"); ah != "" { - // Should be a bearer token - if len(ah) > 6 && strings.ToUpper(ah[0:6]) == "BEARER" { - return Parse(ah[7:], keyFunc) - } - } - - // Look for "access_token" parameter - req.ParseMultipartForm(10e6) - if tokStr := req.Form.Get("access_token"); tokStr != "" { - return Parse(tokStr, keyFunc) - } - - return nil, ErrNoTokenInRequest - -} - // Encode JWT specific base64url encoding with padding stripped func EncodeSegment(seg []byte) string { return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") From e3cd52238a5f930e5ed1dd453153b6a403f92ca4 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Fri, 8 Apr 2016 13:01:55 -0700 Subject: [PATCH 2/4] moved some of the test helpers into a shared location so they can be reused --- parser_test.go | 40 ++++++++-------------------------------- test/helpers.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 32 deletions(-) create mode 100644 test/helpers.go diff --git a/parser_test.go b/parser_test.go index 58efa37..11cc82c 100644 --- a/parser_test.go +++ b/parser_test.go @@ -4,12 +4,12 @@ import ( "crypto/rsa" "encoding/json" "fmt" - "io/ioutil" "reflect" "testing" "time" "github.com/dgrijalva/jwt-go" + "github.com/dgrijalva/jwt-go/test" ) var ( @@ -20,6 +20,10 @@ var ( nilKeyFunc jwt.Keyfunc = nil ) +func init() { + jwtTestDefaultKey = test.LoadRSAPublicKeyFromDisk("test/sample_key.pub") +} + var jwtTestData = []struct { name string tokenString string @@ -130,40 +134,12 @@ var jwtTestData = []struct { }, } -func init() { - if keyData, e := ioutil.ReadFile("test/sample_key.pub"); e == nil { - if jwtTestDefaultKey, e = jwt.ParseRSAPublicKeyFromPEM(keyData); e != nil { - panic(e) - } - } else { - panic(e) - } -} - -func makeSample(c jwt.MapClaims) string { - keyData, e := ioutil.ReadFile("test/sample_key") - if e != nil { - panic(e.Error()) - } - key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) - if e != nil { - panic(e.Error()) - } - - token := jwt.NewWithClaims(jwt.SigningMethodRS256, c) - s, e := token.SignedString(key) - - if e != nil { - panic(e.Error()) - } - - return s -} - func TestParser_Parse(t *testing.T) { + privateKey := test.LoadRSAPrivateKeyFromDisk("test/sample_key") + for _, data := range jwtTestData { if data.tokenString == "" { - data.tokenString = makeSample(data.claims) + data.tokenString = test.MakeSampleToken(data.claims, privateKey) } var token *jwt.Token diff --git a/test/helpers.go b/test/helpers.go new file mode 100644 index 0000000..39b5208 --- /dev/null +++ b/test/helpers.go @@ -0,0 +1,42 @@ +package test + +import ( + "crypto/rsa" + "github.com/dgrijalva/jwt-go" + "io/ioutil" +) + +func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey { + keyData, e := ioutil.ReadFile(location) + if e != nil { + panic(e.Error()) + } + key, e := jwt.ParseRSAPrivateKeyFromPEM(keyData) + if e != nil { + panic(e.Error()) + } + return key +} + +func LoadRSAPublicKeyFromDisk(location string) *rsa.PublicKey { + keyData, e := ioutil.ReadFile(location) + if e != nil { + panic(e.Error()) + } + key, e := jwt.ParseRSAPublicKeyFromPEM(keyData) + if e != nil { + panic(e.Error()) + } + return key +} + +func MakeSampleToken(c jwt.MapClaims, key interface{}) string { + token := jwt.NewWithClaims(jwt.SigningMethodRS256, c) + s, e := token.SignedString(key) + + if e != nil { + panic(e.Error()) + } + + return s +} From 288cee4336ae43c0f95d491a273714a261c4c319 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Fri, 8 Apr 2016 13:02:18 -0700 Subject: [PATCH 3/4] added a couple tests for request parsing that don't rely on giant parser test dataset --- request/request_test.go | 122 +++++++++++++++++++++++++++------------- 1 file changed, 82 insertions(+), 40 deletions(-) diff --git a/request/request_test.go b/request/request_test.go index 311f8e9..8306912 100644 --- a/request/request_test.go +++ b/request/request_test.go @@ -1,42 +1,84 @@ package request -// import ( -// "fmt" -// "github.com/dgrijalva/jwt-go" -// "net/http" -// "reflect" -// "testing" -// ) -// -// func TestParseRequest(t *testing.T) { -// // Bearer token request -// for _, data := range jwtTestData { -// // FIXME: custom parsers are not supported by this helper. skip tests that require them -// if data.parser != nil { -// t.Logf("Skipping [%v]. Custom parsers are not supported by ParseRequest", data.name) -// continue -// } -// -// if data.tokenString == "" { -// data.tokenString = makeSample(data.claims) -// } -// -// r, _ := http.NewRequest("GET", "/", nil) -// r.Header.Set("Authorization", fmt.Sprintf("Bearer %v", data.tokenString)) -// token, err := ParseFromRequestWithClaims(r, data.keyfunc, &jwt.MapClaims{}) -// -// if token == nil { -// t.Errorf("[%v] Token was not found: %v", data.name, err) -// continue -// } -// if !reflect.DeepEqual(&data.claims, token.Claims) { -// t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) -// } -// if data.valid && err != nil { -// t.Errorf("[%v] Error while verifying token: %v", data.name, err) -// } -// if !data.valid && err == nil { -// t.Errorf("[%v] Invalid token passed validation", data.name) -// } -// } -// } +import ( + "fmt" + "github.com/dgrijalva/jwt-go" + "github.com/dgrijalva/jwt-go/test" + "net/http" + "net/url" + "reflect" + "strings" + "testing" +) + +var requestTestData = []struct { + name string + claims jwt.MapClaims + headers map[string]string + query url.Values + valid bool +}{ + { + "oauth bearer token - header", + jwt.MapClaims{"foo": "bar"}, + map[string]string{"Authorization": "Bearer %v"}, + url.Values{}, + true, + }, + { + "oauth bearer token - url", + jwt.MapClaims{"foo": "bar"}, + map[string]string{}, + url.Values{"access_token": {"%v"}}, + true, + }, +} + +func TestParseRequest(t *testing.T) { + // load keys from disk + privateKey := test.LoadRSAPrivateKeyFromDisk("../test/sample_key") + publicKey := test.LoadRSAPublicKeyFromDisk("../test/sample_key.pub") + keyfunc := func(*jwt.Token) (interface{}, error) { + return publicKey, nil + } + + // Bearer token request + for _, data := range requestTestData { + // Make token from claims + tokenString := test.MakeSampleToken(data.claims, privateKey) + + // Make query string + for k, vv := range data.query { + for i, v := range vv { + if strings.Contains(v, "%v") { + data.query[k][i] = fmt.Sprintf(v, tokenString) + } + } + } + + // Make request from test struct + r, _ := http.NewRequest("GET", fmt.Sprintf("/?%v", data.query.Encode()), nil) + for k, v := range data.headers { + if strings.Contains(v, "%v") { + r.Header.Set(k, fmt.Sprintf(v, tokenString)) + } else { + r.Header.Set(k, tokenString) + } + } + token, err := ParseFromRequestWithClaims(r, keyfunc, &jwt.MapClaims{}) + + if token == nil { + t.Errorf("[%v] Token was not found: %v", data.name, err) + continue + } + if !reflect.DeepEqual(&data.claims, token.Claims) { + t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) + } + if data.valid && err != nil { + t.Errorf("[%v] Error while verifying token: %v", data.name, err) + } + if !data.valid && err == nil { + t.Errorf("[%v] Invalid token passed validation", data.name) + } + } +} From 070a4bdd003267a775ae94172aeb3fba45f1b309 Mon Sep 17 00:00:00 2001 From: Dave Grijalva Date: Fri, 8 Apr 2016 13:58:29 -0700 Subject: [PATCH 4/4] moved request related error int request subpackage --- errors.go | 5 ++--- request/request.go | 8 +++++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/errors.go b/errors.go index b055f3b..6a60e91 100644 --- a/errors.go +++ b/errors.go @@ -6,9 +6,8 @@ import ( // Error constants var ( - ErrInvalidKey = errors.New("key is invalid or of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - ErrNoTokenInRequest = errors.New("no token present in request") + ErrInvalidKey = errors.New("key is invalid or of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") ) // The errors that might occur when parsing and validating a token diff --git a/request/request.go b/request/request.go index c1ba852..c812488 100644 --- a/request/request.go +++ b/request/request.go @@ -1,11 +1,17 @@ package request import ( + "errors" "github.com/dgrijalva/jwt-go" "net/http" "strings" ) +// Errors +var ( + ErrNoTokenInRequest = errors.New("no token present in request") +) + // Try to find the token in an http.Request. // This method will call ParseMultipartForm if there's no token in the header. // Currently, it looks in the Authorization header as well as @@ -29,5 +35,5 @@ func ParseFromRequestWithClaims(req *http.Request, keyFunc jwt.Keyfunc, claims j return jwt.ParseWithClaims(tokStr, keyFunc, claims) } - return nil, jwt.ErrNoTokenInRequest + return nil, ErrNoTokenInRequest }