From 4fd5621d8dd04170aebf0b0f871ce6b64020d102 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Sun, 19 Feb 2023 14:01:18 +0100 Subject: [PATCH 01/14] Added GitHub Actions Markdown (#260) --- .github/workflows/build.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cea5f110..eaf77c4f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,5 +46,6 @@ jobs: run: | go install github.com/mfridman/tparse@latest go vet ./... - go test -v -race -count=1 -json -coverpkg=$(go list ./...) ./... | tparse -follow -notests + go test -v -race -count=1 -json -coverpkg=$(go list ./...) ./... | tee output.json | tparse -follow -notests || true + tparse -format markdown -file output.json -all > $GITHUB_STEP_SUMMARY go build ./... From 148d71010923ca691c950db9846191800f498f8d Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Tue, 21 Feb 2023 14:32:25 +0100 Subject: [PATCH 02/14] `v5` Pre-Release (#234) Co-authored-by: Micah Parks <66095735+MicahParks@users.noreply.github.com> Co-authored-by: Michael Fridman --- .github/workflows/build.yml | 2 +- MIGRATION_GUIDE.md | 84 +++++++++- README.md | 28 ++-- VERSION_HISTORY.md | 16 +- claims.go | 277 ++------------------------------- cmd/jwt/README.md | 2 +- cmd/jwt/main.go | 2 +- ecdsa_test.go | 2 +- ed25519_test.go | 2 +- errors.go | 127 ++++----------- errors_go1_20.go | 47 ++++++ errors_go_other.go | 78 ++++++++++ errors_test.go | 95 ++++++++++++ example_test.go | 64 +++++++- go.mod | 8 +- hmac_example_test.go | 2 +- hmac_test.go | 2 +- http_example_test.go | 4 +- map_claims.go | 184 +++++++++------------- map_claims_test.go | 114 +++++++++++--- none.go | 7 +- none_test.go | 2 +- parser.go | 89 +++++------ parser_option.go | 94 +++++++++-- parser_test.go | 166 ++++++++++---------- registered_claims.go | 63 ++++++++ request/request.go | 2 +- request/request_test.go | 4 +- rsa_pss_test.go | 4 +- rsa_test.go | 2 +- test/helpers.go | 2 +- token.go | 92 +++++------ token_test.go | 6 +- types.go | 43 +++--- types_test.go | 2 +- validator.go | 301 ++++++++++++++++++++++++++++++++++++ validator_test.go | 261 +++++++++++++++++++++++++++++++ 37 files changed, 1513 insertions(+), 767 deletions(-) create mode 100644 errors_go1_20.go create mode 100644 errors_go_other.go create mode 100644 errors_test.go create mode 100644 registered_claims.go create mode 100644 validator.go create mode 100644 validator_test.go diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index eaf77c4f..efef789e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -25,7 +25,7 @@ jobs: strategy: fail-fast: false matrix: - go: [1.17, 1.18, 1.19] + go: ["1.18", "1.19", "1.20"] steps: - name: Checkout uses: actions/checkout@v3 diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 32966f59..1ee690f9 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -1,4 +1,82 @@ -## Migration Guide (v4.0.0) +# Migration Guide (v5.0.0) + +Version `v5` contains a major rework of core functionalities in the `jwt-go` library. This includes support for several +validation options as well as a re-design of the `Claims` interface. Lastly, we reworked how errors work under the hood, +which should provide a better overall developer experience. + +Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), the import path will be: + + "github.com/golang-jwt/jwt/v5" + +For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of +the public API, existing programs might need to be adopted. The following paragraphs go through the individual changes +and make suggestions how to change existing programs. + +## Parsing and Validation Options + +Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option +to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended +to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: + * `WithLeeway`, which can be used to specific leeway that is taken into account when validating time-based claims, such as `exp` or `nbf`. + * The new default behavior now disables checking the `iat` claim by default. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. + * New options have also been added to check for expected `aud`, `sub` and `iss`, namely `WithAudience`, `WithSubject` and `WithIssuer`. + +## Changes to the `Claims` interface + +### Complete Restructuring + +Previously, the claims interface was satisfied with an implementation of a `Valid() error` function. This had several issues: + * The different claim types (struct claims, map claims, etc.) then contained similar (but not 100 % identical) code of how this validation was done. This lead to a lot of (almost) duplicate code and was hard to maintain + * It was not really semantically close to what a "claim" (or a set of claims) really is; which is a list of defined key/value pairs with a certain semantic meaning. + +Since all the validation functionality is now extracted into the validator, all `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. Instead, the interface now represents a list of getters to retrieve values with a specific meaning. This allows us to completely decouple the validation logic with the underlying storage representation of the claim, which could be a struct, a map or even something stored in a database. + +```go +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} +``` + +### Supported Claim Types and Removal of `StandardClaims` + +The two standard claim types supported by this library, `MapClaims` and `RegisteredClaims` both implement the necessary functions of this interface. The old `StandardClaims` struct, which has already been deprecated in `v4` is now removed. + +Users using custom claims, in most cases, will not experience any changes in the behavior as long as they embedded +`RegisteredClaims`. If they created a new claim type from scratch, they now need to implemented the proper getter +functions. + +### Migrating Application Specific Logic of the old `Valid` + +Previously, users could override the `Valid` method in a custom claim, for example to extend the validation with application-specific claims. However, this was always very dangerous, since once could easily disable the standard validation and signature checking. + +In order to avoid that, while still supporting the use-case, a new `ClaimsValidator` interface has been introduced. This interface consists of the `Validate() error` function. If the validator sees, that a `Claims` struct implements this interface, the errors returned to the `Validate` function will be *appended* to the regular standard validation. It is not possible to disable the standard validation anymore (even only by accident). + +Usage examples can be found in [example_test.go](./example_test.go), to build claims structs like the following. + +```go +// MyCustomClaims includes all registered claims, plus Foo. +type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims +} + +// Validate can be used to execute additional application-specific claims +// validation. +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return errors.New("must be foobar") + } + + return nil +} +``` + +# Migration Guide (v4.0.0) Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: @@ -8,7 +86,7 @@ The `/v4` version will be backwards compatible with existing `v3.x.y` tags in th `github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having troubles migrating, please open an issue. -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually or by using tools such as `sed` or `gofmt`. +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually or by using tools such as `sed` or `gofmt`. And then you'd typically run: @@ -17,6 +95,6 @@ go get github.com/golang-jwt/jwt/v4 go mod tidy ``` -## Older releases (before v3.2.0) +# Older releases (before v3.2.0) The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/README.md b/README.md index 30f2f2a6..87259e84 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ # jwt-go [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v4.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) +[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) this project adds Go module support, but maintains backwards compatibility with older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. -See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. +See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version v5.0.0 introduces major improvements to the validation of tokens, but is not entirely backwards compatible. > After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. @@ -41,22 +41,22 @@ This library supports the parsing and verification as well as the generation and 1. To install the jwt package, you first need to have [Go](https://go.dev/doc/install) installed, then you can use the command below to add `jwt-go` as a dependency in your Go program. ```sh -go get -u github.com/golang-jwt/jwt/v4 +go get -u github.com/golang-jwt/jwt/v5 ``` 2. Import it in your code: ```go -import "github.com/golang-jwt/jwt/v4" +import "github.com/golang-jwt/jwt/v5" ``` ## Examples -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) for examples of usage: +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) for examples of usage: -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#pkg-examples) +* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) +* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) +* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) ## Extensions @@ -68,7 +68,7 @@ A common use case would be integrating with different 3rd party signature provid | --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | | AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | *Disclaimer*: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers @@ -110,10 +110,10 @@ Asymmetric signing methods, such as RSA, use different keys for signing and veri Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation -* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation +* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation +* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation ### JWT and OAuth @@ -131,7 +131,7 @@ This library uses descriptive error messages whenever possible. If you are not g ## More -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v4). +Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/VERSION_HISTORY.md b/VERSION_HISTORY.md index afbfc4e4..b5039e49 100644 --- a/VERSION_HISTORY.md +++ b/VERSION_HISTORY.md @@ -1,17 +1,19 @@ -## `jwt-go` Version History +# `jwt-go` Version History -#### 4.0.0 +The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. + +## 4.0.0 * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. -#### 3.2.2 +## 3.2.2 * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). -#### 3.2.1 +## 3.2.1 * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` @@ -117,17 +119,17 @@ It is likely the only integration change required here will be to change `func(t * Refactored the RSA implementation to be easier to read * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` -#### 1.0.2 +## 1.0.2 * Fixed bug in parsing public keys from certificates * Added more tests around the parsing of keys for RS256 * Code refactoring in RS256 implementation. No functional changes -#### 1.0.1 +## 1.0.1 * Fixed panic if RS256 signing method was passed an invalid key -#### 1.0.0 +## 1.0.0 * First versioned release * API stabilized diff --git a/claims.go b/claims.go index 364cec87..d50ff3da 100644 --- a/claims.go +++ b/claims.go @@ -1,269 +1,16 @@ package jwt -import ( - "crypto/subtle" - "fmt" - "time" -) - -// Claims must just have a Valid method that determines -// if the token is invalid for any supported reason +// Claims represent any form of a JWT Claims Set according to +// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a +// common basis for validation, it is required that an implementation is able to +// supply at least the claim names provided in +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, +// `iat`, `nbf`, `iss`, `sub` and `aud`. type Claims interface { - Valid() error -} - -// RegisteredClaims are a structured version of the JWT Claims Set, -// restricted to Registered Claim Names, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 -// -// This type can be used on its own, but then additional private and -// public claims embedded in the JWT will not be parsed. The typical usecase -// therefore is to embedded this in a user-defined claim type. -// -// See examples for how to use this with your own claim types. -type RegisteredClaims struct { - // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 - Issuer string `json:"iss,omitempty"` - - // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 - Subject string `json:"sub,omitempty"` - - // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 - Audience ClaimStrings `json:"aud,omitempty"` - - // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 - ExpiresAt *NumericDate `json:"exp,omitempty"` - - // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 - NotBefore *NumericDate `json:"nbf,omitempty"` - - // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 - IssuedAt *NumericDate `json:"iat,omitempty"` - - // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 - ID string `json:"jti,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c RegisteredClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := now.Sub(c.ExpiresAt.Time) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool { - if c.ExpiresAt == nil { - return verifyExp(nil, cmp, req) - } - - return verifyExp(&c.ExpiresAt.Time, cmp, req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool { - if c.IssuedAt == nil { - return verifyIat(nil, cmp, req) - } - - return verifyIat(&c.IssuedAt.Time, cmp, req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool { - if c.NotBefore == nil { - return verifyNbf(nil, cmp, req) - } - - return verifyNbf(&c.NotBefore.Time, cmp, req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// StandardClaims are a structured version of the JWT Claims Set, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the -// specification exactly, since they were based on an earlier draft of the -// specification and not updated. The main difference is that they only -// support integer-based date fields and singular audiences. This might lead to -// incompatibilities with other JWT implementations. The use of this is discouraged, instead -// the newer RegisteredClaims struct should be used. -// -// Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct. -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud([]string{c.Audience}, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - if c.ExpiresAt == 0 { - return verifyExp(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.ExpiresAt, 0) - return verifyExp(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - if c.IssuedAt == 0 { - return verifyIat(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.IssuedAt, 0) - return verifyIat(&t, time.Unix(cmp, 0), req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - if c.NotBefore == 0 { - return verifyNbf(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.NotBefore, 0) - return verifyNbf(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// ----- helpers - -func verifyAud(aud []string, cmp string, required bool) bool { - if len(aud) == 0 { - return !required - } - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if len(stringClaims) == 0 { - return !required - } - - return result -} - -func verifyExp(exp *time.Time, now time.Time, required bool) bool { - if exp == nil { - return !required - } - return now.Before(*exp) -} - -func verifyIat(iat *time.Time, now time.Time, required bool) bool { - if iat == nil { - return !required - } - return now.After(*iat) || now.Equal(*iat) -} - -func verifyNbf(nbf *time.Time, now time.Time, required bool) bool { - if nbf == nil { - return !required - } - return now.After(*nbf) || now.Equal(*nbf) -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - return subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) } diff --git a/cmd/jwt/README.md b/cmd/jwt/README.md index 4388e5f9..bb02c50e 100644 --- a/cmd/jwt/README.md +++ b/cmd/jwt/README.md @@ -16,4 +16,4 @@ To simply display a token, use: You can install this tool with the following command: - go install github.com/golang-jwt/jwt/v4/cmd/jwt \ No newline at end of file + go install github.com/golang-jwt/jwt/v5/cmd/jwt \ No newline at end of file diff --git a/cmd/jwt/main.go b/cmd/jwt/main.go index 2ca6488d..f1e49a90 100644 --- a/cmd/jwt/main.go +++ b/cmd/jwt/main.go @@ -17,7 +17,7 @@ import ( "sort" "strings" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var ( diff --git a/ecdsa_test.go b/ecdsa_test.go index a3e15f18..7c6d4829 100644 --- a/ecdsa_test.go +++ b/ecdsa_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var ecdsaTestData = []struct { diff --git a/ed25519_test.go b/ed25519_test.go index 533bed30..cd058183 100644 --- a/ed25519_test.go +++ b/ed25519_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var ed25519TestData = []struct { diff --git a/errors.go b/errors.go index 10ac8835..23bb616d 100644 --- a/errors.go +++ b/errors.go @@ -2,111 +2,48 @@ package jwt import ( "errors" + "strings" ) -// Error constants var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") - - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + ErrTokenMalformed = errors.New("token is malformed") + ErrTokenUnverifiable = errors.New("token is unverifiable") + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") + ErrTokenInvalidAudience = errors.New("token has invalid audience") + ErrTokenExpired = errors.New("token is expired") + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + ErrTokenInvalidSubject = errors.New("token has invalid subject") + ErrTokenNotValidYet = errors.New("token is not valid yet") + ErrTokenInvalidId = errors.New("token has invalid id") + ErrTokenInvalidClaims = errors.New("token has invalid claims") + ErrInvalidType = errors.New("invalid type for claim") ) -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// NewValidationError is a helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// ValidationError represents an error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text +// joinedError is an error type that works similar to what [errors.Join] +// produces, with the exception that it has a nice error string; mainly its +// error messages are concatenated using a comma, rather than a newline. +type joinedError struct { + errs []error } -// Error is the implementation of the err interface. -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" +func (je joinedError) Error() string { + msg := []string{} + for _, err := range je.errs { + msg = append(msg, err.Error()) } -} - -// Unwrap gives errors.Is and errors.As access to the inner error. -func (e *ValidationError) Unwrap() error { - return e.Inner -} -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 + return strings.Join(msg, ", ") } -// Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message -// by comparing the inner error message. If that fails, we compare using the error flags. This way we can use -// custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables. -func (e *ValidationError) Is(err error) bool { - // Check, if our inner error is a direct match - if errors.Is(errors.Unwrap(e), err) { - return true +// joinErrors joins together multiple errors. Useful for scenarios where +// multiple errors next to each other occur, e.g., in claims validation. +func joinErrors(errs ...error) error { + return &joinedError{ + errs: errs, } - - // Otherwise, we need to match using our error flags - switch err { - case ErrTokenMalformed: - return e.Errors&ValidationErrorMalformed != 0 - case ErrTokenUnverifiable: - return e.Errors&ValidationErrorUnverifiable != 0 - case ErrTokenSignatureInvalid: - return e.Errors&ValidationErrorSignatureInvalid != 0 - case ErrTokenInvalidAudience: - return e.Errors&ValidationErrorAudience != 0 - case ErrTokenExpired: - return e.Errors&ValidationErrorExpired != 0 - case ErrTokenUsedBeforeIssued: - return e.Errors&ValidationErrorIssuedAt != 0 - case ErrTokenInvalidIssuer: - return e.Errors&ValidationErrorIssuer != 0 - case ErrTokenNotValidYet: - return e.Errors&ValidationErrorNotValidYet != 0 - case ErrTokenInvalidId: - return e.Errors&ValidationErrorId != 0 - case ErrTokenInvalidClaims: - return e.Errors&ValidationErrorClaimsInvalid != 0 - } - - return false } diff --git a/errors_go1_20.go b/errors_go1_20.go new file mode 100644 index 00000000..a893d355 --- /dev/null +++ b/errors_go1_20.go @@ -0,0 +1,47 @@ +//go:build go1.20 +// +build go1.20 + +package jwt + +import ( + "fmt" +) + +// Unwrap implements the multiple error unwrapping for this error type, which is +// possible in Go 1.20. +func (je joinedError) Unwrap() []error { + return je.errs +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. This makes use of Go 1.20's possibility to +// include more than one %w formatting directive in [fmt.Errorf]. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + var format string + var args []any + if message != "" { + format = "%w: %s" + args = []any{err, message} + } else { + format = "%w" + args = []any{err} + } + + for _, e := range more { + format += ": %w" + args = append(args, e) + } + + err = fmt.Errorf(format, args...) + return err +} diff --git a/errors_go_other.go b/errors_go_other.go new file mode 100644 index 00000000..3afb04e6 --- /dev/null +++ b/errors_go_other.go @@ -0,0 +1,78 @@ +//go:build !go1.20 +// +build !go1.20 + +package jwt + +import ( + "errors" + "fmt" +) + +// Is implements checking for multiple errors using [errors.Is], since multiple +// error unwrapping is not possible in versions less than Go 1.20. +func (je joinedError) Is(err error) bool { + for _, e := range je.errs { + if errors.Is(e, err) { + return true + } + } + + return false +} + +// wrappedErrors is a workaround for wrapping multiple errors in environments +// where Go 1.20 is not available. It basically uses the already implemented +// functionatlity of joinedError to handle multiple errors with supplies a +// custom error message that is identical to the one we produce in Go 1.20 using +// multiple %w directives. +type wrappedErrors struct { + msg string + joinedError +} + +// Error returns the stored error string +func (we wrappedErrors) Error() string { + return we.msg +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. Since we cannot use of Go 1.20's possibility +// to include more than one %w formatting directive in [fmt.Errorf], we have to +// emulate that. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + // We cannot wrap multiple errors here with %w, so we have to be a little + // bit creative. Basically, we are using %s instead of %w to produce the + // same error message and then throw the result into a custom error struct. + var format string + var args []any + if message != "" { + format = "%s: %s" + args = []any{err, message} + } else { + format = "%s" + args = []any{err} + } + errs := []error{err} + + for _, e := range more { + format += ": %s" + args = append(args, e) + errs = append(errs, e) + } + + err = &wrappedErrors{ + msg: fmt.Sprintf(format, args...), + joinedError: joinedError{errs: errs}, + } + return err +} diff --git a/errors_test.go b/errors_test.go new file mode 100644 index 00000000..fd4004b3 --- /dev/null +++ b/errors_test.go @@ -0,0 +1,95 @@ +package jwt + +import ( + "errors" + "io" + "testing" +) + +func Test_joinErrors(t *testing.T) { + type args struct { + errs []error + } + tests := []struct { + name string + args args + wantErrors []error + wantMessage string + }{ + { + name: "multiple errors", + args: args{ + errs: []error{ErrTokenNotValidYet, ErrTokenExpired}, + }, + wantErrors: []error{ErrTokenNotValidYet, ErrTokenExpired}, + wantMessage: "token is not valid yet, token is expired", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := joinErrors(tt.args.errs...) + for _, wantErr := range tt.wantErrors { + if !errors.Is(err, wantErr) { + t.Errorf("joinErrors() error = %v, does not contain %v", err, wantErr) + } + } + + if err.Error() != tt.wantMessage { + t.Errorf("joinErrors() error.Error() = %v, wantMessage %v", err, tt.wantMessage) + } + }) + } +} + +func Test_newError(t *testing.T) { + type args struct { + message string + err error + more []error + } + tests := []struct { + name string + args args + wantErrors []error + wantMessage string + }{ + { + name: "single error", + args: args{message: "something is wrong", err: ErrTokenMalformed}, + wantMessage: "token is malformed: something is wrong", + wantErrors: []error{ErrTokenMalformed}, + }, + { + name: "two errors", + args: args{message: "something is wrong", err: ErrTokenMalformed, more: []error{io.ErrUnexpectedEOF}}, + wantMessage: "token is malformed: something is wrong: unexpected EOF", + wantErrors: []error{ErrTokenMalformed}, + }, + { + name: "two errors, no detail", + args: args{message: "", err: ErrTokenInvalidClaims, more: []error{ErrTokenExpired}}, + wantMessage: "token has invalid claims: token is expired", + wantErrors: []error{ErrTokenInvalidClaims, ErrTokenExpired}, + }, + { + name: "two errors, no detail and join error", + args: args{message: "", err: ErrTokenInvalidClaims, more: []error{joinErrors(ErrTokenExpired, ErrTokenNotValidYet)}}, + wantMessage: "token has invalid claims: token is expired, token is not valid yet", + wantErrors: []error{ErrTokenInvalidClaims, ErrTokenExpired, ErrTokenNotValidYet}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := newError(tt.args.message, tt.args.err, tt.args.more...) + for _, wantErr := range tt.wantErrors { + if !errors.Is(err, wantErr) { + t.Errorf("newError() error = %v, does not contain %v", err, wantErr) + } + } + + if err.Error() != tt.wantMessage { + t.Errorf("newError() error.Error() = %v, wantMessage %v", err, tt.wantMessage) + } + }) + } +} diff --git a/example_test.go b/example_test.go index ddf49ccb..58fdea43 100644 --- a/example_test.go +++ b/example_test.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) // Example (atypical) using the RegisteredClaims type by itself to parse a token. @@ -70,7 +70,7 @@ func ExampleNewWithClaims_customClaimsType() { //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM } -// Example creating a token using a custom claims type. The StandardClaim is embedded +// Example creating a token using a custom claims type. The RegisteredClaims is embedded // in the custom type to allow for easy encoding, parsing and validation of standard claims. func ExampleParseWithClaims_customClaimsType() { tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" @@ -93,7 +93,65 @@ func ExampleParseWithClaims_customClaimsType() { // Output: bar test } -// An example of parsing the error types using bitfield checks +// Example creating a token using a custom claims type and validation options. The RegisteredClaims is embedded +// in the custom type to allow for easy encoding, parsing and validation of standard claims. +func ExampleParseWithClaims_validationOptions() { + tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" + + type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims + } + + token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { + return []byte("AllYourBase"), nil + }, jwt.WithLeeway(5*time.Second)) + + if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { + fmt.Printf("%v %v", claims.Foo, claims.RegisteredClaims.Issuer) + } else { + fmt.Println(err) + } + + // Output: bar test +} + +type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims +} + +// Validate can be used to execute additional application-specific claims +// validation. +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return errors.New("must be foobar") + } + + return nil +} + +// Example creating a token using a custom claims type and validation options. +// The RegisteredClaims is embedded in the custom type to allow for easy +// encoding, parsing and validation of standard claims and the function +// CustomValidation is implemented. +func ExampleParseWithClaims_customValidation() { + tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiYXVkIjoic2luZ2xlIn0.QAWg1vGvnqRuCFTMcPkjZljXHh8U3L_qUjszOtQbeaA" + + token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) { + return []byte("AllYourBase"), nil + }, jwt.WithLeeway(5*time.Second)) + + if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid { + fmt.Printf("%v %v", claims.Foo, claims.RegisteredClaims.Issuer) + } else { + fmt.Println(err) + } + + // Output: bar test +} + +// An example of parsing the error types using errors.Is. func ExampleParse_errorChecking() { // Token from another example. This token is expired var tokenString = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJleHAiOjE1MDAwLCJpc3MiOiJ0ZXN0In0.HE7fK0xOQwFEr4WDgRWj4teRPZ6i3GLwD5YCm6Pwu_c" diff --git a/go.mod b/go.mod index 2f215c5e..7fbfcedd 100644 --- a/go.mod +++ b/go.mod @@ -1,7 +1,3 @@ -module github.com/golang-jwt/jwt/v4 +module github.com/golang-jwt/jwt/v5 -go 1.16 - -retract ( - v4.4.0 // Contains a backwards incompatible change to the Claims interface. -) +go 1.18 diff --git a/hmac_example_test.go b/hmac_example_test.go index a35d863c..4b2ff08a 100644 --- a/hmac_example_test.go +++ b/hmac_example_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) // For HMAC signing method, the key can be any []byte. It is recommended to generate diff --git a/hmac_test.go b/hmac_test.go index 5a147f43..83d2c3eb 100644 --- a/hmac_test.go +++ b/hmac_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var hmacTestData = []struct { diff --git a/http_example_test.go b/http_example_test.go index de3cbab4..090aa4f7 100644 --- a/http_example_test.go +++ b/http_example_test.go @@ -16,8 +16,8 @@ import ( "strings" "time" - "github.com/golang-jwt/jwt/v4" - "github.com/golang-jwt/jwt/v4/request" + "github.com/golang-jwt/jwt/v5" + "github.com/golang-jwt/jwt/v5/request" ) // location of the files used for signing and verification diff --git a/map_claims.go b/map_claims.go index 2700d64a..b2b51a1f 100644 --- a/map_claims.go +++ b/map_claims.go @@ -2,150 +2,108 @@ package jwt import ( "encoding/json" - "errors" - "time" - // "fmt" + "fmt" ) -// MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. -// This is the default claims type if you don't supply one +// MapClaims is a claims type that uses the map[string]interface{} for JSON +// decoding. This is the default claims type if you don't supply one type MapClaims map[string]interface{} -// VerifyAudience Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - var aud []string - switch v := m["aud"].(type) { - case string: - aud = append(aud, v) - case []string: - aud = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return false - } - aud = append(aud, vs) - } - } - return verifyAud(aud, cmp, req) +// GetExpirationTime implements the Claims interface. +func (m MapClaims) GetExpirationTime() (*NumericDate, error) { + return m.parseNumericDate("exp") } -// VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). -// If req is false, it will return true, if exp is unset. -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["exp"] - if !ok { - return !req - } - - switch exp := v.(type) { - case float64: - if exp == 0 { - return verifyExp(nil, cmpTime, req) - } +// GetNotBefore implements the Claims interface. +func (m MapClaims) GetNotBefore() (*NumericDate, error) { + return m.parseNumericDate("nbf") +} - return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req) - case json.Number: - v, _ := exp.Float64() +// GetIssuedAt implements the Claims interface. +func (m MapClaims) GetIssuedAt() (*NumericDate, error) { + return m.parseNumericDate("iat") +} - return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } +// GetAudience implements the Claims interface. +func (m MapClaims) GetAudience() (ClaimStrings, error) { + return m.parseClaimsString("aud") +} - return false +// GetIssuer implements the Claims interface. +func (m MapClaims) GetIssuer() (string, error) { + return m.parseString("iss") } -// VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) +// GetSubject implements the Claims interface. +func (m MapClaims) GetSubject() (string, error) { + return m.parseString("sub") +} - v, ok := m["iat"] +// parseNumericDate tries to parse a key in the map claims type as a number +// date. This will succeed, if the underlying type is either a [float64] or a +// [json.Number]. Otherwise, nil will be returned. +func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { + v, ok := m[key] if !ok { - return !req + return nil, nil } - switch iat := v.(type) { + switch exp := v.(type) { case float64: - if iat == 0 { - return verifyIat(nil, cmpTime, req) + if exp == 0 { + return nil, nil } - return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req) + return newNumericDateFromSeconds(exp), nil case json.Number: - v, _ := iat.Float64() + v, _ := exp.Float64() - return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req) + return newNumericDateFromSeconds(v), nil } - return false + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) } -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["nbf"] - if !ok { - return !req - } - - switch nbf := v.(type) { - case float64: - if nbf == 0 { - return verifyNbf(nil, cmpTime, req) +// parseClaimsString tries to parse a key in the map claims type as a +// [ClaimsStrings] type, which can either be a string or an array of string. +func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { + var cs []string + switch v := m[key].(type) { + case string: + cs = append(cs, v) + case []string: + cs = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + cs = append(cs, vs) } - - return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req) - case json.Number: - v, _ := nbf.Float64() - - return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req) } - return false -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) + return cs, nil } -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if !m.VerifyExpiresAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenExpired - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if !m.VerifyIssuedAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenUsedBeforeIssued - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if !m.VerifyNotBefore(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenNotValidYet - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet +// parseString tries to parse a key in the map claims type as a [string] type. +// If the key does not exist, an empty string is returned. If the key has the +// wrong type, an error is returned. +func (m MapClaims) parseString(key string) (string, error) { + var ( + ok bool + raw interface{} + iss string + ) + raw, ok = m[key] + if !ok { + return "", nil } - if vErr.valid() { - return nil + iss, ok = raw.(string) + if !ok { + return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) } - return vErr + return iss, nil } diff --git a/map_claims_test.go b/map_claims_test.go index 361c49d2..83065d5b 100644 --- a/map_claims_test.go +++ b/map_claims_test.go @@ -42,7 +42,7 @@ func TestVerifyAud(t *testing.T) { {Name: "[]String Aud without match not required", MapClaims: MapClaims{"aud": []string{"not.example.com", "example.example.com"}}, Expected: false, Required: true, Comparison: "example.com"}, // Required = false - {Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: false, Required: true, Comparison: "example.com"}, + {Name: "Empty []String Aud without match required", MapClaims: MapClaims{"aud": []string{""}}, Expected: true, Required: false, Comparison: "example.com"}, // []interface{} {Name: "Empty []interface{} Aud without match required", MapClaims: MapClaims{"aud": nilListInterface}, Expected: true, Required: false, Comparison: "example.com"}, @@ -56,10 +56,17 @@ func TestVerifyAud(t *testing.T) { for _, test := range tests { t.Run(test.Name, func(t *testing.T) { - got := test.MapClaims.VerifyAudience(test.Comparison, test.Required) + var opts []ParserOption + + if test.Required { + opts = append(opts, WithAudience(test.Comparison)) + } - if got != test.Expected { - t.Errorf("Expected %v, got %v", test.Expected, got) + validator := newValidator(opts...) + got := validator.Validate(test.MapClaims) + + if (got == nil) != test.Expected { + t.Errorf("Expected %v, got %v", test.Expected, (got == nil)) } }) } @@ -70,9 +77,9 @@ func TestMapclaimsVerifyIssuedAtInvalidTypeString(t *testing.T) { "iat": "foo", } want := false - got := mapClaims.VerifyIssuedAt(0, false) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + got := newValidator(WithIssuedAt()).Validate(mapClaims) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) } } @@ -81,9 +88,9 @@ func TestMapclaimsVerifyNotBeforeInvalidTypeString(t *testing.T) { "nbf": "foo", } want := false - got := mapClaims.VerifyNotBefore(0, false) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + got := newValidator().Validate(mapClaims) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) } } @@ -92,32 +99,91 @@ func TestMapclaimsVerifyExpiresAtInvalidTypeString(t *testing.T) { "exp": "foo", } want := false - got := mapClaims.VerifyExpiresAt(0, false) + got := newValidator().Validate(mapClaims) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) } } func TestMapClaimsVerifyExpiresAtExpire(t *testing.T) { - exp := time.Now().Unix() + exp := time.Now() mapClaims := MapClaims{ - "exp": float64(exp), + "exp": float64(exp.Unix()), } want := false - got := mapClaims.VerifyExpiresAt(exp, true) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + got := newValidator(WithTimeFunc(func() time.Time { + return exp + })).Validate(mapClaims) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) } - got = mapClaims.VerifyExpiresAt(exp+1, true) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + got = newValidator(WithTimeFunc(func() time.Time { + return exp.Add(1 * time.Second) + })).Validate(mapClaims) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) } want = true - got = mapClaims.VerifyExpiresAt(exp-1, true) - if want != got { - t.Fatalf("Failed to verify claims, wanted: %v got %v", want, got) + got = newValidator(WithTimeFunc(func() time.Time { + return exp.Add(-1 * time.Second) + })).Validate(mapClaims) + if want != (got == nil) { + t.Fatalf("Failed to verify claims, wanted: %v got %v", want, (got == nil)) + } +} + +func TestMapClaims_parseString(t *testing.T) { + type args struct { + key string + } + tests := []struct { + name string + m MapClaims + args args + want string + wantErr bool + }{ + { + name: "missing key", + m: MapClaims{}, + args: args{ + key: "mykey", + }, + want: "", + wantErr: false, + }, + { + name: "wrong key type", + m: MapClaims{"mykey": 4}, + args: args{ + key: "mykey", + }, + want: "", + wantErr: true, + }, + { + name: "correct key type", + m: MapClaims{"mykey": "mystring"}, + args: args{ + key: "mykey", + }, + want: "mystring", + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := tt.m.parseString(tt.args.key) + if (err != nil) != tt.wantErr { + t.Errorf("MapClaims.parseString() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("MapClaims.parseString() = %v, want %v", got, tt.want) + } + }) } } diff --git a/none.go b/none.go index f19835d2..a16495ac 100644 --- a/none.go +++ b/none.go @@ -13,7 +13,7 @@ type unsafeNoneMagicConstant string func init() { SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { return SigningMethodNone @@ -33,10 +33,7 @@ func (m *signingMethodNone) Verify(signingString, signature string, key interfac } // If signing method is none, signature must be an empty string if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) + return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) } // Accept 'none' signing method. diff --git a/none_test.go b/none_test.go index cbf6657e..35ff13af 100644 --- a/none_test.go +++ b/none_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var noneTestData = []struct { diff --git a/parser.go b/parser.go index c0a6f692..46b67931 100644 --- a/parser.go +++ b/parser.go @@ -9,26 +9,24 @@ import ( type Parser struct { // If populated, only these methods will be considered valid. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - ValidMethods []string + validMethods []string // Use JSON Number format in JSON decoder. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - UseJSONNumber bool + useJSONNumber bool // Skip claims validation during token parsing. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - SkipClaimsValidation bool + skipClaimsValidation bool + + validator *validator } // NewParser creates a new Parser with the specified options func NewParser(options ...ParserOption) *Parser { - p := &Parser{} + p := &Parser{ + validator: &validator{}, + } - // loop through our parsing options and apply them + // Loop through our parsing options and apply them for _, option := range options { option(p) } @@ -56,10 +54,10 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } // Verify signing method is in the required set - if p.ValidMethods != nil { + if p.validMethods != nil { var signingMethodValid = false var alg = token.Method.Alg() - for _, m := range p.ValidMethods { + for _, m := range p.validMethods { if m == alg { signingMethodValid = true break @@ -67,7 +65,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } if !signingMethodValid { // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) } } @@ -75,45 +73,34 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf var key interface{} if keyFunc == nil { // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + return token, newError("no keyfunc was provided", ErrTokenUnverifiable) } if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) } - vErr := &ValidationError{} + // Perform signature validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + return token, newError("", ErrTokenSignatureInvalid, err) + } // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } + if !p.skipClaimsValidation { + // Make sure we have at least a default validator + if p.validator == nil { + p.validator = newValidator() } - } - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid + if err := p.validator.Validate(claims); err != nil { + return token, newError("", ErrTokenInvalidClaims, err) + } } - if vErr.valid() { - token.Valid = true - return token, nil - } + // No errors so far, token is valid. + token.Valid = true - return token, vErr + return token, nil } // ParseUnverified parses the token but doesn't validate the signature. @@ -125,7 +112,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { parts = strings.Split(tokenString, ".") if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) } token = &Token{Raw: tokenString} @@ -134,12 +121,12 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) } // parse Claims @@ -147,10 +134,10 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) } dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { + if p.useJSONNumber { dec.UseNumber() } // JSON Decode. Special case for map type to avoid weird pointer behavior @@ -161,16 +148,16 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke } // Handle decode error if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) } } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) } return token, parts, nil diff --git a/parser_option.go b/parser_option.go index 6ea6f952..8d5917e9 100644 --- a/parser_option.go +++ b/parser_option.go @@ -1,29 +1,101 @@ package jwt -// ParserOption is used to implement functional-style options that modify the behavior of the parser. To add -// new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that -// takes a *Parser type as input and manipulates its configuration accordingly. +import "time" + +// ParserOption is used to implement functional-style options that modify the +// behavior of the parser. To add new options, just create a function (ideally +// beginning with With or Without) that returns an anonymous function that takes +// a *Parser type as input and manipulates its configuration accordingly. type ParserOption func(*Parser) -// WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. -// It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. +// WithValidMethods is an option to supply algorithm methods that the parser +// will check. Only those methods will be considered valid. It is heavily +// encouraged to use this option in order to prevent attacks such as +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. func WithValidMethods(methods []string) ParserOption { return func(p *Parser) { - p.ValidMethods = methods + p.validMethods = methods } } -// WithJSONNumber is an option to configure the underlying JSON parser with UseNumber +// WithJSONNumber is an option to configure the underlying JSON parser with +// UseNumber. func WithJSONNumber() ParserOption { return func(p *Parser) { - p.UseJSONNumber = true + p.useJSONNumber = true } } -// WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know -// what you are doing. +// WithoutClaimsValidation is an option to disable claims validation. This +// option should only be used if you exactly know what you are doing. func WithoutClaimsValidation() ParserOption { return func(p *Parser) { - p.SkipClaimsValidation = true + p.skipClaimsValidation = true + } +} + +// WithLeeway returns the ParserOption for specifying the leeway window. +func WithLeeway(leeway time.Duration) ParserOption { + return func(p *Parser) { + p.validator.leeway = leeway + } +} + +// WithTimeFunc returns the ParserOption for specifying the time func. The +// primary use-case for this is testing. If you are looking for a way to account +// for clock-skew, WithLeeway should be used instead. +func WithTimeFunc(f func() time.Time) ParserOption { + return func(p *Parser) { + p.validator.timeFunc = f + } +} + +// WithIssuedAt returns the ParserOption to enable verification +// of issued-at. +func WithIssuedAt() ParserOption { + return func(p *Parser) { + p.validator.verifyIat = true + } +} + +// WithAudience configures the validator to require the specified audience in +// the `aud` claim. Validation will fail if the audience is not listed in the +// token or the `aud` claim is missing. +// +// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an audience is expected. +func WithAudience(aud string) ParserOption { + return func(p *Parser) { + p.validator.expectedAud = aud + } +} + +// WithIssuer configures the validator to require the specified issuer in the +// `iss` claim. Validation will fail if a different issuer is specified in the +// token or the `iss` claim is missing. +// +// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an issuer is expected. +func WithIssuer(iss string) ParserOption { + return func(p *Parser) { + p.validator.expectedIss = iss + } +} + +// WithSubject configures the validator to require the specified subject in the +// `sub` claim. Validation will fail if a different subject is specified in the +// token or the `sub` claim is missing. +// +// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if a subject is expected. +func WithSubject(sub string) ParserOption { + return func(p *Parser) { + p.validator.expectedSub = sub } } diff --git a/parser_test.go b/parser_test.go index 26a168e9..fdb5eef3 100644 --- a/parser_test.go +++ b/parser_test.go @@ -10,8 +10,8 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" - "github.com/golang-jwt/jwt/v4/test" + "github.com/golang-jwt/jwt/v5" + "github.com/golang-jwt/jwt/v5/test" ) var errKeyFuncError error = fmt.Errorf("error loading key") @@ -51,18 +51,46 @@ var jwtTestData = []struct { keyfunc jwt.Keyfunc claims jwt.Claims valid bool - errors uint32 err []error parser *jwt.Parser signingMethod jwt.SigningMethod // The method to sign the JWT token for test purpose }{ + { + "invalid JWT", + "thisisnotreallyajwt", + defaultKeyFunc, + nil, + false, + []error{jwt.ErrTokenMalformed}, + nil, + jwt.SigningMethodRS256, + }, + { + "invalid JSON claim", + "eyJhbGciOiJSUzI1NiIsInppcCI6IkRFRiJ9.eNqqVkqtKFCyMjQ1s7Q0sbA0MtFRyk3NTUot8kxRslIKLbZQggn4JeamAoUcfRz99HxcXRWeze172tr4bFq7Ui0AAAD__w.jBXD4LT4aq4oXTgDoPkiV6n4QdSZPZI1Z4J8MWQC42aHK0oXwcovEU06dVbtB81TF-2byuu0-qi8J0GUttODT67k6gCl6DV_iuCOV7gczwTcvKslotUvXzoJ2wa0QuujnjxLEE50r0p6k0tsv_9OIFSUZzDksJFYNPlJH2eFG55DROx4TsOz98az37SujZi9GGbTc9SLgzFHPrHMrovRZ5qLC_w4JrdtsLzBBI11OQJgRYwV8fQf4O8IsMkHtetjkN7dKgUkJtRarNWOk76rpTPppLypiLU4_J0-wrElLMh1TzUVZW6Fz2cDHDDBACJgMmKQ2pOFEDK_vYZN74dLCF5GiTZV6DbXhNxO7lqT7JUN4a3p2z96G7WNRjblf2qZeuYdQvkIsiK-rCbSIE836XeY5gaBgkOzuEvzl_tMrpRmb5Oox1ibOfVT2KBh9Lvqsb1XbQjCio2CLE2ViCLqoe0AaRqlUyrk3n8BIG-r0IW4dcw96CEryEMIjsjVp9mtPXamJzf391kt8Rf3iRBqwv3zP7Plg1ResXbmsFUgOflAUPcYmfLug4W3W52ntcUlTHAKXrNfaJL9QQiYAaDukG-ZHDytsOWTuuXw7lVxjt-XYi1VbRAIjh1aIYSELEmEpE4Ny74htQtywYXMQNfJpB0nNn8IiWakgcYYMJ0TmKM", + defaultKeyFunc, + nil, + false, + []error{jwt.ErrTokenMalformed}, + nil, + jwt.SigningMethodRS256, + }, + { + "bearer in JWT", + "bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", + defaultKeyFunc, + nil, + false, + []error{jwt.ErrTokenMalformed}, + nil, + jwt.SigningMethodRS256, + }, { "basic", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJmb28iOiJiYXIifQ.FhkiHkoESI_cG3NPigFrxEk9Z60_oXrOT2vGm9Pn6RDgYNovYORQmmA0zs1AoAOf09ly2Nx2YAg6ABqAYga1AcMFkJljwxTT5fYphTuqpWdy4BELeSYJx5Ty2gmr8e7RonuUztrdD5WfPqLKMm1Ozp_T6zALpRmwTIW0QPnaBXaQD90FplAg46Iy1UlDKr-Eupy0i5SLch5Q-p2ZpaL_5fnTIUDlxC3pWhJTyx_71qDI-mAA_5lE_VdroOeflG56sSmDxopPEG3bFlSu1eowyBfxtu0_CuVd-M42RU75Zc4Gsj6uV77MBtbMrf4_7M_NUTSgoIF3fRqxrj0NzihIBg", defaultKeyFunc, jwt.MapClaims{"foo": "bar"}, true, - 0, nil, nil, jwt.SigningMethodRS256, @@ -73,7 +101,6 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "exp": float64(time.Now().Unix() - 100)}, false, - jwt.ValidationErrorExpired, []error{jwt.ErrTokenExpired}, nil, jwt.SigningMethodRS256, @@ -84,7 +111,6 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100)}, false, - jwt.ValidationErrorNotValidYet, []error{jwt.ErrTokenNotValidYet}, nil, jwt.SigningMethodRS256, @@ -95,8 +121,7 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "nbf": float64(time.Now().Unix() + 100), "exp": float64(time.Now().Unix() - 100)}, false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - []error{jwt.ErrTokenNotValidYet}, + []error{jwt.ErrTokenNotValidYet, jwt.ErrTokenExpired}, nil, jwt.SigningMethodRS256, }, @@ -106,7 +131,6 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorSignatureInvalid, []error{jwt.ErrTokenSignatureInvalid, rsa.ErrVerification}, nil, jwt.SigningMethodRS256, @@ -117,7 +141,6 @@ var jwtTestData = []struct { nilKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorUnverifiable, []error{jwt.ErrTokenUnverifiable}, nil, jwt.SigningMethodRS256, @@ -128,7 +151,6 @@ var jwtTestData = []struct { emptyKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorSignatureInvalid, []error{jwt.ErrTokenSignatureInvalid}, nil, jwt.SigningMethodRS256, @@ -139,7 +161,6 @@ var jwtTestData = []struct { errorKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorUnverifiable, []error{jwt.ErrTokenUnverifiable, errKeyFuncError}, nil, jwt.SigningMethodRS256, @@ -150,9 +171,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorSignatureInvalid, []error{jwt.ErrTokenSignatureInvalid}, - &jwt.Parser{ValidMethods: []string{"HS256"}}, + jwt.NewParser(jwt.WithValidMethods([]string{"HS256"})), jwt.SigningMethodRS256, }, { @@ -161,9 +181,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar"}, true, - 0, nil, - &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}}, + jwt.NewParser(jwt.WithValidMethods([]string{"RS256", "HS256"})), jwt.SigningMethodRS256, }, { @@ -172,9 +191,8 @@ var jwtTestData = []struct { ecdsaKeyFunc, jwt.MapClaims{"foo": "bar"}, false, - jwt.ValidationErrorSignatureInvalid, []error{jwt.ErrTokenSignatureInvalid}, - &jwt.Parser{ValidMethods: []string{"RS256", "HS256"}}, + jwt.NewParser(jwt.WithValidMethods([]string{"RS256", "HS256"})), jwt.SigningMethodES256, }, { @@ -183,9 +201,8 @@ var jwtTestData = []struct { ecdsaKeyFunc, jwt.MapClaims{"foo": "bar"}, true, - 0, nil, - &jwt.Parser{ValidMethods: []string{"HS256", "ES256"}}, + jwt.NewParser(jwt.WithValidMethods([]string{"HS256", "ES256"})), jwt.SigningMethodES256, }, { @@ -194,22 +211,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": json.Number("123.4")}, true, - 0, - nil, - &jwt.Parser{UseJSONNumber: true}, - jwt.SigningMethodRS256, - }, - { - "Standard Claims", - "", - defaultKeyFunc, - &jwt.StandardClaims{ - ExpiresAt: time.Now().Add(time.Second * 10).Unix(), - }, - true, - 0, nil, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -218,9 +221,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, false, - jwt.ValidationErrorExpired, []error{jwt.ErrTokenExpired}, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -229,9 +231,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, false, - jwt.ValidationErrorNotValidYet, []error{jwt.ErrTokenNotValidYet}, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -240,9 +241,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100)), "exp": json.Number(fmt.Sprintf("%v", time.Now().Unix()-100))}, false, - jwt.ValidationErrorNotValidYet | jwt.ValidationErrorExpired, - []error{jwt.ErrTokenNotValidYet}, - &jwt.Parser{UseJSONNumber: true}, + []error{jwt.ErrTokenNotValidYet, jwt.ErrTokenExpired}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -251,9 +251,8 @@ var jwtTestData = []struct { defaultKeyFunc, jwt.MapClaims{"foo": "bar", "nbf": json.Number(fmt.Sprintf("%v", time.Now().Unix()+100))}, true, - 0, nil, - &jwt.Parser{UseJSONNumber: true, SkipClaimsValidation: true}, + jwt.NewParser(jwt.WithJSONNumber(), jwt.WithoutClaimsValidation()), jwt.SigningMethodRS256, }, { @@ -264,9 +263,8 @@ var jwtTestData = []struct { ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second * 10)), }, true, - 0, nil, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -277,9 +275,8 @@ var jwtTestData = []struct { Audience: jwt.ClaimStrings{"test"}, }, true, - 0, nil, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -290,9 +287,8 @@ var jwtTestData = []struct { Audience: jwt.ClaimStrings{"test", "test"}, }, true, - 0, nil, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -303,9 +299,8 @@ var jwtTestData = []struct { Audience: nil, // because of the unmarshal error, this will be empty }, false, - jwt.ValidationErrorMalformed, []error{jwt.ErrTokenMalformed}, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), jwt.SigningMethodRS256, }, { @@ -316,9 +311,28 @@ var jwtTestData = []struct { Audience: nil, // because of the unmarshal error, this will be empty }, false, - jwt.ValidationErrorMalformed, []error{jwt.ErrTokenMalformed}, - &jwt.Parser{UseJSONNumber: true}, + jwt.NewParser(jwt.WithJSONNumber()), + jwt.SigningMethodRS256, + }, + { + "RFC7519 Claims - nbf with 60s skew", + "", // autogen + defaultKeyFunc, + &jwt.RegisteredClaims{NotBefore: jwt.NewNumericDate(time.Now().Add(time.Second * 100))}, + false, + []error{jwt.ErrTokenNotValidYet}, + jwt.NewParser(jwt.WithLeeway(time.Minute)), + jwt.SigningMethodRS256, + }, + { + "RFC7519 Claims - nbf with 120s skew", + "", // autogen + defaultKeyFunc, + &jwt.RegisteredClaims{NotBefore: jwt.NewNumericDate(time.Now().Add(time.Second * 100))}, + true, + nil, + jwt.NewParser(jwt.WithLeeway(2 * time.Minute)), jwt.SigningMethodRS256, }, } @@ -350,24 +364,23 @@ func TestParser_Parse(t *testing.T) { // Parse the token var token *jwt.Token - var ve *jwt.ValidationError var err error var parser = data.parser if parser == nil { - parser = new(jwt.Parser) + parser = jwt.NewParser() } // Figure out correct claims type switch data.claims.(type) { case jwt.MapClaims: token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) - case *jwt.StandardClaims: - token, err = parser.ParseWithClaims(data.tokenString, &jwt.StandardClaims{}, data.keyfunc) case *jwt.RegisteredClaims: token, err = parser.ParseWithClaims(data.tokenString, &jwt.RegisteredClaims{}, data.keyfunc) + case nil: + token, err = parser.ParseWithClaims(data.tokenString, nil, data.keyfunc) } // Verify result matches expectation - if !reflect.DeepEqual(data.claims, token.Claims) { + if data.claims != nil && !reflect.DeepEqual(data.claims, token.Claims) { t.Errorf("[%v] Claims mismatch. Expecting: %v Got: %v", data.name, data.claims, token.Claims) } @@ -379,27 +392,13 @@ func TestParser_Parse(t *testing.T) { t.Errorf("[%v] Invalid token passed validation", data.name) } - if (err == nil && !token.Valid) || (err != nil && token.Valid) { + // Since the returned token is nil in the ErrTokenMalformed, we + // cannot make the comparison here + if !errors.Is(err, jwt.ErrTokenMalformed) && + ((err == nil && !token.Valid) || (err != nil && token.Valid)) { t.Errorf("[%v] Inconsistent behavior between returned error and token.Valid", data.name) } - if data.errors != 0 { - if err == nil { - t.Errorf("[%v] Expecting error. Didn't get one.", data.name) - } else { - if errors.As(err, &ve) { - // compare the bitfield part of the error - if e := ve.Errors; e != data.errors { - t.Errorf("[%v] Errors don't match expectation. %v != %v", data.name, e, data.errors) - } - - if err.Error() == errKeyFuncError.Error() && ve.Inner != errKeyFuncError { - t.Errorf("[%v] Inner error does not match expectation. %v != %v", data.name, ve.Inner, errKeyFuncError) - } - } - } - } - if data.err != nil { if err == nil { t.Errorf("[%v] Expecting error(s). Didn't get one.", data.name) @@ -433,7 +432,7 @@ func TestParser_ParseUnverified(t *testing.T) { // Iterate over test data set and run tests for _, data := range jwtTestData { // Skip test data, that intentionally contains malformed tokens, as they would lead to an error - if data.errors&jwt.ValidationErrorMalformed != 0 { + if len(data.err) == 1 && errors.Is(data.err[0], jwt.ErrTokenMalformed) { continue } @@ -454,8 +453,6 @@ func TestParser_ParseUnverified(t *testing.T) { switch data.claims.(type) { case jwt.MapClaims: token, _, err = parser.ParseUnverified(data.tokenString, jwt.MapClaims{}) - case *jwt.StandardClaims: - token, _, err = parser.ParseUnverified(data.tokenString, &jwt.StandardClaims{}) case *jwt.RegisteredClaims: token, _, err = parser.ParseUnverified(data.tokenString, &jwt.RegisteredClaims{}) } @@ -655,8 +652,7 @@ func TestSetPadding(t *testing.T) { // Parse the token var token *jwt.Token var err error - parser := new(jwt.Parser) - parser.SkipClaimsValidation = true + parser := jwt.NewParser(jwt.WithoutClaimsValidation()) // Figure out correct claims type token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) @@ -695,9 +691,9 @@ func BenchmarkParseUnverified(b *testing.B) { b.Run("map_claims", func(b *testing.B) { benchmarkParsing(b, parser, data.tokenString, jwt.MapClaims{}) }) - case *jwt.StandardClaims: - b.Run("standard_claims", func(b *testing.B) { - benchmarkParsing(b, parser, data.tokenString, &jwt.StandardClaims{}) + case *jwt.RegisteredClaims: + b.Run("registered_claims", func(b *testing.B) { + benchmarkParsing(b, parser, data.tokenString, &jwt.RegisteredClaims{}) }) } } diff --git a/registered_claims.go b/registered_claims.go new file mode 100644 index 00000000..77951a53 --- /dev/null +++ b/registered_claims.go @@ -0,0 +1,63 @@ +package jwt + +// RegisteredClaims are a structured version of the JWT Claims Set, +// restricted to Registered Claim Names, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +// +// This type can be used on its own, but then additional private and +// public claims embedded in the JWT will not be parsed. The typical use-case +// therefore is to embedded this in a user-defined claim type. +// +// See examples for how to use this with your own claim types. +type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` + + // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` + + // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` + + // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` + + // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` + + // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` + + // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` +} + +// GetExpirationTime implements the Claims interface. +func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { + return c.ExpiresAt, nil +} + +// GetNotBefore implements the Claims interface. +func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { + return c.NotBefore, nil +} + +// GetIssuedAt implements the Claims interface. +func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { + return c.IssuedAt, nil +} + +// GetAudience implements the Claims interface. +func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { + return c.Audience, nil +} + +// GetIssuer implements the Claims interface. +func (c RegisteredClaims) GetIssuer() (string, error) { + return c.Issuer, nil +} + +// GetSubject implements the Claims interface. +func (c RegisteredClaims) GetSubject() (string, error) { + return c.Subject, nil +} diff --git a/request/request.go b/request/request.go index 79f53f4e..5723c809 100644 --- a/request/request.go +++ b/request/request.go @@ -3,7 +3,7 @@ package request import ( "net/http" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) // ParseFromRequest extracts and parses a JWT token from an HTTP request. diff --git a/request/request_test.go b/request/request_test.go index b7c07648..0906d1cf 100644 --- a/request/request_test.go +++ b/request/request_test.go @@ -8,8 +8,8 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" - "github.com/golang-jwt/jwt/v4/test" + "github.com/golang-jwt/jwt/v5" + "github.com/golang-jwt/jwt/v5/test" ) var requestTestData = []struct { diff --git a/rsa_pss_test.go b/rsa_pss_test.go index a897e136..1c3d9ea5 100644 --- a/rsa_pss_test.go +++ b/rsa_pss_test.go @@ -10,8 +10,8 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" - "github.com/golang-jwt/jwt/v4/test" + "github.com/golang-jwt/jwt/v5" + "github.com/golang-jwt/jwt/v5/test" ) var rsaPSSTestData = []struct { diff --git a/rsa_test.go b/rsa_test.go index 97ae0409..8ca6e7a1 100644 --- a/rsa_test.go +++ b/rsa_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) var rsaTestData = []struct { diff --git a/test/helpers.go b/test/helpers.go index 6dd64f8a..381c5f8a 100644 --- a/test/helpers.go +++ b/test/helpers.go @@ -5,7 +5,7 @@ import ( "crypto/rsa" "os" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) func LoadRSAPrivateKeyFromDisk(location string) *rsa.PrivateKey { diff --git a/token.go b/token.go index 786b275c..b3459427 100644 --- a/token.go +++ b/token.go @@ -4,50 +4,51 @@ import ( "encoding/base64" "encoding/json" "strings" - "time" ) -// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 -// states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations -// of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global -// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. -// To use the non-recommended decoding, set this boolean to `true` prior to using this package. +// DecodePaddingAllowed will switch the codec used for decoding JWTs +// respectively. Note that the JWS RFC7515 states that the tokens will utilize a +// Base64url encoding with no padding. Unfortunately, some implementations of +// JWT are producing non-standard tokens, and thus require support for decoding. +// Note that this is a global variable, and updating it will change the behavior +// on a package level, and is also NOT go-routine safe. To use the +// non-recommended decoding, set this boolean to `true` prior to using this +// package. var DecodePaddingAllowed bool // DecodeStrict will switch the codec used for decoding JWTs into strict mode. -// In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. -// Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. -// To use strict decoding, set this boolean to `true` prior to using this package. +// In this mode, the decoder requires that trailing padding bits are zero, as +// described in RFC 4648 section 3.5. Note that this is a global variable, and +// updating it will change the behavior on a package level, and is also NOT +// go-routine safe. To use strict decoding, set this boolean to `true` prior to +// using this package. var DecodeStrict bool -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - // Keyfunc will be used by the Parse methods as a callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. +// the key for verification. The function receives the parsed, but unverified +// Token. This allows you to use properties in the Header of the token (such as +// `kid`) to identify which key to use. type Keyfunc func(*Token) (interface{}, error) -// Token represents a JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. +// Token represents a JWT Token. Different fields will be used depending on +// whether you're creating or parsing/verifying a token. type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token + Raw string // Raw contains the raw token. Populated when you [Parse] a token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token + Claims Claims // Claims is the second segment of the token + Signature string // Signature is the third segment of the token. Populated when you Parse a token + Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token } -// New creates a new Token with the specified signing method and an empty map of claims. +// New creates a new [Token] with the specified signing method and an empty map of +// claims. func New(method SigningMethod) *Token { return NewWithClaims(method, MapClaims{}) } -// NewWithClaims creates a new Token with the specified signing method and claims. +// NewWithClaims creates a new [Token] with the specified signing method and +// claims. func NewWithClaims(method SigningMethod, claims Claims) *Token { return &Token{ Header: map[string]interface{}{ @@ -59,8 +60,8 @@ func NewWithClaims(method SigningMethod, claims Claims) *Token { } } -// SignedString creates and returns a complete, signed JWT. -// The token is signed using the SigningMethod specified in the token. +// SignedString creates and returns a complete, signed JWT. The token is signed +// using the SigningMethod specified in the token. func (t *Token) SignedString(key interface{}) (string, error) { var sig, sstr string var err error @@ -73,10 +74,9 @@ func (t *Token) SignedString(key interface{}) (string, error) { return strings.Join([]string{sstr, sig}, "."), nil } -// SigningString generates the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. +// SigningString generates the signing string. This is the most expensive part +// of the whole deal. Unless you need this for something special, just go +// straight for the SignedString. func (t *Token) SigningString() (string, error) { var err error var jsonValue []byte @@ -96,36 +96,38 @@ func (t *Token) SigningString() (string, error) { // Parse parses, validates, verifies the signature and returns the parsed token. // keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. -// The caller is strongly encouraged to set the WithValidMethods option to -// validate the 'alg' claim in the token matches the expected algorithm. -// For more details about the importance of validating the 'alg' claim, -// see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +// for verifying the signature. The caller is strongly encouraged to set the +// WithValidMethods option to validate the 'alg' claim in the token matches the +// expected algorithm. For more details about the importance of validating the +// 'alg' claim, see +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { return NewParser(options...).Parse(tokenString, keyFunc) } // ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). // -// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), -// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the -// proper memory for it before passing in the overall claims, otherwise you might run into a panic. +// Note: If you provide a custom claim implementation that embeds one of the +// standard claims (such as RegisteredClaims), make sure that a) you either +// embed a non-pointer version of the claims or b) if you are using a pointer, +// allocate the proper memory for it before passing in the overall claims, +// otherwise you might run into a panic. func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) } // EncodeSegment encodes a JWT specific base64url encoding with padding stripped // -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally +// Deprecated: In a future release, we will demote this function to a +// non-exported function, since it should only be used internally func EncodeSegment(seg []byte) string { return base64.RawURLEncoding.EncodeToString(seg) } // DecodeSegment decodes a JWT specific base64url encoding with padding stripped // -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally +// Deprecated: In a future release, we will demote this function to a +// non-exported function, since it should only be used internally func DecodeSegment(seg string) ([]byte, error) { encoding := base64.RawURLEncoding diff --git a/token_test.go b/token_test.go index e0d740a9..52a00212 100644 --- a/token_test.go +++ b/token_test.go @@ -3,7 +3,7 @@ package jwt_test import ( "testing" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) func TestToken_SigningString(t1 *testing.T) { @@ -30,7 +30,7 @@ func TestToken_SigningString(t1 *testing.T) { "typ": "JWT", "alg": jwt.SigningMethodHS256.Alg(), }, - Claims: jwt.StandardClaims{}, + Claims: jwt.RegisteredClaims{}, Signature: "", Valid: false, }, @@ -67,7 +67,7 @@ func BenchmarkToken_SigningString(b *testing.B) { "typ": "JWT", "alg": jwt.SigningMethodHS256.Alg(), }, - Claims: jwt.StandardClaims{}, + Claims: jwt.RegisteredClaims{}, } b.Run("BenchmarkToken_SigningString", func(b *testing.B) { b.ResetTimer() diff --git a/types.go b/types.go index ac8e140e..b82b3886 100644 --- a/types.go +++ b/types.go @@ -9,22 +9,23 @@ import ( "time" ) -// TimePrecision sets the precision of times and dates within this library. -// This has an influence on the precision of times when comparing expiry or -// other related time fields. Furthermore, it is also the precision of times -// when serializing. +// TimePrecision sets the precision of times and dates within this library. This +// has an influence on the precision of times when comparing expiry or other +// related time fields. Furthermore, it is also the precision of times when +// serializing. // // For backwards compatibility the default precision is set to seconds, so that // no fractional timestamps are generated. var TimePrecision = time.Second -// MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially -// its MarshalJSON function. +// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, +// especially its MarshalJSON function. // // If it is set to true (the default), it will always serialize the type as an -// array of strings, even if it just contains one element, defaulting to the behaviour -// of the underlying []string. If it is set to false, it will serialize to a single -// string, if it contains one element. Otherwise, it will serialize to an array of strings. +// array of strings, even if it just contains one element, defaulting to the +// behavior of the underlying []string. If it is set to false, it will serialize +// to a single string, if it contains one element. Otherwise, it will serialize +// to an array of strings. var MarshalSingleStringAsArray = true // NumericDate represents a JSON numeric date value, as referenced at @@ -58,9 +59,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { // For very large timestamps, UnixNano would overflow an int64, but this // function requires nanosecond level precision, so we have to use the // following technique to get round the issue: + // // 1. Take the normal unix timestamp to form the whole number part of the // output, - // 2. Take the result of the Nanosecond function, which retuns the offset + // 2. Take the result of the Nanosecond function, which returns the offset // within the second of the particular unix time instance, to form the // decimal part of the output // 3. Concatenate them to produce the final result @@ -72,9 +74,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { return output, nil } -// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a -// NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch -// with either integer or non-integer seconds. +// UnmarshalJSON is an implementation of the json.RawMessage interface and +// deserializes a [NumericDate] from a JSON representation, i.e. a +// [json.Number]. This number represents an UNIX epoch with either integer or +// non-integer seconds. func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { var ( number json.Number @@ -95,8 +98,9 @@ func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { return nil } -// ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. -// This type is necessary, since the "aud" claim can either be a single string or an array. +// ClaimStrings is basically just a slice of strings, but it can be either +// serialized from a string array or just a string. This type is necessary, +// since the "aud" claim can either be a single string or an array. type ClaimStrings []string func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { @@ -133,10 +137,11 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { } func (s ClaimStrings) MarshalJSON() (b []byte, err error) { - // This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field, - // only contains one element, it MAY be serialized as a single string. This may or may not be - // desired based on the ecosystem of other JWT library used, so we make it configurable by the - // variable MarshalSingleStringAsArray. + // This handles a special case in the JWT RFC. If the string array, e.g. + // used by the "aud" field, only contains one element, it MAY be serialized + // as a single string. This may or may not be desired based on the ecosystem + // of other JWT library used, so we make it configurable by the variable + // MarshalSingleStringAsArray. if len(s) == 1 && !MarshalSingleStringAsArray { return json.Marshal(s[0]) } diff --git a/types_test.go b/types_test.go index b26c2bef..d07f5586 100644 --- a/types_test.go +++ b/types_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" ) func TestNumericDate(t *testing.T) { diff --git a/validator.go b/validator.go new file mode 100644 index 00000000..38504389 --- /dev/null +++ b/validator.go @@ -0,0 +1,301 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// ClaimsValidator is an interface that can be implemented by custom claims who +// wish to execute any additional claims validation based on +// application-specific logic. The Validate function is then executed in +// addition to the regular claims validation and any error returned is appended +// to the final validation result. +// +// type MyCustomClaims struct { +// Foo string `json:"foo"` +// jwt.RegisteredClaims +// } +// +// func (m MyCustomClaims) Validate() error { +// if m.Foo != "bar" { +// return errors.New("must be foobar") +// } +// return nil +// } +type ClaimsValidator interface { + Claims + Validate() error +} + +// validator is the core of the new Validation API. It is automatically used by +// a [Parser] during parsing and can be modified with various parser options. +// +// Note: This struct is intentionally not exported (yet) as we want to +// internally finalize its API. In the future, we might make it publicly +// available. +type validator struct { + // leeway is an optional leeway that can be provided to account for clock skew. + leeway time.Duration + + // timeFunc is used to supply the current time that is needed for + // validation. If unspecified, this defaults to time.Now. + timeFunc func() time.Time + + // verifyIat specifies whether the iat (Issued At) claim will be verified. + // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this + // only specifies the age of the token, but no validation check is + // necessary. However, if wanted, it can be checked if the iat is + // unrealistic, i.e., in the future. + verifyIat bool + + // expectedAud contains the audience this token expects. Supplying an empty + // string will disable aud checking. + expectedAud string + + // expectedIss contains the issuer this token expects. Supplying an empty + // string will disable iss checking. + expectedIss string + + // expectedSub contains the subject this token expects. Supplying an empty + // string will disable sub checking. + expectedSub string +} + +// newValidator can be used to create a stand-alone validator with the supplied +// options. This validator can then be used to validate already parsed claims. +func newValidator(opts ...ParserOption) *validator { + p := NewParser(opts...) + return p.validator +} + +// Validate validates the given claims. It will also perform any custom +// validation if claims implements the [ClaimsValidator] interface. +func (v *validator) Validate(claims Claims) error { + var ( + now time.Time + errs []error = make([]error, 0, 6) + err error + ) + + // Check, if we have a time func + if v.timeFunc != nil { + now = v.timeFunc() + } else { + now = time.Now() + } + + // We always need to check the expiration time, but usage of the claim + // itself is OPTIONAL. + if err = v.verifyExpiresAt(claims, now, false); err != nil { + errs = append(errs, err) + } + + // We always need to check not-before, but usage of the claim itself is + // OPTIONAL. + if err = v.verifyNotBefore(claims, now, false); err != nil { + errs = append(errs, err) + } + + // Check issued-at if the option is enabled + if v.verifyIat { + if err = v.verifyIssuedAt(claims, now, false); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected audience, we also require the audience claim + if v.expectedAud != "" { + if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected issuer, we also require the issuer claim + if v.expectedIss != "" { + if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected subject, we also require the subject claim + if v.expectedSub != "" { + if err = v.verifySubject(claims, v.expectedSub, true); err != nil { + errs = append(errs, err) + } + } + + // Finally, we want to give the claim itself some possibility to do some + // additional custom validation based on a custom Validate function. + cvt, ok := claims.(ClaimsValidator) + if ok { + if err := cvt.Validate(); err != nil { + errs = append(errs, err) + } + } + + if len(errs) == 0 { + return nil + } + + return joinErrors(errs...) +} + +// verifyExpiresAt compares the exp claim in claims against cmp. This function +// will succeed if cmp < exp. Additional leeway is taken into account. +// +// If exp is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { + exp, err := claims.GetExpirationTime() + if err != nil { + return err + } + + if exp == nil { + return errorIfRequired(required, "exp") + } + + return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) +} + +// verifyIssuedAt compares the iat claim in claims against cmp. This function +// will succeed if cmp >= iat. Additional leeway is taken into account. +// +// If iat is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { + iat, err := claims.GetIssuedAt() + if err != nil { + return err + } + + if iat == nil { + return errorIfRequired(required, "iat") + } + + return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) +} + +// verifyNotBefore compares the nbf claim in claims against cmp. This function +// will return true if cmp >= nbf. Additional leeway is taken into account. +// +// If nbf is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { + nbf, err := claims.GetNotBefore() + if err != nil { + return err + } + + if nbf == nil { + return errorIfRequired(required, "nbf") + } + + return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) +} + +// verifyAudience compares the aud claim against cmp. +// +// If aud is not set or an empty list, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyAudience(claims Claims, cmp string, required bool) error { + aud, err := claims.GetAudience() + if err != nil { + return err + } + + if len(aud) == 0 { + return errorIfRequired(required, "aud") + } + + // use a var here to keep constant time compare when looping over a number of claims + result := false + + var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } + + // case where "" is sent in one or many aud claims + if stringClaims == "" { + return errorIfRequired(required, "aud") + } + + return errorIfFalse(result, ErrTokenInvalidAudience) +} + +// verifyIssuer compares the iss claim in claims against cmp. +// +// If iss is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error { + iss, err := claims.GetIssuer() + if err != nil { + return err + } + + if iss == "" { + return errorIfRequired(required, "iss") + } + + return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) +} + +// verifySubject compares the sub claim against cmp. +// +// If sub is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifySubject(claims Claims, cmp string, required bool) error { + sub, err := claims.GetSubject() + if err != nil { + return err + } + + if sub == "" { + return errorIfRequired(required, "sub") + } + + return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) +} + +// errorIfFalse returns the error specified in err, if the value is true. +// Otherwise, nil is returned. +func errorIfFalse(value bool, err error) error { + if value { + return nil + } else { + return err + } +} + +// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is +// true. Otherwise, nil is returned. +func errorIfRequired(required bool, claim string) error { + if required { + return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) + } else { + return nil + } +} diff --git a/validator_test.go b/validator_test.go new file mode 100644 index 00000000..869b0507 --- /dev/null +++ b/validator_test.go @@ -0,0 +1,261 @@ +package jwt + +import ( + "errors" + "testing" + "time" +) + +var ErrFooBar = errors.New("must be foobar") + +type MyCustomClaims struct { + Foo string `json:"foo"` + RegisteredClaims +} + +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return ErrFooBar + } + return nil +} + +func Test_validator_Validate(t *testing.T) { + type fields struct { + leeway time.Duration + timeFunc func() time.Time + verifyIat bool + expectedAud string + expectedIss string + expectedSub string + } + type args struct { + claims Claims + } + tests := []struct { + name string + fields fields + args args + wantErr error + }{ + { + name: "expected iss mismatch", + fields: fields{expectedIss: "me"}, + args: args{RegisteredClaims{Issuer: "not_me"}}, + wantErr: ErrTokenInvalidIssuer, + }, + { + name: "expected iss is missing", + fields: fields{expectedIss: "me"}, + args: args{RegisteredClaims{}}, + wantErr: ErrTokenRequiredClaimMissing, + }, + { + name: "expected sub mismatch", + fields: fields{expectedSub: "me"}, + args: args{RegisteredClaims{Subject: "not-me"}}, + wantErr: ErrTokenInvalidSubject, + }, + { + name: "expected sub is missing", + fields: fields{expectedSub: "me"}, + args: args{RegisteredClaims{}}, + wantErr: ErrTokenRequiredClaimMissing, + }, + { + name: "custom validator", + fields: fields{}, + args: args{MyCustomClaims{Foo: "not-bar"}}, + wantErr: ErrFooBar, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := &validator{ + leeway: tt.fields.leeway, + timeFunc: tt.fields.timeFunc, + verifyIat: tt.fields.verifyIat, + expectedAud: tt.fields.expectedAud, + expectedIss: tt.fields.expectedIss, + expectedSub: tt.fields.expectedSub, + } + if err := v.Validate(tt.args.claims); (err != nil) && !errors.Is(err, tt.wantErr) { + t.Errorf("validator.Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_validator_verifyExpiresAt(t *testing.T) { + type fields struct { + leeway time.Duration + timeFunc func() time.Time + } + type args struct { + claims Claims + cmp time.Time + required bool + } + tests := []struct { + name string + fields fields + args args + wantErr error + }{ + { + name: "good claim", + fields: fields{timeFunc: time.Now}, + args: args{claims: RegisteredClaims{ExpiresAt: NewNumericDate(time.Now().Add(10 * time.Minute))}}, + wantErr: nil, + }, + { + name: "claims with invalid type", + fields: fields{}, + args: args{claims: MapClaims{"exp": "string"}}, + wantErr: ErrInvalidType, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := &validator{ + leeway: tt.fields.leeway, + timeFunc: tt.fields.timeFunc, + } + + err := v.verifyExpiresAt(tt.args.claims, tt.args.cmp, tt.args.required) + if (err != nil) && !errors.Is(err, tt.wantErr) { + t.Errorf("validator.verifyExpiresAt() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_validator_verifyIssuer(t *testing.T) { + type fields struct { + expectedIss string + } + type args struct { + claims Claims + cmp string + required bool + } + tests := []struct { + name string + fields fields + args args + wantErr error + }{ + { + name: "good claim", + fields: fields{expectedIss: "me"}, + args: args{claims: MapClaims{"iss": "me"}, cmp: "me"}, + wantErr: nil, + }, + { + name: "claims with invalid type", + fields: fields{expectedIss: "me"}, + args: args{claims: MapClaims{"iss": 1}, cmp: "me"}, + wantErr: ErrInvalidType, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := &validator{ + expectedIss: tt.fields.expectedIss, + } + err := v.verifyIssuer(tt.args.claims, tt.args.cmp, tt.args.required) + if (err != nil) && !errors.Is(err, tt.wantErr) { + t.Errorf("validator.verifyIssuer() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_validator_verifySubject(t *testing.T) { + type fields struct { + expectedSub string + } + type args struct { + claims Claims + cmp string + required bool + } + tests := []struct { + name string + fields fields + args args + wantErr error + }{ + { + name: "good claim", + fields: fields{expectedSub: "me"}, + args: args{claims: MapClaims{"sub": "me"}, cmp: "me"}, + wantErr: nil, + }, + { + name: "claims with invalid type", + fields: fields{expectedSub: "me"}, + args: args{claims: MapClaims{"sub": 1}, cmp: "me"}, + wantErr: ErrInvalidType, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := &validator{ + expectedSub: tt.fields.expectedSub, + } + err := v.verifySubject(tt.args.claims, tt.args.cmp, tt.args.required) + if (err != nil) && !errors.Is(err, tt.wantErr) { + t.Errorf("validator.verifySubject() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_validator_verifyIssuedAt(t *testing.T) { + type fields struct { + leeway time.Duration + timeFunc func() time.Time + verifyIat bool + } + type args struct { + claims Claims + cmp time.Time + required bool + } + tests := []struct { + name string + fields fields + args args + wantErr error + }{ + { + name: "good claim without iat", + fields: fields{verifyIat: true}, + args: args{claims: MapClaims{}, required: false}, + wantErr: nil, + }, + { + name: "good claim with iat", + fields: fields{verifyIat: true}, + args: args{ + claims: RegisteredClaims{IssuedAt: NewNumericDate(time.Now())}, + cmp: time.Now().Add(10 * time.Minute), + required: false, + }, + wantErr: nil, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + v := &validator{ + leeway: tt.fields.leeway, + timeFunc: tt.fields.timeFunc, + verifyIat: tt.fields.verifyIat, + } + if err := v.verifyIssuedAt(tt.args.claims, tt.args.cmp, tt.args.required); (err != nil) && !errors.Is(err, tt.wantErr) { + t.Errorf("validator.verifyIssuedAt() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} From 0d2f0d4809b8a7e01b0cb27cbfde79a69cb2a298 Mon Sep 17 00:00:00 2001 From: Mones Zarrugh Date: Wed, 22 Feb 2023 04:28:00 +0200 Subject: [PATCH 03/14] remove string slice and strings.join (#115) --- token.go | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/token.go b/token.go index b3459427..85350b1e 100644 --- a/token.go +++ b/token.go @@ -63,35 +63,34 @@ func NewWithClaims(method SigningMethod, claims Claims) *Token { // SignedString creates and returns a complete, signed JWT. The token is signed // using the SigningMethod specified in the token. func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { + sstr, err := t.SigningString() + if err != nil { return "", err } - if sig, err = t.Method.Sign(sstr, key); err != nil { + + sig, err := t.Method.Sign(sstr, key) + if err != nil { return "", err } - return strings.Join([]string{sstr, sig}, "."), nil + + return sstr + "." + sig, nil } // SigningString generates the signing string. This is the most expensive part // of the whole deal. Unless you need this for something special, just go // straight for the SignedString. func (t *Token) SigningString() (string, error) { - var err error - var jsonValue []byte - - if jsonValue, err = json.Marshal(t.Header); err != nil { + h, err := json.Marshal(t.Header) + if err != nil { return "", err } - header := EncodeSegment(jsonValue) - if jsonValue, err = json.Marshal(t.Claims); err != nil { + c, err := json.Marshal(t.Claims) + if err != nil { return "", err } - claim := EncodeSegment(jsonValue) - return strings.Join([]string{header, claim}, "."), nil + return EncodeSegment(h) + "." + EncodeSegment(c), nil } // Parse parses, validates, verifies the signature and returns the parsed token. From c6ec5a22b4df47488745c7a902671dafd8edfe90 Mon Sep 17 00:00:00 2001 From: Liam Newman <96086065+liam-verta@users.noreply.github.com> Date: Fri, 24 Mar 2023 11:10:52 -0700 Subject: [PATCH 04/14] Update MIGRATION_GUIDE.md (#289) * Update MIGRATION_GUIDE.md Saw one typo, spent a few minutes improving a few paragraphs. --- MIGRATION_GUIDE.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 1ee690f9..09a1c672 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -9,17 +9,17 @@ Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), t "github.com/golang-jwt/jwt/v5" For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of -the public API, existing programs might need to be adopted. The following paragraphs go through the individual changes -and make suggestions how to change existing programs. +the public API, existing programs might need to be updated. The following sections describe significant changes +and corresponding updates for existing programs. ## Parsing and Validation Options Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: - * `WithLeeway`, which can be used to specific leeway that is taken into account when validating time-based claims, such as `exp` or `nbf`. - * The new default behavior now disables checking the `iat` claim by default. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. - * New options have also been added to check for expected `aud`, `sub` and `iss`, namely `WithAudience`, `WithSubject` and `WithIssuer`. + * Added `WithLeeway` to support specifying the leeway that is allowed when validating time-based claims, such as `exp` or `nbf`. + * Changed default behavior to not check the `iat` claim. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. + * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for expected `aud`, `sub` and `iss`. ## Changes to the `Claims` interface From b357385d3ee5c53c16db81addf9c6c8059c4cf15 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Fri, 24 Mar 2023 19:13:09 +0100 Subject: [PATCH 05/14] Moving `DecodeSegement` to `Parser` (#278) * Moving `DecodeSegement` to `Parser` This would allow us to remove some global variables and move them to parser options as well as potentially introduce interfaces for json and b64 encoding/decoding to replace the std lib, if someone wanted to do that for performance reasons. We keep the functions exported because of explicit user demand. * Sign/Verify does take the decoded form now --- ecdsa.go | 22 ++++------- ecdsa_test.go | 26 ++++++++++--- ed25519.go | 25 +++++-------- ed25519_test.go | 8 ++-- hmac.go | 16 +++----- hmac_test.go | 5 ++- none.go | 11 +++--- none_test.go | 5 ++- parser.go | 57 +++++++++++++++++++++++++++-- parser_option.go | 26 +++++++++++++ parser_test.go | 20 ++++++---- rsa.go | 20 +++------- rsa_pss.go | 20 +++------- rsa_pss_test.go | 22 ++++++----- rsa_test.go | 9 +++-- signing_method.go | 11 ++++-- token.go | 93 ++++++++--------------------------------------- token_option.go | 5 +++ token_test.go | 7 ++-- 19 files changed, 212 insertions(+), 196 deletions(-) create mode 100644 token_option.go diff --git a/ecdsa.go b/ecdsa.go index eac023fc..4ccae2a8 100644 --- a/ecdsa.go +++ b/ecdsa.go @@ -55,15 +55,7 @@ func (m *SigningMethodECDSA) Alg() string { // Verify implements token verification for the SigningMethod. // For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { // Get the key var ecdsaKey *ecdsa.PublicKey switch k := key.(type) { @@ -97,19 +89,19 @@ func (m *SigningMethodECDSA) Verify(signingString, signature string, key interfa // Sign implements token signing for the SigningMethod. // For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { // Get the key var ecdsaKey *ecdsa.PrivateKey switch k := key.(type) { case *ecdsa.PrivateKey: ecdsaKey = k default: - return "", ErrInvalidKeyType + return nil, ErrInvalidKeyType } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -120,7 +112,7 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { - return "", ErrInvalidKey + return nil, ErrInvalidKey } keyBytes := curveBits / 8 @@ -135,8 +127,8 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. - return EncodeSegment(out), nil + return out, nil } else { - return "", err + return nil, err } } diff --git a/ecdsa_test.go b/ecdsa_test.go index 7c6d4829..3caf0a89 100644 --- a/ecdsa_test.go +++ b/ecdsa_test.go @@ -3,6 +3,7 @@ package jwt_test import ( "crypto/ecdsa" "os" + "reflect" "strings" "testing" @@ -65,7 +66,7 @@ func TestECDSAVerify(t *testing.T) { parts := strings.Split(data.tokenString, ".") method := jwt.GetSigningMethod(data.alg) - err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ecdsaKey) + err = method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), ecdsaKey) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -90,12 +91,13 @@ func TestECDSASign(t *testing.T) { toSign := strings.Join(parts[0:2], ".") method := jwt.GetSigningMethod(data.alg) sig, err := method.Sign(toSign, ecdsaKey) - if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig == parts[2] { - t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) + + ssig := encodeSegment(sig) + if ssig == parts[2] { + t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], ssig) } err = method.Verify(toSign, sig, ecdsaKey.Public()) @@ -155,10 +157,24 @@ func BenchmarkECDSASigning(b *testing.B) { if err != nil { b.Fatalf("[%v] Error signing token: %v", data.name, err) } - if sig == parts[2] { + if reflect.DeepEqual(sig, decodeSegment(b, parts[2])) { b.Fatalf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) } } }) } } + +func decodeSegment(t interface{ Fatalf(string, ...any) }, signature string) (sig []byte) { + var err error + sig, err = jwt.NewParser().DecodeSegment(signature) + if err != nil { + t.Fatalf("could not decode segment: %v", err) + } + + return +} + +func encodeSegment(sig []byte) string { + return (&jwt.Token{}).EncodeSegment(sig) +} diff --git a/ed25519.go b/ed25519.go index 07d3aacd..3db00e4a 100644 --- a/ed25519.go +++ b/ed25519.go @@ -34,8 +34,7 @@ func (m *SigningMethodEd25519) Alg() string { // Verify implements token verification for the SigningMethod. // For this verify method, key must be an ed25519.PublicKey -func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error { - var err error +func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { var ed25519Key ed25519.PublicKey var ok bool @@ -47,12 +46,6 @@ func (m *SigningMethodEd25519) Verify(signingString, signature string, key inter return ErrInvalidKey } - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - // Verify the signature if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { return ErrEd25519Verification @@ -63,23 +56,25 @@ func (m *SigningMethodEd25519) Verify(signingString, signature string, key inter // Sign implements token signing for the SigningMethod. // For this signing method, key must be an ed25519.PrivateKey -func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { var ed25519Key crypto.Signer var ok bool if ed25519Key, ok = key.(crypto.Signer); !ok { - return "", ErrInvalidKeyType + return nil, ErrInvalidKeyType } if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { - return "", ErrInvalidKey + return nil, ErrInvalidKey } - // Sign the string and return the encoded result - // ed25519 performs a two-pass hash as part of its algorithm. Therefore, we need to pass a non-prehashed message into the Sign function, as indicated by crypto.Hash(0) + // Sign the string and return the result. ed25519 performs a two-pass hash + // as part of its algorithm. Therefore, we need to pass a non-prehashed + // message into the Sign function, as indicated by crypto.Hash(0) sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) if err != nil { - return "", err + return nil, err } - return EncodeSegment(sig), nil + + return sig, nil } diff --git a/ed25519_test.go b/ed25519_test.go index cd058183..e9c7432e 100644 --- a/ed25519_test.go +++ b/ed25519_test.go @@ -49,7 +49,7 @@ func TestEd25519Verify(t *testing.T) { method := jwt.GetSigningMethod(data.alg) - err = method.Verify(strings.Join(parts[0:2], "."), parts[2], ed25519Key) + err = method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), ed25519Key) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -77,8 +77,10 @@ func TestEd25519Sign(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig == parts[2] && !data.valid { - t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], sig) + + ssig := encodeSegment(sig) + if ssig == parts[2] && !data.valid { + t.Errorf("[%v] Identical signatures\nbefore:\n%v\nafter:\n%v", data.name, parts[2], ssig) } } } diff --git a/hmac.go b/hmac.go index 011f68a2..8609f4a8 100644 --- a/hmac.go +++ b/hmac.go @@ -46,19 +46,13 @@ func (m *SigningMethodHMAC) Alg() string { } // Verify implements token verification for the SigningMethod. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { +func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { // Verify the key is the right type keyBytes, ok := key.([]byte) if !ok { return ErrInvalidKeyType } - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - // Can we use the specified hashing method? if !m.Hash.Available() { return ErrHashUnavailable @@ -79,17 +73,17 @@ func (m *SigningMethodHMAC) Verify(signingString, signature string, key interfac // Sign implements token signing for the SigningMethod. // Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { if keyBytes, ok := key.([]byte); ok { if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := hmac.New(m.Hash.New, keyBytes) hasher.Write([]byte(signingString)) - return EncodeSegment(hasher.Sum(nil)), nil + return hasher.Sum(nil), nil } - return "", ErrInvalidKeyType + return nil, ErrInvalidKeyType } diff --git a/hmac_test.go b/hmac_test.go index 83d2c3eb..264a2a42 100644 --- a/hmac_test.go +++ b/hmac_test.go @@ -2,6 +2,7 @@ package jwt_test import ( "os" + "reflect" "strings" "testing" @@ -53,7 +54,7 @@ func TestHMACVerify(t *testing.T) { parts := strings.Split(data.tokenString, ".") method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], hmacTestKey) + err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), hmacTestKey) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -72,7 +73,7 @@ func TestHMACSign(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig != parts[2] { + if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) } } diff --git a/none.go b/none.go index a16495ac..c93daa58 100644 --- a/none.go +++ b/none.go @@ -25,14 +25,14 @@ func (m *signingMethodNone) Alg() string { } // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { +func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { // Key must be UnsafeAllowNoneSignatureType to prevent accidentally // accepting 'none' signing method if _, ok := key.(unsafeNoneMagicConstant); !ok { return NoneSignatureTypeDisallowedError } // If signing method is none, signature must be an empty string - if signature != "" { + if string(sig) != "" { return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) } @@ -41,9 +41,10 @@ func (m *signingMethodNone) Verify(signingString, signature string, key interfac } // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { +func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil + return []byte{}, nil } - return "", NoneSignatureTypeDisallowedError + + return nil, NoneSignatureTypeDisallowedError } diff --git a/none_test.go b/none_test.go index 35ff13af..d370cf8c 100644 --- a/none_test.go +++ b/none_test.go @@ -1,6 +1,7 @@ package jwt_test import ( + "reflect" "strings" "testing" @@ -46,7 +47,7 @@ func TestNoneVerify(t *testing.T) { parts := strings.Split(data.tokenString, ".") method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], data.key) + err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), data.key) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -65,7 +66,7 @@ func TestNoneSign(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig != parts[2] { + if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) } } diff --git a/parser.go b/parser.go index 46b67931..f4386fba 100644 --- a/parser.go +++ b/parser.go @@ -2,6 +2,7 @@ package jwt import ( "bytes" + "encoding/base64" "encoding/json" "fmt" "strings" @@ -18,6 +19,10 @@ type Parser struct { skipClaimsValidation bool validator *validator + + decodeStrict bool + + decodePaddingAllowed bool } // NewParser creates a new Parser with the specified options @@ -79,8 +84,13 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) } + // Decode signature + token.Signature, err = p.DecodeSegment(parts[2]) + if err != nil { + return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + } + // Perform signature validation - token.Signature = parts[2] if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { return token, newError("", ErrTokenSignatureInvalid, err) } @@ -119,7 +129,7 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke // parse Header var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) } @@ -133,7 +143,7 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke var claimBytes []byte token.Claims = claims - if claimBytes, err = DecodeSegment(parts[1]); err != nil { + if claimBytes, err = p.DecodeSegment(parts[1]); err != nil { return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) } dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) @@ -162,3 +172,44 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke return token, parts, nil } + +// DecodeSegment decodes a JWT specific base64url encoding. This function will +// take into account whether the [Parser] is configured with additional options, +// such as [WithStrictDecoding] or [WithPaddingAllowed]. +func (p *Parser) DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding + + if p.decodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } + + if p.decodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the cryptographic key +// for verifying the signature. The caller is strongly encouraged to set the +// WithValidMethods option to validate the 'alg' claim in the token matches the +// expected algorithm. For more details about the importance of validating the +// 'alg' claim, see +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) +} + +// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). +// +// Note: If you provide a custom claim implementation that embeds one of the +// standard claims (such as RegisteredClaims), make sure that a) you either +// embed a non-pointer version of the claims or b) if you are using a pointer, +// allocate the proper memory for it before passing in the overall claims, +// otherwise you might run into a panic. +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) +} diff --git a/parser_option.go b/parser_option.go index 8d5917e9..3ad17bc6 100644 --- a/parser_option.go +++ b/parser_option.go @@ -99,3 +99,29 @@ func WithSubject(sub string) ParserOption { p.validator.expectedSub = sub } } + +// WithPaddingAllowed will enable the codec used for decoding JWTs to allow +// padding. Note that the JWS RFC7515 states that the tokens will utilize a +// Base64url encoding with no padding. Unfortunately, some implementations of +// JWT are producing non-standard tokens, and thus require support for decoding. +// Note that this is a global variable, and updating it will change the behavior +// on a package level, and is also NOT go-routine safe. To use the +// non-recommended decoding, set this boolean to `true` prior to using this +// package. +func WithPaddingAllowed() ParserOption { + return func(p *Parser) { + p.decodePaddingAllowed = true + } +} + +// WithStrictDecoding will switch the codec used for decoding JWTs into strict +// mode. In this mode, the decoder requires that trailing padding bits are zero, +// as described in RFC 4648 section 3.5. Note that this is a global variable, +// and updating it will change the behavior on a package level, and is also NOT +// go-routine safe. To use strict decoding, set this boolean to `true` prior to +// using this package. +func WithStrictDecoding() ParserOption { + return func(p *Parser) { + p.decodeStrict = true + } +} diff --git a/parser_test.go b/parser_test.go index fdb5eef3..5b912b15 100644 --- a/parser_test.go +++ b/parser_test.go @@ -415,7 +415,7 @@ func TestParser_Parse(t *testing.T) { } if data.valid { - if token.Signature == "" { + if len(token.Signature) == 0 { t.Errorf("[%v] Signature is left unpopulated after parsing", data.name) } if !token.Valid { @@ -473,7 +473,7 @@ func TestParser_ParseUnverified(t *testing.T) { // The 'Valid' field should not be set to true when invoking ParseUnverified() t.Errorf("[%v] Token.Valid field mismatch. Expecting false, got %v", data.name, token.Valid) } - if token.Signature != "" { + if len(token.Signature) != 0 { // The signature was not validated, hence the 'Signature' field is not populated. t.Errorf("[%v] Token.Signature field mismatch. Expecting '', got %v", data.name, token.Signature) } @@ -641,9 +641,6 @@ var setPaddingTestData = []struct { func TestSetPadding(t *testing.T) { for _, data := range setPaddingTestData { t.Run(data.name, func(t *testing.T) { - jwt.DecodePaddingAllowed = data.paddedDecode - jwt.DecodeStrict = data.strictDecode - // If the token string is blank, use helper function to generate string if data.tokenString == "" { data.tokenString = signToken(data.claims, data.signingMethod) @@ -652,7 +649,16 @@ func TestSetPadding(t *testing.T) { // Parse the token var token *jwt.Token var err error - parser := jwt.NewParser(jwt.WithoutClaimsValidation()) + var opts []jwt.ParserOption = []jwt.ParserOption{jwt.WithoutClaimsValidation()} + + if data.paddedDecode { + opts = append(opts, jwt.WithPaddingAllowed()) + } + if data.strictDecode { + opts = append(opts, jwt.WithStrictDecoding()) + } + + parser := jwt.NewParser(opts...) // Figure out correct claims type token, err = parser.ParseWithClaims(data.tokenString, jwt.MapClaims{}, data.keyfunc) @@ -666,8 +672,6 @@ func TestSetPadding(t *testing.T) { } }) - jwt.DecodePaddingAllowed = false - jwt.DecodeStrict = false } } diff --git a/rsa.go b/rsa.go index b910b19c..daff0943 100644 --- a/rsa.go +++ b/rsa.go @@ -46,15 +46,7 @@ func (m *SigningMethodRSA) Alg() string { // Verify implements token verification for the SigningMethod // For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey var ok bool @@ -75,18 +67,18 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface // Sign implements token signing for the SigningMethod // For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey var ok bool // Validate type of key if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey + return nil, ErrInvalidKey } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -94,8 +86,8 @@ func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/rsa_pss.go b/rsa_pss.go index 4fd6f9e6..9599f0a4 100644 --- a/rsa_pss.go +++ b/rsa_pss.go @@ -82,15 +82,7 @@ func init() { // Verify implements token verification for the SigningMethod. // For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey switch k := key.(type) { case *rsa.PublicKey: @@ -116,19 +108,19 @@ func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interf // Sign implements token signing for the SigningMethod. // For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey switch k := key.(type) { case *rsa.PrivateKey: rsaKey = k default: - return "", ErrInvalidKeyType + return nil, ErrInvalidKeyType } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -136,8 +128,8 @@ func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (strin // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/rsa_pss_test.go b/rsa_pss_test.go index 1c3d9ea5..9707a755 100644 --- a/rsa_pss_test.go +++ b/rsa_pss_test.go @@ -64,7 +64,7 @@ func TestRSAPSSVerify(t *testing.T) { parts := strings.Split(data.tokenString, ".") method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey) + err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), rsaPSSKey) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -91,8 +91,10 @@ func TestRSAPSSSign(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig == parts[2] { - t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, sig, parts[2]) + + ssig := encodeSegment(sig) + if ssig == parts[2] { + t.Errorf("[%v] Signatures shouldn't match\nnew:\n%v\noriginal:\n%v", data.name, ssig, parts[2]) } } } @@ -114,19 +116,19 @@ func TestRSAPSSSaltLengthCompatibility(t *testing.T) { SaltLength: rsa.PSSSaltLengthAuto, }, } - if !verify(jwt.SigningMethodPS256, makeToken(ps256SaltLengthEqualsHash)) { + if !verify(t, jwt.SigningMethodPS256, makeToken(ps256SaltLengthEqualsHash)) { t.Error("SigningMethodPS256 should accept salt length that is defined in RFC") } - if !verify(ps256SaltLengthEqualsHash, makeToken(jwt.SigningMethodPS256)) { + if !verify(t, ps256SaltLengthEqualsHash, makeToken(jwt.SigningMethodPS256)) { t.Error("Sign by SigningMethodPS256 should have salt length that is defined in RFC") } - if !verify(jwt.SigningMethodPS256, makeToken(ps256SaltLengthAuto)) { + if !verify(t, jwt.SigningMethodPS256, makeToken(ps256SaltLengthAuto)) { t.Error("SigningMethodPS256 should accept auto salt length to be compatible with previous versions") } - if !verify(ps256SaltLengthAuto, makeToken(jwt.SigningMethodPS256)) { + if !verify(t, ps256SaltLengthAuto, makeToken(jwt.SigningMethodPS256)) { t.Error("Sign by SigningMethodPS256 should be accepted by previous versions") } - if verify(ps256SaltLengthEqualsHash, makeToken(ps256SaltLengthAuto)) { + if verify(t, ps256SaltLengthEqualsHash, makeToken(ps256SaltLengthAuto)) { t.Error("Auto salt length should be not accepted, when RFC salt length is required") } } @@ -144,8 +146,8 @@ func makeToken(method jwt.SigningMethod) string { return signed } -func verify(signingMethod jwt.SigningMethod, token string) bool { +func verify(t *testing.T, signingMethod jwt.SigningMethod, token string) bool { segments := strings.Split(token, ".") - err := signingMethod.Verify(strings.Join(segments[:2], "."), segments[2], test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")) + err := signingMethod.Verify(strings.Join(segments[:2], "."), decodeSegment(t, segments[2]), test.LoadRSAPublicKeyFromDisk("test/sample_key.pub")) return err == nil } diff --git a/rsa_test.go b/rsa_test.go index 8ca6e7a1..cba41001 100644 --- a/rsa_test.go +++ b/rsa_test.go @@ -2,6 +2,7 @@ package jwt_test import ( "os" + "reflect" "strings" "testing" @@ -48,7 +49,7 @@ func TestRSAVerify(t *testing.T) { parts := strings.Split(data.tokenString, ".") method := jwt.GetSigningMethod(data.alg) - err := method.Verify(strings.Join(parts[0:2], "."), parts[2], key) + err := method.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), key) if data.valid && err != nil { t.Errorf("[%v] Error while verifying key: %v", data.name, err) } @@ -70,7 +71,7 @@ func TestRSASign(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", data.name, err) } - if sig != parts[2] { + if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", data.name, sig, parts[2]) } } @@ -85,7 +86,7 @@ func TestRSAVerifyWithPreParsedPrivateKey(t *testing.T) { } testData := rsaTestData[0] parts := strings.Split(testData.tokenString, ".") - err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), parts[2], parsedKey) + err = jwt.SigningMethodRS256.Verify(strings.Join(parts[0:2], "."), decodeSegment(t, parts[2]), parsedKey) if err != nil { t.Errorf("[%v] Error while verifying key: %v", testData.name, err) } @@ -103,7 +104,7 @@ func TestRSAWithPreParsedPrivateKey(t *testing.T) { if err != nil { t.Errorf("[%v] Error signing token: %v", testData.name, err) } - if sig != parts[2] { + if !reflect.DeepEqual(sig, decodeSegment(t, parts[2])) { t.Errorf("[%v] Incorrect signature.\nwas:\n%v\nexpecting:\n%v", testData.name, sig, parts[2]) } } diff --git a/signing_method.go b/signing_method.go index 241ae9c6..0d73631c 100644 --- a/signing_method.go +++ b/signing_method.go @@ -7,11 +7,14 @@ import ( var signingMethods = map[string]func() SigningMethod{} var signingMethodLock = new(sync.RWMutex) -// SigningMethod can be used add new methods for signing or verifying tokens. +// SigningMethod can be used add new methods for signing or verifying tokens. It +// takes a decoded signature as an input in the Verify function and produces a +// signature in Sign. The signature is then usually base64 encoded as part of a +// JWT. type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') + Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') } // RegisterSigningMethod registers the "alg" name and a factory function for signing method. diff --git a/token.go b/token.go index 85350b1e..163c02f1 100644 --- a/token.go +++ b/token.go @@ -3,27 +3,8 @@ package jwt import ( "encoding/base64" "encoding/json" - "strings" ) -// DecodePaddingAllowed will switch the codec used for decoding JWTs -// respectively. Note that the JWS RFC7515 states that the tokens will utilize a -// Base64url encoding with no padding. Unfortunately, some implementations of -// JWT are producing non-standard tokens, and thus require support for decoding. -// Note that this is a global variable, and updating it will change the behavior -// on a package level, and is also NOT go-routine safe. To use the -// non-recommended decoding, set this boolean to `true` prior to using this -// package. -var DecodePaddingAllowed bool - -// DecodeStrict will switch the codec used for decoding JWTs into strict mode. -// In this mode, the decoder requires that trailing padding bits are zero, as -// described in RFC 4648 section 3.5. Note that this is a global variable, and -// updating it will change the behavior on a package level, and is also NOT -// go-routine safe. To use strict decoding, set this boolean to `true` prior to -// using this package. -var DecodeStrict bool - // Keyfunc will be used by the Parse methods as a callback function to supply // the key for verification. The function receives the parsed, but unverified // Token. This allows you to use properties in the Header of the token (such as @@ -35,21 +16,21 @@ type Keyfunc func(*Token) (interface{}, error) type Token struct { Raw string // Raw contains the raw token. Populated when you [Parse] a token Method SigningMethod // Method is the signing method used or to be used - Header map[string]interface{} // Header is the first segment of the token - Claims Claims // Claims is the second segment of the token - Signature string // Signature is the third segment of the token. Populated when you Parse a token + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token } -// New creates a new [Token] with the specified signing method and an empty map of -// claims. -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) +// New creates a new [Token] with the specified signing method and an empty map +// of claims. Additional options can be specified, but are currently unused. +func New(method SigningMethod, opts ...TokenOption) *Token { + return NewWithClaims(method, MapClaims{}, opts...) } // NewWithClaims creates a new [Token] with the specified signing method and -// claims. -func NewWithClaims(method SigningMethod, claims Claims) *Token { +// claims. Additional options can be specified, but are currently unused. +func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { return &Token{ Header: map[string]interface{}{ "typ": "JWT", @@ -73,7 +54,7 @@ func (t *Token) SignedString(key interface{}) (string, error) { return "", err } - return sstr + "." + sig, nil + return sstr + "." + t.EncodeSegment(sig), nil } // SigningString generates the signing string. This is the most expensive part @@ -90,55 +71,13 @@ func (t *Token) SigningString() (string, error) { return "", err } - return EncodeSegment(h) + "." + EncodeSegment(c), nil -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. The caller is strongly encouraged to set the -// WithValidMethods option to validate the 'alg' claim in the token matches the -// expected algorithm. For more details about the importance of validating the -// 'alg' claim, see -// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ -func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).Parse(tokenString, keyFunc) -} - -// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). -// -// Note: If you provide a custom claim implementation that embeds one of the -// standard claims (such as RegisteredClaims), make sure that a) you either -// embed a non-pointer version of the claims or b) if you are using a pointer, -// allocate the proper memory for it before passing in the overall claims, -// otherwise you might run into a panic. -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) + return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil } -// EncodeSegment encodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a -// non-exported function, since it should only be used internally -func EncodeSegment(seg []byte) string { +// EncodeSegment encodes a JWT specific base64url encoding with padding +// stripped. In the future, this function might take into account a +// [TokenOption]. Therefore, this function exists as a method of [Token], rather +// than a global function. +func (*Token) EncodeSegment(seg []byte) string { return base64.RawURLEncoding.EncodeToString(seg) } - -// DecodeSegment decodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a -// non-exported function, since it should only be used internally -func DecodeSegment(seg string) ([]byte, error) { - encoding := base64.RawURLEncoding - - if DecodePaddingAllowed { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - encoding = base64.URLEncoding - } - - if DecodeStrict { - encoding = encoding.Strict() - } - return encoding.DecodeString(seg) -} diff --git a/token_option.go b/token_option.go new file mode 100644 index 00000000..b4ae3bad --- /dev/null +++ b/token_option.go @@ -0,0 +1,5 @@ +package jwt + +// TokenOption is a reserved type, which provides some forward compatibility, +// if we ever want to introduce token creation-related options. +type TokenOption func(*Token) diff --git a/token_test.go b/token_test.go index 52a00212..95709ade 100644 --- a/token_test.go +++ b/token_test.go @@ -12,7 +12,7 @@ func TestToken_SigningString(t1 *testing.T) { Method jwt.SigningMethod Header map[string]interface{} Claims jwt.Claims - Signature string + Signature []byte Valid bool } tests := []struct { @@ -30,9 +30,8 @@ func TestToken_SigningString(t1 *testing.T) { "typ": "JWT", "alg": jwt.SigningMethodHS256.Alg(), }, - Claims: jwt.RegisteredClaims{}, - Signature: "", - Valid: false, + Claims: jwt.RegisteredClaims{}, + Valid: false, }, want: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30", wantErr: false, From 1c4047f488ec4e73d7b6ffafd7bff78ab82a1cc4 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Fri, 24 Mar 2023 23:11:38 +0100 Subject: [PATCH 06/14] Adjusting the error checking example (#270) This PR adjusts the error checking example so that a check for an invalid signature is also included. See discussion in #143 --- example_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/example_test.go b/example_test.go index 58fdea43..abf7efab 100644 --- a/example_test.go +++ b/example_test.go @@ -164,6 +164,9 @@ func ExampleParse_errorChecking() { fmt.Println("You look nice today") } else if errors.Is(err, jwt.ErrTokenMalformed) { fmt.Println("That's not even a token") + } else if errors.Is(err, jwt.ErrTokenSignatureInvalid) { + // Invalid signature + fmt.Println("Invalid signature") } else if errors.Is(err, jwt.ErrTokenExpired) || errors.Is(err, jwt.ErrTokenNotValidYet) { // Token is either expired or not active yet fmt.Println("Timing is everything") From 843e9bfe4d28d74b95dee953c41db603123aeeba Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Fri, 31 Mar 2023 06:19:48 -0500 Subject: [PATCH 07/14] add documentation to hmac `Verify` & `Sign` to detail why string is not an advisable input for key (#249) * add documentation around Verify & Sign to detail why string is not an advisable input for key * Refer to the usage guide --------- Co-authored-by: Dillon Streator Co-authored-by: Christian Banse --- hmac.go | 21 ++++++++++++++++++--- token.go | 5 ++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/hmac.go b/hmac.go index 8609f4a8..91b688ba 100644 --- a/hmac.go +++ b/hmac.go @@ -45,7 +45,16 @@ func (m *SigningMethodHMAC) Alg() string { return m.Name } -// Verify implements token verification for the SigningMethod. Returns nil if the signature is valid. +// Verify implements token verification for the SigningMethod. Returns nil if +// the signature is valid. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { // Verify the key is the right type keyBytes, ok := key.([]byte) @@ -71,8 +80,14 @@ func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interfa return nil } -// Sign implements token signing for the SigningMethod. -// Key must be []byte +// Sign implements token signing for the SigningMethod. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { if keyBytes, ok := key.([]byte); ok { if !m.Hash.Available() { diff --git a/token.go b/token.go index 163c02f1..c8ad7c78 100644 --- a/token.go +++ b/token.go @@ -42,7 +42,10 @@ func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *To } // SignedString creates and returns a complete, signed JWT. The token is signed -// using the SigningMethod specified in the token. +// using the SigningMethod specified in the token. Please refer to +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types +// for an overview of the different signing methods and their respective key +// types. func (t *Token) SignedString(key interface{}) (string, error) { sstr, err := t.SigningString() if err != nil { From 15f96b06270d2cc0ffb92efbb80ddbc0eb7b7bae Mon Sep 17 00:00:00 2001 From: Michael Fridman Date: Fri, 31 Mar 2023 07:20:59 -0400 Subject: [PATCH 08/14] Add golangci-lint (#279) * Add golangci-lint-action * Upgrading CodeQL to v2 * Fixed linting errors --------- Co-authored-by: Christian Banse --- .github/workflows/build.yml | 14 +------ .github/workflows/codeql-analysis.yml | 60 +++++++++++++-------------- .github/workflows/lint.yml | 43 +++++++++++++++++++ example_test.go | 7 +++- http_example_test.go | 6 ++- request/extractor.go | 4 +- token_test.go | 2 +- 7 files changed, 85 insertions(+), 51 deletions(-) create mode 100644 .github/workflows/lint.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index efef789e..c4398c17 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,24 +8,12 @@ on: types: [opened, synchronize, reopened] jobs: - check: - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v3 - - uses: reviewdog/action-staticcheck@v1 - with: - github_token: ${{ secrets.github_token }} - reporter: github-pr-review - filter_mode: nofilter - fail_on_error: true - build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: - go: ["1.18", "1.19", "1.20"] + go: ["1.18.x", "1.19.x", "1.20.x"] steps: - name: Checkout uses: actions/checkout@v3 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 5b36162b..e82b45c6 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -13,12 +13,10 @@ name: "CodeQL" on: push: - branches: [ main ] - # pull_request: - # The branches below must be a subset of the branches above - # branches: [ main ] + branches: [main] + pull_request: schedule: - - cron: '31 10 * * 5' + - cron: "31 10 * * 5" jobs: analyze: @@ -32,40 +30,40 @@ jobs: strategy: fail-fast: false matrix: - language: [ 'go' ] + language: ["go"] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] # Learn more: # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed steps: - - name: Checkout repository - uses: actions/checkout@v2 + - name: Checkout repository + uses: actions/checkout@v2 - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language + # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language - #- run: | - # make bootstrap - # make release + #- run: | + # make bootstrap + # make release - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 00000000..55b1a8e1 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,43 @@ +name: golangci +on: + push: + branches: + - main + pull_request: +jobs: + golangci: + name: lint + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v3 + - name: Setup Go + uses: actions/setup-go@v3 + with: + go-version: "1.20.x" + check-latest: true + cache: true + - name: golangci-lint + uses: golangci/golangci-lint-action@v3 + with: + # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version + version: latest + + # Optional: working directory, useful for monorepos + # working-directory: somedir + + # Optional: golangci-lint command line arguments. + # args: --issues-exit-code=0 + + # Optional: show only new issues if it's a pull request. The default value is `false`. + # only-new-issues: true + + # Optional: if set to true then the all caching functionality will be complete disabled, + # takes precedence over all other caching options. + # skip-cache: true + + # Optional: if set to true then the action don't cache or restore ~/go/pkg. + # skip-pkg-cache: true + + # Optional: if set to true then the action don't cache or restore ~/.cache/go-build. + # skip-build-cache: true diff --git a/example_test.go b/example_test.go index abf7efab..f677d7c0 100644 --- a/example_test.go +++ b/example_test.go @@ -38,7 +38,7 @@ func ExampleNewWithClaims_customClaimsType() { jwt.RegisteredClaims } - // Create the claims + // Create claims with multiple fields populated claims := MyCustomClaims{ "bar", jwt.RegisteredClaims{ @@ -53,6 +53,8 @@ func ExampleNewWithClaims_customClaimsType() { }, } + fmt.Printf("foo: %v\n", claims.Foo) + // Create claims while leaving out some of the optional fields claims = MyCustomClaims{ "bar", @@ -67,7 +69,8 @@ func ExampleNewWithClaims_customClaimsType() { ss, err := token.SignedString(mySigningKey) fmt.Printf("%v %v", ss, err) - //Output: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM + //Output: foo: bar + //eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpc3MiOiJ0ZXN0IiwiZXhwIjoxNTE2MjM5MDIyfQ.xVuY2FZ_MRXMIEgVQ7J-TFtaucVFRXUzHm9LmV41goM } // Example creating a token using a custom claims type. The RegisteredClaims is embedded diff --git a/http_example_test.go b/http_example_test.go index 090aa4f7..c09cc367 100644 --- a/http_example_test.go +++ b/http_example_test.go @@ -94,7 +94,8 @@ func Example_getTokenViaHTTP() { // Read the token out of the response body buf := new(bytes.Buffer) - io.Copy(buf, res.Body) + _, err = io.Copy(buf, res.Body) + fatal(err) res.Body.Close() tokenString := strings.TrimSpace(buf.String()) @@ -129,7 +130,8 @@ func Example_useTokenViaHTTP() { // Read the response body buf := new(bytes.Buffer) - io.Copy(buf, res.Body) + _, err = io.Copy(buf, res.Body) + fatal(err) res.Body.Close() fmt.Println(buf.String()) diff --git a/request/extractor.go b/request/extractor.go index 57de8b77..780721b6 100644 --- a/request/extractor.go +++ b/request/extractor.go @@ -38,8 +38,8 @@ func (e HeaderExtractor) ExtractToken(req *http.Request) (string, error) { type ArgumentExtractor []string func (e ArgumentExtractor) ExtractToken(req *http.Request) (string, error) { - // Make sure form is parsed - req.ParseMultipartForm(10e6) + // Make sure form is parsed. We are explicitly ignoring errors at this point + _ = req.ParseMultipartForm(10e6) // loop over arg names and return the first one that contains data for _, arg := range e { diff --git a/token_test.go b/token_test.go index 95709ade..f18329e0 100644 --- a/token_test.go +++ b/token_test.go @@ -72,7 +72,7 @@ func BenchmarkToken_SigningString(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { - t.SigningString() + _, _ = t.SigningString() } }) } From 8cde7faf81fee53a7daff3372389029891e483fc Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Fri, 31 Mar 2023 13:26:46 +0200 Subject: [PATCH 09/14] Added dependabot updates for GitHub actions (#298) --- .github/dependabot.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..92c44a82 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" From 7342a71265e932a094d018172f217f66bced96dd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 31 Mar 2023 13:29:34 +0200 Subject: [PATCH 10/14] Bump actions/checkout from 2 to 3 (#299) Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v2...v3) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index e82b45c6..6210b814 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -37,7 +37,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v2 + uses: actions/checkout@v3 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL From b88a60f2d771b225195859f27dd5ae1901ffb483 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 31 Mar 2023 13:29:59 +0200 Subject: [PATCH 11/14] Bump actions/setup-go from 3 to 4 (#300) Bumps [actions/setup-go](https://github.com/actions/setup-go) from 3 to 4. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- .github/workflows/lint.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index c4398c17..97e9b4f7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -18,7 +18,7 @@ jobs: - name: Checkout uses: actions/checkout@v3 - name: Setup Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v4 with: go-version: "${{ matrix.go }}" check-latest: true diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 55b1a8e1..e6ef00ba 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -12,7 +12,7 @@ jobs: - name: Checkout code uses: actions/checkout@v3 - name: Setup Go - uses: actions/setup-go@v3 + uses: actions/setup-go@v4 with: go-version: "1.20.x" check-latest: true From 5ea71e36a0cf83ab89d29b405b6bad972eeebd20 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Mon, 10 Apr 2023 10:23:00 +0200 Subject: [PATCH 12/14] Added coverage reporting (#304) Co-authored-by: Michael Fridman --- .github/workflows/build.yml | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 97e9b4f7..0ab081f7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -32,8 +32,23 @@ jobs: fi - name: Build run: | - go install github.com/mfridman/tparse@latest + go install github.com/mfridman/tparse@latest go vet ./... go test -v -race -count=1 -json -coverpkg=$(go list ./...) ./... | tee output.json | tparse -follow -notests || true tparse -format markdown -file output.json -all > $GITHUB_STEP_SUMMARY go build ./... + coverage: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Setup Go + uses: actions/setup-go@v4 + - name: Coverage + run: | + go test -v -covermode=count -coverprofile=coverage.cov ./... + - name: Coveralls + uses: coverallsapp/github-action@v2 + with: + file: coverage.cov + format: golang From 6c9126f9c639633d29e0a48a4b13444707fa1e81 Mon Sep 17 00:00:00 2001 From: Christian Banse Date: Mon, 10 Apr 2023 10:33:52 +0200 Subject: [PATCH 13/14] Last Documentation cleanups for `v5` release (#291) * Updated MIGRATION_GUIDE.md after changes to Token and Parser * Updated doc * Cleanup of README and refer to project page * Update MIGRATION_GUIDE.md Co-authored-by: Michael Fridman * Wrapping markdown files at 80 --------- Co-authored-by: Michael Fridman --- MIGRATION_GUIDE.md | 143 +++++++++++++++++++++++++------- README.md | 201 ++++++++++++++++++++++++++------------------- parser_option.go | 9 +- 3 files changed, 230 insertions(+), 123 deletions(-) diff --git a/MIGRATION_GUIDE.md b/MIGRATION_GUIDE.md index 09a1c672..6ad1c22b 100644 --- a/MIGRATION_GUIDE.md +++ b/MIGRATION_GUIDE.md @@ -1,35 +1,61 @@ # Migration Guide (v5.0.0) -Version `v5` contains a major rework of core functionalities in the `jwt-go` library. This includes support for several -validation options as well as a re-design of the `Claims` interface. Lastly, we reworked how errors work under the hood, -which should provide a better overall developer experience. +Version `v5` contains a major rework of core functionalities in the `jwt-go` +library. This includes support for several validation options as well as a +re-design of the `Claims` interface. Lastly, we reworked how errors work under +the hood, which should provide a better overall developer experience. -Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), the import path will be: +Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), +the import path will be: "github.com/golang-jwt/jwt/v5" -For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of -the public API, existing programs might need to be updated. The following sections describe significant changes +For most users, changing the import path *should* suffice. However, since we +intentionally changed and cleaned some of the public API, existing programs +might need to be updated. The following sections describe significant changes and corresponding updates for existing programs. ## Parsing and Validation Options -Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option -to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended -to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: - * Added `WithLeeway` to support specifying the leeway that is allowed when validating time-based claims, such as `exp` or `nbf`. - * Changed default behavior to not check the `iat` claim. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. - * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for expected `aud`, `sub` and `iss`. +Under the hood, a new `validator` struct takes care of validating the claims. A +long awaited feature has been the option to fine-tune the validation of tokens. +This is now possible with several `ParserOption` functions that can be appended +to most `Parse` functions, such as `ParseWithClaims`. The most important options +and changes are: + * Added `WithLeeway` to support specifying the leeway that is allowed when + validating time-based claims, such as `exp` or `nbf`. + * Changed default behavior to not check the `iat` claim. Usage of this claim + is OPTIONAL according to the JWT RFC. The claim itself is also purely + informational according to the RFC, so a strict validation failure is not + recommended. If you want to check for sensible values in these claims, + please use the `WithIssuedAt` parser option. + * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for + expected `aud`, `sub` and `iss`. + * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow + previously global settings to enable base64 strict encoding and the parsing + of base64 strings with padding. The latter is strictly speaking against the + standard, but unfortunately some of the major identity providers issue some + of these incorrect tokens. Both options are disabled by default. ## Changes to the `Claims` interface ### Complete Restructuring -Previously, the claims interface was satisfied with an implementation of a `Valid() error` function. This had several issues: - * The different claim types (struct claims, map claims, etc.) then contained similar (but not 100 % identical) code of how this validation was done. This lead to a lot of (almost) duplicate code and was hard to maintain - * It was not really semantically close to what a "claim" (or a set of claims) really is; which is a list of defined key/value pairs with a certain semantic meaning. - -Since all the validation functionality is now extracted into the validator, all `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. Instead, the interface now represents a list of getters to retrieve values with a specific meaning. This allows us to completely decouple the validation logic with the underlying storage representation of the claim, which could be a struct, a map or even something stored in a database. +Previously, the claims interface was satisfied with an implementation of a +`Valid() error` function. This had several issues: + * The different claim types (struct claims, map claims, etc.) then contained + similar (but not 100 % identical) code of how this validation was done. This + lead to a lot of (almost) duplicate code and was hard to maintain + * It was not really semantically close to what a "claim" (or a set of claims) + really is; which is a list of defined key/value pairs with a certain + semantic meaning. + +Since all the validation functionality is now extracted into the validator, all +`VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. +Instead, the interface now represents a list of getters to retrieve values with +a specific meaning. This allows us to completely decouple the validation logic +with the underlying storage representation of the claim, which could be a +struct, a map or even something stored in a database. ```go type Claims interface { @@ -44,19 +70,32 @@ type Claims interface { ### Supported Claim Types and Removal of `StandardClaims` -The two standard claim types supported by this library, `MapClaims` and `RegisteredClaims` both implement the necessary functions of this interface. The old `StandardClaims` struct, which has already been deprecated in `v4` is now removed. +The two standard claim types supported by this library, `MapClaims` and +`RegisteredClaims` both implement the necessary functions of this interface. The +old `StandardClaims` struct, which has already been deprecated in `v4` is now +removed. -Users using custom claims, in most cases, will not experience any changes in the behavior as long as they embedded -`RegisteredClaims`. If they created a new claim type from scratch, they now need to implemented the proper getter +Users using custom claims, in most cases, will not experience any changes in the +behavior as long as they embedded `RegisteredClaims`. If they created a new +claim type from scratch, they now need to implemented the proper getter functions. ### Migrating Application Specific Logic of the old `Valid` -Previously, users could override the `Valid` method in a custom claim, for example to extend the validation with application-specific claims. However, this was always very dangerous, since once could easily disable the standard validation and signature checking. +Previously, users could override the `Valid` method in a custom claim, for +example to extend the validation with application-specific claims. However, this +was always very dangerous, since once could easily disable the standard +validation and signature checking. -In order to avoid that, while still supporting the use-case, a new `ClaimsValidator` interface has been introduced. This interface consists of the `Validate() error` function. If the validator sees, that a `Claims` struct implements this interface, the errors returned to the `Validate` function will be *appended* to the regular standard validation. It is not possible to disable the standard validation anymore (even only by accident). +In order to avoid that, while still supporting the use-case, a new +`ClaimsValidator` interface has been introduced. This interface consists of the +`Validate() error` function. If the validator sees, that a `Claims` struct +implements this interface, the errors returned to the `Validate` function will +be *appended* to the regular standard validation. It is not possible to disable +the standard validation anymore (even only by accident). -Usage examples can be found in [example_test.go](./example_test.go), to build claims structs like the following. +Usage examples can be found in [example_test.go](./example_test.go), to build +claims structs like the following. ```go // MyCustomClaims includes all registered claims, plus Foo. @@ -76,17 +115,62 @@ func (m MyCustomClaims) Validate() error { } ``` +## Changes to the `Token` and `Parser` struct + +The previously global functions `DecodeSegment` and `EncodeSegment` were moved +to the `Parser` and `Token` struct respectively. This will allow us in the +future to configure the behavior of these two based on options supplied on the +parser or the token (creation). This also removes two previously global +variables and moves them to parser options `WithStrictDecoding` and +`WithPaddingAllowed`. + +In order to do that, we had to adjust the way signing methods work. Previously +they were given a base64 encoded signature in `Verify` and were expected to +return a base64 encoded version of the signature in `Sign`, both as a `string`. +However, this made it necessary to have `DecodeSegment` and `EncodeSegment` +global and was a less than perfect design because we were repeating +encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` +operate on a decoded signature as a `[]byte`, which feels more natural for a +cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of +the final encoding/decoding part. + +In addition to that, we also changed the `Signature` field on `Token` from a +`string` to `[]byte` and this is also now populated with the decoded form. This +is also more consistent, because the other parts of the JWT, mainly `Header` and +`Claims` were already stored in decoded form in `Token`. Only the signature was +stored in base64 encoded form, which was redundant with the information in the +`Raw` field, which contains the complete token as base64. + +```go +type Token struct { + Raw string // Raw contains the raw token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form + Valid bool // Valid specifies if the token is valid +} +``` + +Most (if not all) of these changes should not impact the normal usage of this +library. Only users directly accessing the `Signature` field as well as +developers of custom signing methods should be affected. + # Migration Guide (v4.0.0) -Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: +Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), +the import path will be: "github.com/golang-jwt/jwt/v4" -The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as -`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having -troubles migrating, please open an issue. +The `/v4` version will be backwards compatible with existing `v3.x.y` tags in +this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should +be a drop-in replacement, if you're having troubles migrating, please open an +issue. -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually or by using tools such as `sed` or `gofmt`. +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or +`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually +or by using tools such as `sed` or `gofmt`. And then you'd typically run: @@ -97,4 +181,5 @@ go mod tidy # Older releases (before v3.2.0) -The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. +The original migration guide for older releases can be found at +https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/README.md b/README.md index 87259e84..964598a3 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,79 @@ # jwt-go [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). - -Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) this project adds Go module support, but maintains backwards compatibility with older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. -See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version v5.0.0 introduces major improvements to the validation of tokens, but is not entirely backwards compatible. - -> After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. - - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. +[![Go +Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +[![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](https://coveralls.io/github/golang-jwt/jwt?branch=main) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) +implementation of [JSON Web +Tokens](https://datatracker.ietf.org/doc/html/rfc7519). + +Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) +this project adds Go module support, but maintains backwards compatibility with +older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the +[`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version +v5.0.0 introduces major improvements to the validation of tokens, but is not +entirely backwards compatible. + +> After the original author of the library suggested migrating the maintenance +> of `jwt-go`, a dedicated team of open source maintainers decided to clone the +> existing library into this repository. See +> [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a +> detailed discussion on this topic. + + +**SECURITY NOTICE:** Some older versions of Go have a security issue in the +crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue +[dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more +detail. + +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is +what you +expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). +This library attempts to make it easy to do the right thing by requiring key +types match the expected alg, but you should take the extra step to verify it in +your usage. See the examples provided. ### Supported Go versions -Our support of Go versions is aligned with Go's [version release policy](https://golang.org/doc/devel/release#policy). -So we will support a major version of Go until there are two newer major releases. -We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities -which will not be fixed. +Our support of Go versions is aligned with Go's [version release +policy](https://golang.org/doc/devel/release#policy). So we will support a major +version of Go until there are two newer major releases. We no longer support +building jwt-go with unsupported Go versions, as these contain security +vulnerabilities which will not be fixed. ## What the heck is a JWT? -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web +Tokens. -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) encoded. The last part is the signature, encoded the same way. +In short, it's a signed JSON object that does something useful (for example, +authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is +made of three parts, separated by `.`'s. The first two parts are JSON objects, +that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) +encoded. The last part is the signature, encoded the same way. -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. +The first part is called the header. It contains the necessary information for +verifying the last part, the signature. For example, which encryption method +was used for signing and what key was used. -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about reserved keys and the proper way to add your own. +The part in the middle is the interesting bit. It's called the Claims and +contains the actual stuff you care about. Refer to [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about +reserved keys and the proper way to add your own. ## What's in the box? -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. +This library supports the parsing and verification as well as the generation and +signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, +RSA-PSS, and ECDSA, though hooks are present for adding your own. ## Installation Guidelines -1. To install the jwt package, you first need to have [Go](https://go.dev/doc/install) installed, then you can use the command below to add `jwt-go` as a dependency in your Go program. +1. To install the jwt package, you first need to have + [Go](https://go.dev/doc/install) installed, then you can use the command + below to add `jwt-go` as a dependency in your Go program. ```sh go get -u github.com/golang-jwt/jwt/v5 @@ -50,89 +85,83 @@ go get -u github.com/golang-jwt/jwt/v5 import "github.com/golang-jwt/jwt/v5" ``` -## Examples - -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) for examples of usage: - -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) +## Usage -## Extensions +A detailed usage guide, including how to sign and verify tokens can be found on +our [documentation website](https://golang-jwt.github.io/jwt/usage/create/). -This library publishes all the necessary components for adding your own signing methods or key functions. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod` or provide a `jwt.Keyfunc`. +## Examples -A common use case would be integrating with different 3rd party signature providers, like key management services from various cloud providers or Hardware Security Modules (HSMs) or to implement additional standards. +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +for examples of usage: -| Extension | Purpose | Repo | -| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | -| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | - -*Disclaimer*: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers +* [Simple example of parsing and validating a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) +* [Simple example of building and signing a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) +* [Directory of + Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) ## Compliance -This library was last reviewed to comply with [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few notable differences: +This library was last reviewed to comply with [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few +notable differences: -* In order to protect against accidental use of [Unsecured JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. +* In order to protect against accidental use of [Unsecured + JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using + `alg=none` will only be accepted if the constant + `jwt.UnsafeAllowNoneSignatureType` is provided as the key. ## Project Status & Versioning -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `main`. Periodically, versions will be tagged from `main`. You can find all the releases on [the project releases page](https://github.com/golang-jwt/jwt/releases). +This library is considered production ready. Feedback and feature requests are +appreciated. The API should be considered stable. There should be very few +backwards-incompatible changes outside of major version updates (and only with +good reason). -**BREAKING CHANGES:*** -A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. +This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull +requests will land on `main`. Periodically, versions will be tagged from +`main`. You can find all the releases on [the project releases +page](https://github.com/golang-jwt/jwt/releases). -## Usage Tips +**BREAKING CHANGES:*** A full list of breaking changes is available in +`VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating +your code. -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. The companion project https://github.com/golang-jwt/jwe aims at a (very) experimental implementation of the JWE standard. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### Signing Methods and Key Types - -Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: - -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation -* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. +## Extensions -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: +This library publishes all the necessary components for adding your own signing +methods or key functions. Simply implement the `SigningMethod` interface and +register a factory method using `RegisterSigningMethod` or provide a +`jwt.Keyfunc`. -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. +A common use case would be integrating with different 3rd party signature +providers, like key management services from various cloud providers or Hardware +Security Modules (HSMs) or to implement additional standards. -### Troubleshooting +| Extension | Purpose | Repo | +| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | +| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | -This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types. +*Disclaimer*: Unless otherwise specified, these integrations are maintained by +third parties and should not be considered as a primary offer by any of the +mentioned cloud providers ## More -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). +Go package documentation can be found [on +pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional +documentation can be found on [our project +page](https://golang-jwt.github.io/jwt/). -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. +The command line utility included in this project (cmd/jwt) provides a +straightforward example of token creation and parsing as well as a useful tool +for debugging your own integration. You'll also find several implementation +examples in the documentation. -[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version of the JWT logo, which is distributed under the terms of the [MIT License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). +[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version +of the JWT logo, which is distributed under the terms of the [MIT +License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). diff --git a/parser_option.go b/parser_option.go index 3ad17bc6..1b5af970 100644 --- a/parser_option.go +++ b/parser_option.go @@ -104,10 +104,6 @@ func WithSubject(sub string) ParserOption { // padding. Note that the JWS RFC7515 states that the tokens will utilize a // Base64url encoding with no padding. Unfortunately, some implementations of // JWT are producing non-standard tokens, and thus require support for decoding. -// Note that this is a global variable, and updating it will change the behavior -// on a package level, and is also NOT go-routine safe. To use the -// non-recommended decoding, set this boolean to `true` prior to using this -// package. func WithPaddingAllowed() ParserOption { return func(p *Parser) { p.decodePaddingAllowed = true @@ -116,10 +112,7 @@ func WithPaddingAllowed() ParserOption { // WithStrictDecoding will switch the codec used for decoding JWTs into strict // mode. In this mode, the decoder requires that trailing padding bits are zero, -// as described in RFC 4648 section 3.5. Note that this is a global variable, -// and updating it will change the behavior on a package level, and is also NOT -// go-routine safe. To use strict decoding, set this boolean to `true` prior to -// using this package. +// as described in RFC 4648 section 3.5. func WithStrictDecoding() ParserOption { return func(p *Parser) { p.decodeStrict = true From 5e00fbc8e7eb1af78d4a0ebce6ecf2394675bd99 Mon Sep 17 00:00:00 2001 From: Tom Anderson Date: Tue, 18 Apr 2023 02:29:03 +0930 Subject: [PATCH 14/14] enable jwt.ParsePublicKeyFromPEM to parse PKCS1 Public Key (#120) --- rsa_test.go | 19 +++++++++++++++++++ rsa_utils.go | 6 ++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/rsa_test.go b/rsa_test.go index cba41001..87734760 100644 --- a/rsa_test.go +++ b/rsa_test.go @@ -1,6 +1,11 @@ package jwt_test import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" "os" "reflect" "strings" @@ -115,6 +120,17 @@ func TestRSAKeyParsing(t *testing.T) { pubKey, _ := os.ReadFile("test/sample_key.pub") badKey := []byte("All your base are belong to key") + randomKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Errorf("Failed to generate RSA private key: %v", err) + } + + publicKeyBytes := x509.MarshalPKCS1PublicKey(&randomKey.PublicKey) + pkcs1Buffer := new(bytes.Buffer) + if err = pem.Encode(pkcs1Buffer, &pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}); err != nil { + t.Errorf("Failed to encode public pem: %v", err) + } + // Test parsePrivateKey if _, e := jwt.ParseRSAPrivateKeyFromPEM(key); e != nil { t.Errorf("Failed to parse valid private key: %v", e) @@ -149,6 +165,9 @@ func TestRSAKeyParsing(t *testing.T) { t.Errorf("Parsed invalid key as valid private key: %v", k) } + if _, err := jwt.ParseRSAPublicKeyFromPEM(pkcs1Buffer.Bytes()); err != nil { + t.Errorf("failed to parse RSA public key: %v", err) + } } func BenchmarkRSAParsing(b *testing.B) { diff --git a/rsa_utils.go b/rsa_utils.go index 1966c450..b3aeebbe 100644 --- a/rsa_utils.go +++ b/rsa_utils.go @@ -75,7 +75,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr return pkey, nil } -// ParseRSAPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key +// ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { var err error @@ -91,7 +91,9 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { if cert, err := x509.ParseCertificate(block.Bytes); err == nil { parsedKey = cert.PublicKey } else { - return nil, err + if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { + return nil, err + } } }