mirror of https://github.com/docker/cli.git
Merge pull request #1936 from thaJeztah/bump_jwt_go
bump dgrijalva/jwt-go v3.2.0, docker/licencing 7c3de6a
This commit is contained in:
commit
0fd5c16ab9
|
@ -119,7 +119,7 @@ func (c mockLicenseClient) StoreLicense(ctx context.Context, dclnt licensing.Wra
|
||||||
func (c mockLicenseClient) LoadLocalLicense(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error) {
|
func (c mockLicenseClient) LoadLocalLicense(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error) {
|
||||||
return nil, fmt.Errorf("not implemented")
|
return nil, fmt.Errorf("not implemented")
|
||||||
}
|
}
|
||||||
func (c mockLicenseClient) SummarizeLicense(res *model.CheckResponse, keyID string) *model.Subscription {
|
func (c mockLicenseClient) SummarizeLicense(res *model.CheckResponse) *model.Subscription {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
func TestActivateDisplayOnlyHub(t *testing.T) {
|
func TestActivateDisplayOnlyHub(t *testing.T) {
|
||||||
|
|
|
@ -40,8 +40,8 @@ func TestSubscriptionContextWrite(t *testing.T) {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
formatter.Context{Format: NewSubscriptionsFormat("table", true)},
|
formatter.Context{Format: NewSubscriptionsFormat("table", true)},
|
||||||
`1:License Name: name1 Quantity: 10 nodes Expiration date: 2020-01-01
|
`1:License Name: name1 Components: 10 nodes Expiration date: 2020-01-01
|
||||||
2:License Name: name2 Quantity: 20 nodes Expiration date: 2020-01-01
|
2:License Name: name2 Components: 20 nodes Expiration date: 2020-01-01
|
||||||
`,
|
`,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
@ -197,7 +197,7 @@ func TestSubscriptionContextWriteJSON(t *testing.T) {
|
||||||
"ProductRatePlan": "",
|
"ProductRatePlan": "",
|
||||||
"ProductRatePlanID": "",
|
"ProductRatePlanID": "",
|
||||||
"State": "",
|
"State": "",
|
||||||
"Summary": "License Name: name1\tQuantity: 10 nodes\tExpiration date: 2020-01-01",
|
"Summary": "License Name: name1\tComponents: 10 nodes\tExpiration date: 2020-01-01",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"Owner": "owner2",
|
"Owner": "owner2",
|
||||||
|
@ -219,7 +219,7 @@ func TestSubscriptionContextWriteJSON(t *testing.T) {
|
||||||
"ProductRatePlan": "",
|
"ProductRatePlan": "",
|
||||||
"ProductRatePlanID": "",
|
"ProductRatePlanID": "",
|
||||||
"State": "",
|
"State": "",
|
||||||
"Summary": "License Name: name2\tQuantity: 20 nodes\tExpiration date: 2020-01-01",
|
"Summary": "License Name: name2\tComponents: 20 nodes\tExpiration date: 2020-01-01",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
License: Quantity: 1 Nodes Expiration date: 2018-03-18 Expired! You will no longer receive updates. Please renew at https://docker.com/licensing
|
License: Components: 1 Nodes Expiration date: 2018-03-18 Expired! You will no longer receive updates. Please renew at https://docker.com/licensing
|
||||||
|
|
|
@ -20,7 +20,7 @@ type (
|
||||||
parseLicenseFunc func(license []byte) (parsedLicense *model.IssuedLicense, err error)
|
parseLicenseFunc func(license []byte) (parsedLicense *model.IssuedLicense, err error)
|
||||||
storeLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
|
storeLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
|
||||||
loadLocalLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error)
|
loadLocalLicenseFunc func(ctx context.Context, dclnt licensing.WrappedDockerClient) (*model.Subscription, error)
|
||||||
summarizeLicenseFunc func(*model.CheckResponse, string) *model.Subscription
|
summarizeLicenseFunc func(*model.CheckResponse) *model.Subscription
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -103,9 +103,9 @@ func (c *fakeLicensingClient) LoadLocalLicense(ctx context.Context, dclnt licens
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *fakeLicensingClient) SummarizeLicense(cr *model.CheckResponse, keyid string) *model.Subscription {
|
func (c *fakeLicensingClient) SummarizeLicense(cr *model.CheckResponse) *model.Subscription {
|
||||||
if c.summarizeLicenseFunc != nil {
|
if c.summarizeLicenseFunc != nil {
|
||||||
return c.summarizeLicenseFunc(cr, keyid)
|
return c.summarizeLicenseFunc(cr)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -166,7 +166,7 @@ func GetLicenseSummary(ctx context.Context, license model.IssuedLicense) (string
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return lclient.SummarizeLicense(cr, license.KeyID).String(), nil
|
return lclient.SummarizeLicense(cr).String(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func doLoadLocalIssuedLicense(ctx context.Context, filename string, lclient licensing.Client) (*model.IssuedLicense, error) {
|
func doLoadLocalIssuedLicense(ctx context.Context, filename string, lclient licensing.Client) (*model.IssuedLicense, error) {
|
||||||
|
|
|
@ -13,7 +13,7 @@ github.com/coreos/etcd d57e8b8d97adfc4a6c224fe11671
|
||||||
github.com/cpuguy83/go-md2man 20f5889cbdc3c73dbd2862796665e7c465ade7d1 # v1.0.8
|
github.com/cpuguy83/go-md2man 20f5889cbdc3c73dbd2862796665e7c465ade7d1 # v1.0.8
|
||||||
github.com/creack/pty 3a6a957789163cacdfe0e291617a1c8e80612c11 # v1.1.9
|
github.com/creack/pty 3a6a957789163cacdfe0e291617a1c8e80612c11 # v1.1.9
|
||||||
github.com/davecgh/go-spew 8991bc29aa16c548c550c7ff78260e27b9ab7c73 # v1.1.1
|
github.com/davecgh/go-spew 8991bc29aa16c548c550c7ff78260e27b9ab7c73 # v1.1.1
|
||||||
github.com/dgrijalva/jwt-go a2c85815a77d0f951e33ba4db5ae93629a1530af
|
github.com/dgrijalva/jwt-go 06ea1031745cb8b3dab3f6a236daf2b0aa468b7e # v3.2.0
|
||||||
github.com/docker/compose-on-kubernetes 78e6a00beda64ac8ccb9fec787e601fe2ce0d5bb # v0.5.0-alpha1
|
github.com/docker/compose-on-kubernetes 78e6a00beda64ac8ccb9fec787e601fe2ce0d5bb # v0.5.0-alpha1
|
||||||
github.com/docker/distribution 0d3efadf0154c2b8a4e7b6621fff9809655cc580
|
github.com/docker/distribution 0d3efadf0154c2b8a4e7b6621fff9809655cc580
|
||||||
github.com/docker/docker a09e6e323e55e1a9b21df9c2c555f5668df3ac9b
|
github.com/docker/docker a09e6e323e55e1a9b21df9c2c555f5668df3ac9b
|
||||||
|
@ -24,7 +24,7 @@ github.com/docker/go-events 9461782956ad83b30282bf90e31f
|
||||||
github.com/docker/go-metrics d466d4f6fd960e01820085bd7e1a24426ee7ef18
|
github.com/docker/go-metrics d466d4f6fd960e01820085bd7e1a24426ee7ef18
|
||||||
github.com/docker/go-units 519db1ee28dcc9fd2474ae59fca29a810482bfb1 # v0.4.0
|
github.com/docker/go-units 519db1ee28dcc9fd2474ae59fca29a810482bfb1 # v0.4.0
|
||||||
github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
|
github.com/docker/libtrust 9cbd2a1374f46905c68a4eb3694a130610adc62a
|
||||||
github.com/docker/licensing 9781369abdb5281cdc07a2a446c6df01347ec793
|
github.com/docker/licensing 5f0f1276fe42dd721c1c093604995a9f758ace21
|
||||||
github.com/docker/swarmkit 7dded76ec532741c1ad9736cd2bb6d6661f0a386
|
github.com/docker/swarmkit 7dded76ec532741c1ad9736cd2bb6d6661f0a386
|
||||||
github.com/evanphx/json-patch 72bf35d0ff611848c1dc9df0f976c81192392fa5 # v4.1.0
|
github.com/evanphx/json-patch 72bf35d0ff611848c1dc9df0f976c81192392fa5 # v4.1.0
|
||||||
github.com/gofrs/flock 392e7fae8f1b0bdbd67dad7237d23f618feb6dbb # v0.7.1
|
github.com/gofrs/flock 392e7fae8f1b0bdbd67dad7237d23f618feb6dbb # v0.7.1
|
||||||
|
|
|
@ -1,11 +1,20 @@
|
||||||
A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-jones-json-web-token.html)
|
# jwt-go
|
||||||
|
|
||||||
[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go)
|
[![Build Status](https://travis-ci.org/dgrijalva/jwt-go.svg?branch=master)](https://travis-ci.org/dgrijalva/jwt-go)
|
||||||
|
[![GoDoc](https://godoc.org/github.com/dgrijalva/jwt-go?status.svg)](https://godoc.org/github.com/dgrijalva/jwt-go)
|
||||||
|
|
||||||
**NOTICE:** A vulnerability in JWT was [recently published](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). As this library doesn't force users to validate the `alg` is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the `alg` is what you expect.
|
A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html)
|
||||||
|
|
||||||
|
**NEW VERSION COMING:** There have been a lot of improvements suggested since the version 3.0.0 released in 2016. I'm working now on cutting two different releases: 3.2.0 will contain any non-breaking changes or enhancements. 4.0.0 will follow shortly which will include breaking changes. See the 4.0.0 milestone to get an idea of what's coming. If you have other ideas, or would like to participate in 4.0.0, now's the time. If you depend on this library and don't want to be interrupted, I recommend you use your dependency mangement tool to pin to version 3.
|
||||||
|
|
||||||
|
**SECURITY NOTICE:** Some older versions of Go have a security issue in the cryotp/elliptic. Recommendation is to upgrade to at least 1.8.3. See issue #216 for more detail.
|
||||||
|
|
||||||
|
**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/2015/03/31/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.
|
||||||
|
|
||||||
## What the heck is a JWT?
|
## What the heck is a JWT?
|
||||||
|
|
||||||
|
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](http://tools.ietf.org/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](http://tools.ietf.org/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.
|
||||||
|
@ -16,37 +25,13 @@ The part in the middle is the interesting bit. It's called the Claims and conta
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
## Parse and Verify
|
## Examples
|
||||||
|
|
||||||
Parsing and verifying tokens is pretty straight forward. You pass in the token and a function for looking up the key. This is done as a callback since you may need to parse the token to find out what signing method and key was used.
|
See [the project documentation](https://godoc.org/github.com/dgrijalva/jwt-go) for examples of usage:
|
||||||
|
|
||||||
```go
|
* [Simple example of parsing and validating a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-Parse--Hmac)
|
||||||
token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
|
* [Simple example of building and signing a token](https://godoc.org/github.com/dgrijalva/jwt-go#example-New--Hmac)
|
||||||
// Don't forget to validate the alg is what you expect:
|
* [Directory of Examples](https://godoc.org/github.com/dgrijalva/jwt-go#pkg-examples)
|
||||||
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
|
|
||||||
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
|
|
||||||
}
|
|
||||||
return myLookupKey(token.Header["kid"]), nil
|
|
||||||
})
|
|
||||||
|
|
||||||
if err == nil && token.Valid {
|
|
||||||
deliverGoodness("!")
|
|
||||||
} else {
|
|
||||||
deliverUtterRejection(":(")
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Create a token
|
|
||||||
|
|
||||||
```go
|
|
||||||
// Create the token
|
|
||||||
token := jwt.New(jwt.SigningMethodHS256)
|
|
||||||
// Set some claims
|
|
||||||
token.Claims["foo"] = "bar"
|
|
||||||
token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
|
|
||||||
// Sign and get the complete encoded token as a string
|
|
||||||
tokenString, err := token.SignedString(mySigningKey)
|
|
||||||
```
|
|
||||||
|
|
||||||
## Extensions
|
## Extensions
|
||||||
|
|
||||||
|
@ -54,13 +39,22 @@ This library publishes all the necessary components for adding your own signing
|
||||||
|
|
||||||
Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go
|
Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go
|
||||||
|
|
||||||
|
## Compliance
|
||||||
|
|
||||||
|
This library was last reviewed to comply with [RTF 7519](http://www.rfc-editor.org/info/rfc7519) dated May 2015 with a few notable differences:
|
||||||
|
|
||||||
|
* In order to protect against accidental use of [Unsecured JWTs](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#UnsecuredJWT), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
|
||||||
|
|
||||||
## Project Status & Versioning
|
## 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 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 `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases).
|
This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `master`. Periodically, versions will be tagged from `master`. You can find all the releases on [the project releases page](https://github.com/dgrijalva/jwt-go/releases).
|
||||||
|
|
||||||
While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v2`. It will do the right thing WRT semantic versioning.
|
While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/dgrijalva/jwt-go.v3`. It will do the right thing WRT semantic versioning.
|
||||||
|
|
||||||
|
**BREAKING CHANGES:***
|
||||||
|
* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code.
|
||||||
|
|
||||||
## Usage Tips
|
## Usage Tips
|
||||||
|
|
||||||
|
@ -81,6 +75,14 @@ Symmetric signing methods, such as HSA, use only a single secret. This is probab
|
||||||
|
|
||||||
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.
|
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://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation
|
||||||
|
* The [RSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation
|
||||||
|
* The [ECDSA signing method](https://godoc.org/github.com/dgrijalva/jwt-go#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation
|
||||||
|
|
||||||
### JWT and OAuth
|
### 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.
|
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.
|
||||||
|
@ -95,4 +97,4 @@ Without going too far down the rabbit hole, here's a description of the interact
|
||||||
|
|
||||||
Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
|
Documentation can be found [on godoc.org](http://godoc.org/github.com/dgrijalva/jwt-go).
|
||||||
|
|
||||||
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. For a more http centric example, see [this gist](https://gist.github.com/cryptix/45c33ecf0ae54828e63b).
|
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.
|
||||||
|
|
|
@ -0,0 +1,134 @@
|
||||||
|
package jwt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/subtle"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// For a type to be a Claims object, it must just have a Valid method that determines
|
||||||
|
// if the token is invalid for any supported reason
|
||||||
|
type Claims interface {
|
||||||
|
Valid() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Structured version of Claims Section, as referenced at
|
||||||
|
// https://tools.ietf.org/html/rfc7519#section-4.1
|
||||||
|
// See examples for how to use this with your own claim types
|
||||||
|
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"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) == false {
|
||||||
|
delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0))
|
||||||
|
vErr.Inner = fmt.Errorf("token is expired by %v", delta)
|
||||||
|
vErr.Errors |= ValidationErrorExpired
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.VerifyIssuedAt(now, false) == false {
|
||||||
|
vErr.Inner = fmt.Errorf("Token used before issued")
|
||||||
|
vErr.Errors |= ValidationErrorIssuedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
if c.VerifyNotBefore(now, false) == false {
|
||||||
|
vErr.Inner = fmt.Errorf("token is not valid yet")
|
||||||
|
vErr.Errors |= ValidationErrorNotValidYet
|
||||||
|
}
|
||||||
|
|
||||||
|
if vErr.valid() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return vErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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(c.Audience, cmp, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the exp claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool {
|
||||||
|
return verifyExp(c.ExpiresAt, cmp, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the iat claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool {
|
||||||
|
return verifyIat(c.IssuedAt, cmp, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the nbf claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool {
|
||||||
|
return verifyNbf(c.NotBefore, cmp, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- helpers
|
||||||
|
|
||||||
|
func verifyAud(aud string, cmp string, required bool) bool {
|
||||||
|
if aud == "" {
|
||||||
|
return !required
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyExp(exp int64, now int64, required bool) bool {
|
||||||
|
if exp == 0 {
|
||||||
|
return !required
|
||||||
|
}
|
||||||
|
return now <= exp
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyIat(iat int64, now int64, required bool) bool {
|
||||||
|
if iat == 0 {
|
||||||
|
return !required
|
||||||
|
}
|
||||||
|
return now >= iat
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyIss(iss string, cmp string, required bool) bool {
|
||||||
|
if iss == "" {
|
||||||
|
return !required
|
||||||
|
}
|
||||||
|
if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyNbf(nbf int64, now int64, required bool) bool {
|
||||||
|
if nbf == 0 {
|
||||||
|
return !required
|
||||||
|
}
|
||||||
|
return now >= nbf
|
||||||
|
}
|
|
@ -14,6 +14,7 @@ var (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Implements the ECDSA family of signing methods signing methods
|
// Implements the ECDSA family of signing methods signing methods
|
||||||
|
// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification
|
||||||
type SigningMethodECDSA struct {
|
type SigningMethodECDSA struct {
|
||||||
Name string
|
Name string
|
||||||
Hash crypto.Hash
|
Hash crypto.Hash
|
||||||
|
@ -69,7 +70,7 @@ func (m *SigningMethodECDSA) Verify(signingString, signature string, key interfa
|
||||||
case *ecdsa.PublicKey:
|
case *ecdsa.PublicKey:
|
||||||
ecdsaKey = k
|
ecdsaKey = k
|
||||||
default:
|
default:
|
||||||
return ErrInvalidKey
|
return ErrInvalidKeyType
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(sig) != 2*m.KeySize {
|
if len(sig) != 2*m.KeySize {
|
||||||
|
@ -103,7 +104,7 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string
|
||||||
case *ecdsa.PrivateKey:
|
case *ecdsa.PrivateKey:
|
||||||
ecdsaKey = k
|
ecdsaKey = k
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidKey
|
return "", ErrInvalidKeyType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the hasher
|
// Create the hasher
|
||||||
|
|
|
@ -6,9 +6,9 @@ import (
|
||||||
|
|
||||||
// Error constants
|
// Error constants
|
||||||
var (
|
var (
|
||||||
ErrInvalidKey = errors.New("key is invalid or of invalid type")
|
ErrInvalidKey = errors.New("key is invalid")
|
||||||
|
ErrInvalidKeyType = errors.New("key is of invalid type")
|
||||||
ErrHashUnavailable = errors.New("the requested hash function is unavailable")
|
ErrHashUnavailable = errors.New("the requested hash function is unavailable")
|
||||||
ErrNoTokenInRequest = errors.New("no token present in request")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// The errors that might occur when parsing and validating a token
|
// The errors that might occur when parsing and validating a token
|
||||||
|
@ -16,14 +16,21 @@ const (
|
||||||
ValidationErrorMalformed uint32 = 1 << iota // Token is malformed
|
ValidationErrorMalformed uint32 = 1 << iota // Token is malformed
|
||||||
ValidationErrorUnverifiable // Token could not be verified because of signing problems
|
ValidationErrorUnverifiable // Token could not be verified because of signing problems
|
||||||
ValidationErrorSignatureInvalid // Signature validation failed
|
ValidationErrorSignatureInvalid // Signature validation failed
|
||||||
ValidationErrorExpired // Exp 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
|
ValidationErrorNotValidYet // NBF validation failed
|
||||||
|
ValidationErrorId // JTI validation failed
|
||||||
|
ValidationErrorClaimsInvalid // Generic claims validation error
|
||||||
)
|
)
|
||||||
|
|
||||||
// Helper for constructing a ValidationError with a string error message
|
// Helper for constructing a ValidationError with a string error message
|
||||||
func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
|
func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
|
||||||
return &ValidationError{
|
return &ValidationError{
|
||||||
Inner: errors.New(errorText),
|
text: errorText,
|
||||||
Errors: errorFlags,
|
Errors: errorFlags,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -32,20 +39,21 @@ func NewValidationError(errorText string, errorFlags uint32) *ValidationError {
|
||||||
type ValidationError struct {
|
type ValidationError struct {
|
||||||
Inner error // stores the error returned by external dependencies, i.e.: KeyFunc
|
Inner error // stores the error returned by external dependencies, i.e.: KeyFunc
|
||||||
Errors uint32 // bitfield. see ValidationError... constants
|
Errors uint32 // bitfield. see ValidationError... constants
|
||||||
|
text string // errors that do not have a valid error just have text
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validation error is an error type
|
// Validation error is an error type
|
||||||
func (e ValidationError) Error() string {
|
func (e ValidationError) Error() string {
|
||||||
if e.Inner == nil {
|
if e.Inner != nil {
|
||||||
|
return e.Inner.Error()
|
||||||
|
} else if e.text != "" {
|
||||||
|
return e.text
|
||||||
|
} else {
|
||||||
return "token is invalid"
|
return "token is invalid"
|
||||||
}
|
}
|
||||||
return e.Inner.Error()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// No errors
|
// No errors
|
||||||
func (e *ValidationError) valid() bool {
|
func (e *ValidationError) valid() bool {
|
||||||
if e.Errors > 0 {
|
return e.Errors == 0
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Implements the HMAC-SHA family of signing methods signing methods
|
// Implements the HMAC-SHA family of signing methods signing methods
|
||||||
|
// Expects key type of []byte for both signing and validation
|
||||||
type SigningMethodHMAC struct {
|
type SigningMethodHMAC struct {
|
||||||
Name string
|
Name string
|
||||||
Hash crypto.Hash
|
Hash crypto.Hash
|
||||||
|
@ -49,7 +50,7 @@ func (m *SigningMethodHMAC) Verify(signingString, signature string, key interfac
|
||||||
// Verify the key is the right type
|
// Verify the key is the right type
|
||||||
keyBytes, ok := key.([]byte)
|
keyBytes, ok := key.([]byte)
|
||||||
if !ok {
|
if !ok {
|
||||||
return ErrInvalidKey
|
return ErrInvalidKeyType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode signature, for comparison
|
// Decode signature, for comparison
|
||||||
|
@ -90,5 +91,5 @@ func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string,
|
||||||
return EncodeSegment(hasher.Sum(nil)), nil
|
return EncodeSegment(hasher.Sum(nil)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", ErrInvalidKey
|
return "", ErrInvalidKeyType
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,94 @@
|
||||||
|
package jwt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
// "fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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{}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
aud, _ := m["aud"].(string)
|
||||||
|
return verifyAud(aud, cmp, req)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the exp claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool {
|
||||||
|
switch exp := m["exp"].(type) {
|
||||||
|
case float64:
|
||||||
|
return verifyExp(int64(exp), cmp, req)
|
||||||
|
case json.Number:
|
||||||
|
v, _ := exp.Int64()
|
||||||
|
return verifyExp(v, cmp, req)
|
||||||
|
}
|
||||||
|
return req == false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the iat claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool {
|
||||||
|
switch iat := m["iat"].(type) {
|
||||||
|
case float64:
|
||||||
|
return verifyIat(int64(iat), cmp, req)
|
||||||
|
case json.Number:
|
||||||
|
v, _ := iat.Int64()
|
||||||
|
return verifyIat(v, cmp, req)
|
||||||
|
}
|
||||||
|
return req == false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compares the nbf claim against cmp.
|
||||||
|
// If required is false, this method will return true if the value matches or is unset
|
||||||
|
func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool {
|
||||||
|
switch nbf := m["nbf"].(type) {
|
||||||
|
case float64:
|
||||||
|
return verifyNbf(int64(nbf), cmp, req)
|
||||||
|
case json.Number:
|
||||||
|
v, _ := nbf.Int64()
|
||||||
|
return verifyNbf(v, cmp, req)
|
||||||
|
}
|
||||||
|
return req == false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) == false {
|
||||||
|
vErr.Inner = errors.New("Token is expired")
|
||||||
|
vErr.Errors |= ValidationErrorExpired
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.VerifyIssuedAt(now, false) == false {
|
||||||
|
vErr.Inner = errors.New("Token used before issued")
|
||||||
|
vErr.Errors |= ValidationErrorIssuedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.VerifyNotBefore(now, false) == false {
|
||||||
|
vErr.Inner = errors.New("Token is not valid yet")
|
||||||
|
vErr.Errors |= ValidationErrorNotValidYet
|
||||||
|
}
|
||||||
|
|
||||||
|
if vErr.valid() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return vErr
|
||||||
|
}
|
|
@ -10,51 +10,20 @@ import (
|
||||||
type Parser struct {
|
type Parser struct {
|
||||||
ValidMethods []string // If populated, only these methods will be considered valid
|
ValidMethods []string // If populated, only these methods will be considered valid
|
||||||
UseJSONNumber bool // Use JSON Number format in JSON decoder
|
UseJSONNumber bool // Use JSON Number format in JSON decoder
|
||||||
|
SkipClaimsValidation bool // Skip claims validation during token parsing
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse, validate, and return a token.
|
// Parse, validate, and return a token.
|
||||||
// keyFunc will receive the parsed token and should return the key for validating.
|
// keyFunc will receive the parsed token and should return the key for validating.
|
||||||
// If everything is kosher, err will be nil
|
// If everything is kosher, err will be nil
|
||||||
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||||
parts := strings.Split(tokenString, ".")
|
return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc)
|
||||||
if len(parts) != 3 {
|
}
|
||||||
return nil, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed)
|
|
||||||
}
|
|
||||||
|
|
||||||
var err error
|
func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
|
||||||
token := &Token{Raw: tokenString}
|
token, parts, err := p.ParseUnverified(tokenString, claims)
|
||||||
// parse Header
|
if err != nil {
|
||||||
var headerBytes []byte
|
return token, err
|
||||||
if headerBytes, err = DecodeSegment(parts[0]); err != nil {
|
|
||||||
if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") {
|
|
||||||
return token, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed)
|
|
||||||
}
|
|
||||||
return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
|
||||||
}
|
|
||||||
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
|
||||||
return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
|
||||||
}
|
|
||||||
|
|
||||||
// parse Claims
|
|
||||||
var claimBytes []byte
|
|
||||||
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
|
||||||
return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
|
||||||
}
|
|
||||||
dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
|
|
||||||
if p.UseJSONNumber {
|
|
||||||
dec.UseNumber()
|
|
||||||
}
|
|
||||||
if err = dec.Decode(&token.Claims); err != nil {
|
|
||||||
return token, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lookup signature method
|
|
||||||
if method, ok := token.Header["alg"].(string); ok {
|
|
||||||
if token.Method = GetSigningMethod(method); token.Method == nil {
|
|
||||||
return token, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return token, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify signing method is in the required set
|
// Verify signing method is in the required set
|
||||||
|
@ -81,45 +50,26 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||||
}
|
}
|
||||||
if key, err = keyFunc(token); err != nil {
|
if key, err = keyFunc(token); err != nil {
|
||||||
// keyFunc returned an error
|
// keyFunc returned an error
|
||||||
|
if ve, ok := err.(*ValidationError); ok {
|
||||||
|
return token, ve
|
||||||
|
}
|
||||||
return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
|
return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check expiration times
|
|
||||||
vErr := &ValidationError{}
|
vErr := &ValidationError{}
|
||||||
now := TimeFunc().Unix()
|
|
||||||
var exp, nbf int64
|
|
||||||
var vexp, vnbf bool
|
|
||||||
|
|
||||||
// Parse 'exp' claim
|
// Validate Claims
|
||||||
switch num := token.Claims["exp"].(type) {
|
if !p.SkipClaimsValidation {
|
||||||
case json.Number:
|
if err := token.Claims.Valid(); err != nil {
|
||||||
if exp, err = num.Int64(); err == nil {
|
|
||||||
vexp = true
|
|
||||||
}
|
|
||||||
case float64:
|
|
||||||
vexp = true
|
|
||||||
exp = int64(num)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse 'nbf' claim
|
// If the Claims Valid returned an error, check if it is a validation error,
|
||||||
switch num := token.Claims["nbf"].(type) {
|
// If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set
|
||||||
case json.Number:
|
if e, ok := err.(*ValidationError); !ok {
|
||||||
if nbf, err = num.Int64(); err == nil {
|
vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid}
|
||||||
vnbf = true
|
} else {
|
||||||
|
vErr = e
|
||||||
}
|
}
|
||||||
case float64:
|
|
||||||
vnbf = true
|
|
||||||
nbf = int64(num)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if vexp && now > exp {
|
|
||||||
vErr.Inner = fmt.Errorf("token is expired")
|
|
||||||
vErr.Errors |= ValidationErrorExpired
|
|
||||||
}
|
|
||||||
|
|
||||||
if vnbf && now < nbf {
|
|
||||||
vErr.Inner = fmt.Errorf("token is not valid yet")
|
|
||||||
vErr.Errors |= ValidationErrorNotValidYet
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Perform validation
|
// Perform validation
|
||||||
|
@ -136,3 +86,63 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||||
|
|
||||||
return token, vErr
|
return token, vErr
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// WARNING: Don't use this method unless you know what you're doing
|
||||||
|
//
|
||||||
|
// This method parses the token but doesn't validate the signature. It's only
|
||||||
|
// ever useful in cases where you know the signature is valid (because it has
|
||||||
|
// been checked previously in the stack) and you want to extract values from
|
||||||
|
// it.
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
token = &Token{Raw: tokenString}
|
||||||
|
|
||||||
|
// parse Header
|
||||||
|
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, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
||||||
|
}
|
||||||
|
if err = json.Unmarshal(headerBytes, &token.Header); err != nil {
|
||||||
|
return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parse Claims
|
||||||
|
var claimBytes []byte
|
||||||
|
token.Claims = claims
|
||||||
|
|
||||||
|
if claimBytes, err = DecodeSegment(parts[1]); err != nil {
|
||||||
|
return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(bytes.NewBuffer(claimBytes))
|
||||||
|
if p.UseJSONNumber {
|
||||||
|
dec.UseNumber()
|
||||||
|
}
|
||||||
|
// JSON Decode. Special case for map type to avoid weird pointer behavior
|
||||||
|
if c, ok := token.Claims.(MapClaims); ok {
|
||||||
|
err = dec.Decode(&c)
|
||||||
|
} else {
|
||||||
|
err = dec.Decode(&claims)
|
||||||
|
}
|
||||||
|
// Handle decode error
|
||||||
|
if err != nil {
|
||||||
|
return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable)
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, parts, nil
|
||||||
|
}
|
||||||
|
|
|
@ -7,6 +7,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Implements the RSA family of signing methods signing methods
|
// Implements the RSA family of signing methods signing methods
|
||||||
|
// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation
|
||||||
type SigningMethodRSA struct {
|
type SigningMethodRSA struct {
|
||||||
Name string
|
Name string
|
||||||
Hash crypto.Hash
|
Hash crypto.Hash
|
||||||
|
@ -44,8 +45,7 @@ func (m *SigningMethodRSA) Alg() string {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implements the Verify method from SigningMethod
|
// Implements the Verify method from SigningMethod
|
||||||
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA public key as
|
// For this signing method, must be an *rsa.PublicKey structure.
|
||||||
// []byte, or an rsa.PublicKey structure.
|
|
||||||
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
|
func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
|
@ -56,16 +56,10 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
|
||||||
}
|
}
|
||||||
|
|
||||||
var rsaKey *rsa.PublicKey
|
var rsaKey *rsa.PublicKey
|
||||||
|
var ok bool
|
||||||
|
|
||||||
switch k := key.(type) {
|
if rsaKey, ok = key.(*rsa.PublicKey); !ok {
|
||||||
case []byte:
|
return ErrInvalidKeyType
|
||||||
if rsaKey, err = ParseRSAPublicKeyFromPEM(k); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
case *rsa.PublicKey:
|
|
||||||
rsaKey = k
|
|
||||||
default:
|
|
||||||
return ErrInvalidKey
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create hasher
|
// Create hasher
|
||||||
|
@ -80,20 +74,13 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface
|
||||||
}
|
}
|
||||||
|
|
||||||
// Implements the Sign method from SigningMethod
|
// Implements the Sign method from SigningMethod
|
||||||
// For this signing method, must be either a PEM encoded PKCS1 or PKCS8 RSA private key as
|
// For this signing method, must be an *rsa.PrivateKey structure.
|
||||||
// []byte, or an rsa.PrivateKey structure.
|
|
||||||
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
|
func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) {
|
||||||
var err error
|
|
||||||
var rsaKey *rsa.PrivateKey
|
var rsaKey *rsa.PrivateKey
|
||||||
|
var ok bool
|
||||||
|
|
||||||
switch k := key.(type) {
|
// Validate type of key
|
||||||
case []byte:
|
if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
|
||||||
if rsaKey, err = ParseRSAPrivateKeyFromPEM(k); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
case *rsa.PrivateKey:
|
|
||||||
rsaKey = k
|
|
||||||
default:
|
|
||||||
return "", ErrInvalidKey
|
return "", ErrInvalidKey
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -106,7 +106,7 @@ func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (strin
|
||||||
case *rsa.PrivateKey:
|
case *rsa.PrivateKey:
|
||||||
rsaKey = k
|
rsaKey = k
|
||||||
default:
|
default:
|
||||||
return "", ErrInvalidKey
|
return "", ErrInvalidKeyType
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the hasher
|
// Create the hasher
|
||||||
|
|
|
@ -10,6 +10,7 @@ import (
|
||||||
var (
|
var (
|
||||||
ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
|
ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
|
||||||
ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
|
ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
|
||||||
|
ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key")
|
||||||
)
|
)
|
||||||
|
|
||||||
// Parse PEM encoded PKCS1 or PKCS8 private key
|
// Parse PEM encoded PKCS1 or PKCS8 private key
|
||||||
|
@ -38,6 +39,38 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
|
||||||
return pkey, nil
|
return pkey, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Parse PEM encoded PKCS1 or PKCS8 private key protected with password
|
||||||
|
func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) {
|
||||||
|
var err error
|
||||||
|
|
||||||
|
// Parse PEM block
|
||||||
|
var block *pem.Block
|
||||||
|
if block, _ = pem.Decode(key); block == nil {
|
||||||
|
return nil, ErrKeyMustBePEMEncoded
|
||||||
|
}
|
||||||
|
|
||||||
|
var parsedKey interface{}
|
||||||
|
|
||||||
|
var blockDecrypted []byte
|
||||||
|
if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil {
|
||||||
|
if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var pkey *rsa.PrivateKey
|
||||||
|
var ok bool
|
||||||
|
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
|
||||||
|
return nil, ErrNotRSAPrivateKey
|
||||||
|
}
|
||||||
|
|
||||||
|
return pkey, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Parse PEM encoded PKCS1 or PKCS8 public key
|
// Parse PEM encoded PKCS1 or PKCS8 public key
|
||||||
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
|
func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
|
||||||
var err error
|
var err error
|
||||||
|
@ -61,7 +94,7 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
|
||||||
var pkey *rsa.PublicKey
|
var pkey *rsa.PublicKey
|
||||||
var ok bool
|
var ok bool
|
||||||
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
|
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
|
||||||
return nil, ErrNotRSAPrivateKey
|
return nil, ErrNotRSAPublicKey
|
||||||
}
|
}
|
||||||
|
|
||||||
return pkey, nil
|
return pkey, nil
|
||||||
|
|
|
@ -1,6 +1,11 @@
|
||||||
package jwt
|
package jwt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
var signingMethods = map[string]func() SigningMethod{}
|
var signingMethods = map[string]func() SigningMethod{}
|
||||||
|
var signingMethodLock = new(sync.RWMutex)
|
||||||
|
|
||||||
// Implement SigningMethod to add new methods for signing or verifying tokens.
|
// Implement SigningMethod to add new methods for signing or verifying tokens.
|
||||||
type SigningMethod interface {
|
type SigningMethod interface {
|
||||||
|
@ -12,11 +17,17 @@ type SigningMethod interface {
|
||||||
// Register the "alg" name and a factory function for signing method.
|
// Register the "alg" name and a factory function for signing method.
|
||||||
// This is typically done during init() in the method's implementation
|
// This is typically done during init() in the method's implementation
|
||||||
func RegisterSigningMethod(alg string, f func() SigningMethod) {
|
func RegisterSigningMethod(alg string, f func() SigningMethod) {
|
||||||
|
signingMethodLock.Lock()
|
||||||
|
defer signingMethodLock.Unlock()
|
||||||
|
|
||||||
signingMethods[alg] = f
|
signingMethods[alg] = f
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get a signing method from an "alg" string
|
// Get a signing method from an "alg" string
|
||||||
func GetSigningMethod(alg string) (method SigningMethod) {
|
func GetSigningMethod(alg string) (method SigningMethod) {
|
||||||
|
signingMethodLock.RLock()
|
||||||
|
defer signingMethodLock.RUnlock()
|
||||||
|
|
||||||
if methodF, ok := signingMethods[alg]; ok {
|
if methodF, ok := signingMethods[alg]; ok {
|
||||||
method = methodF()
|
method = methodF()
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,6 @@ package jwt
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
@ -15,7 +14,7 @@ var TimeFunc = time.Now
|
||||||
|
|
||||||
// Parse methods use this callback function to supply
|
// Parse methods use this callback function to supply
|
||||||
// the key for verification. The function receives the parsed,
|
// the key for verification. The function receives the parsed,
|
||||||
// but unverified Token. This allows you to use propries in the
|
// but unverified Token. This allows you to use properties in the
|
||||||
// Header of the token (such as `kid`) to identify which key to use.
|
// Header of the token (such as `kid`) to identify which key to use.
|
||||||
type Keyfunc func(*Token) (interface{}, error)
|
type Keyfunc func(*Token) (interface{}, error)
|
||||||
|
|
||||||
|
@ -25,19 +24,23 @@ type Token struct {
|
||||||
Raw string // The raw token. Populated when you Parse a token
|
Raw string // The raw token. Populated when you Parse a token
|
||||||
Method SigningMethod // The signing method used or to be used
|
Method SigningMethod // The signing method used or to be used
|
||||||
Header map[string]interface{} // The first segment of the token
|
Header map[string]interface{} // The first segment of the token
|
||||||
Claims map[string]interface{} // The second 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
|
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
|
Valid bool // Is the token valid? Populated when you Parse/Verify a token
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new Token. Takes a signing method
|
// Create a new Token. Takes a signing method
|
||||||
func New(method SigningMethod) *Token {
|
func New(method SigningMethod) *Token {
|
||||||
|
return NewWithClaims(method, MapClaims{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWithClaims(method SigningMethod, claims Claims) *Token {
|
||||||
return &Token{
|
return &Token{
|
||||||
Header: map[string]interface{}{
|
Header: map[string]interface{}{
|
||||||
"typ": "JWT",
|
"typ": "JWT",
|
||||||
"alg": method.Alg(),
|
"alg": method.Alg(),
|
||||||
},
|
},
|
||||||
Claims: make(map[string]interface{}),
|
Claims: claims,
|
||||||
Method: method,
|
Method: method,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -63,17 +66,16 @@ func (t *Token) SigningString() (string, error) {
|
||||||
var err error
|
var err error
|
||||||
parts := make([]string, 2)
|
parts := make([]string, 2)
|
||||||
for i, _ := range parts {
|
for i, _ := range parts {
|
||||||
var source map[string]interface{}
|
|
||||||
if i == 0 {
|
|
||||||
source = t.Header
|
|
||||||
} else {
|
|
||||||
source = t.Claims
|
|
||||||
}
|
|
||||||
|
|
||||||
var jsonValue []byte
|
var jsonValue []byte
|
||||||
if jsonValue, err = json.Marshal(source); err != nil {
|
if i == 0 {
|
||||||
|
if jsonValue, err = json.Marshal(t.Header); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if jsonValue, err = json.Marshal(t.Claims); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
parts[i] = EncodeSegment(jsonValue)
|
parts[i] = EncodeSegment(jsonValue)
|
||||||
}
|
}
|
||||||
|
@ -87,28 +89,8 @@ func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) {
|
||||||
return new(Parser).Parse(tokenString, keyFunc)
|
return new(Parser).Parse(tokenString, keyFunc)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try to find the token in an http.Request.
|
func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) {
|
||||||
// This method will call ParseMultipartForm if there's no token in the header.
|
return new(Parser).ParseWithClaims(tokenString, claims, keyFunc)
|
||||||
// Currently, it looks in the Authorization header as well as
|
|
||||||
// looking for an 'access_token' request parameter in req.Form.
|
|
||||||
func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err error) {
|
|
||||||
|
|
||||||
// Look for an Authorization header
|
|
||||||
if ah := req.Header.Get("Authorization"); ah != "" {
|
|
||||||
// Should be a bearer token
|
|
||||||
if len(ah) > 6 && strings.ToUpper(ah[0:7]) == "BEARER " {
|
|
||||||
return Parse(ah[7:], keyFunc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Look for "access_token" parameter
|
|
||||||
req.ParseMultipartForm(10e6)
|
|
||||||
if tokStr := req.Form.Get("access_token"); tokStr != "" {
|
|
||||||
return Parse(tokStr, keyFunc)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, ErrNoTokenInRequest
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Encode JWT specific base64url encoding with padding stripped
|
// Encode JWT specific base64url encoding with padding stripped
|
||||||
|
|
|
@ -3,10 +3,88 @@ docker/licensing
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
*licensing* is a library for interacting with Docker issued product licenses. It facilitates user's authentication to the [Docker Store](https://store.docker.com), provides a mechanism for retrieving a user's existing licenses, detects and verifies locally stored licenses, and can be used to provision trial licenses for [Docker Enterprise Edition](https://www.docker.com/enterprise-edition).
|
*licensing* is a library for interacting with Docker issued product licenses. It facilitates user's authentication to the [Docker Hub](https://hub.docker.com), provides a mechanism for retrieving a user's existing docker-issued subscriptions/licenses, detects and verifies locally stored licenses, and can be used to provision trial licenses for [Docker Enterprise Edition](https://www.docker.com/enterprise-edition).
|
||||||
|
|
||||||
License
|
License
|
||||||
=========
|
=========
|
||||||
docker/licensing is licensed under the Apache License, Version 2.0. See
|
docker/licensing is licensed under the Apache License, Version 2.0. See
|
||||||
[LICENSE](https://github.com/docker/licensing/blob/master/LICENSE) for the full
|
[LICENSE](https://github.com/docker/licensing/blob/master/LICENSE) for the full
|
||||||
license text.
|
license text.
|
||||||
|
|
||||||
|
Usage
|
||||||
|
========
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
|
||||||
|
"github.com/docker/licensing"
|
||||||
|
"github.com/docker/licensing/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
hubURL = "https://hub.docker.com"
|
||||||
|
pubKey = "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0Ka2lkOiBKN0xEOjY3VlI6TDVIWjpVN0JBOjJPNEc6NEFMMzpPRjJOOkpIR0I6RUZUSDo1Q1ZROk1GRU86QUVJVAoKTUlJQ0lqQU5CZ2txaGtpRzl3MEJBUUVGQUFPQ0FnOEFNSUlDQ2dLQ0FnRUF5ZEl5K2xVN283UGNlWSs0K3MrQwpRNU9FZ0N5RjhDeEljUUlXdUs4NHBJaVpjaVk2NzMweUNZbndMU0tUbHcrVTZVQy9RUmVXUmlvTU5ORTVEczVUCllFWGJHRzZvbG0ycWRXYkJ3Y0NnKzJVVUgvT2NCOVd1UDZnUlBIcE1GTXN4RHpXd3ZheThKVXVIZ1lVTFVwbTEKSXYrbXE3bHA1blEvUnhyVDBLWlJBUVRZTEVNRWZHd20zaE1PL2dlTFBTK2hnS1B0SUhsa2c2L1djb3hUR29LUAo3OWQvd2FIWXhHTmw3V2hTbmVpQlN4YnBiUUFLazIxbGc3OThYYjd2WnlFQVRETXJSUjlNZUU2QWRqNUhKcFkzCkNveVJBUENtYUtHUkNLNHVvWlNvSXUwaEZWbEtVUHliYncwMDBHTyt3YTJLTjhVd2dJSW0waTVJMXVXOUdrcTQKempCeTV6aGdxdVVYYkc5YldQQU9ZcnE1UWE4MUR4R2NCbEp5SFlBcCtERFBFOVRHZzR6WW1YakpueFpxSEVkdQpHcWRldlo4WE1JMHVrZmtHSUkxNHdVT2lNSUlJclhsRWNCZi80Nkk4Z1FXRHp4eWNaZS9KR1grTEF1YXlYcnlyClVGZWhWTlVkWlVsOXdYTmFKQitrYUNxejVRd2FSOTNzR3crUVNmdEQwTnZMZTdDeU9IK0U2dmc2U3QvTmVUdmcKdjhZbmhDaVhJbFo4SE9mSXdOZTd0RUYvVWN6NU9iUHlrbTN0eWxyTlVqdDBWeUFtdHRhY1ZJMmlHaWhjVVBybQprNGxWSVo3VkQvTFNXK2k3eW9TdXJ0cHNQWGNlMnBLRElvMzBsSkdoTy8zS1VtbDJTVVpDcXpKMXlFbUtweXNICjVIRFc5Y3NJRkNBM2RlQWpmWlV2TjdVQ0F3RUFBUT09Ci0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQo="
|
||||||
|
username = "docker username"
|
||||||
|
password = "your password"
|
||||||
|
appFeature = "jump"
|
||||||
|
)
|
||||||
|
|
||||||
|
func panicOnErr(err error) {
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
hubURI, err := url.Parse(hubURL)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
// setup client
|
||||||
|
c, err := licensing.New(&licensing.Config{
|
||||||
|
BaseURI: *hubURI,
|
||||||
|
HTTPClient: nil,
|
||||||
|
PublicKeys: []string{pubKey},
|
||||||
|
})
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
// grab token
|
||||||
|
ctx := context.Background()
|
||||||
|
token, err := c.LoginViaAuth(ctx, username, password)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
// fetch dockerID, if not already known
|
||||||
|
id, err := c.GetHubUserByName(ctx, username)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
subs, err := c.ListSubscriptions(ctx, token, id.ID)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
// find first available subscription with given feature
|
||||||
|
var featuredSub *model.Subscription
|
||||||
|
for _, sub := range subs {
|
||||||
|
_, ok := sub.GetFeatureValue(appFeature)
|
||||||
|
if ok {
|
||||||
|
featuredSub = sub
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if featuredSub == nil {
|
||||||
|
fmt.Println("account has no subscriptions with the desired feature entitlements")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// download license file for this subscription
|
||||||
|
subLic, err := c.DownloadLicenseFromHub(ctx, token, featuredSub.ID)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
// verify license is issued by corresponding keypair and is not expired
|
||||||
|
licFile, err := c.VerifyLicense(ctx, *subLic)
|
||||||
|
panicOnErr(err)
|
||||||
|
|
||||||
|
fmt.Println("license summary: ", c.SummarizeLicense(licFile))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
|
@ -35,7 +35,7 @@ type Client interface {
|
||||||
ParseLicense(license []byte) (parsedLicense *model.IssuedLicense, err error)
|
ParseLicense(license []byte) (parsedLicense *model.IssuedLicense, err error)
|
||||||
StoreLicense(ctx context.Context, dclnt WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
|
StoreLicense(ctx context.Context, dclnt WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
|
||||||
LoadLocalLicense(ctx context.Context, dclnt WrappedDockerClient) (*model.Subscription, error)
|
LoadLocalLicense(ctx context.Context, dclnt WrappedDockerClient) (*model.Subscription, error)
|
||||||
SummarizeLicense(res *model.CheckResponse, keyID string) *model.Subscription
|
SummarizeLicense(res *model.CheckResponse) *model.Subscription
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) LoginViaAuth(ctx context.Context, username, password string) (string, error) {
|
func (c *client) LoginViaAuth(ctx context.Context, username, password string) (string, error) {
|
||||||
|
@ -115,7 +115,7 @@ func (c *client) ListSubscriptions(ctx context.Context, authToken, dockerID stri
|
||||||
// filter out non docker licenses
|
// filter out non docker licenses
|
||||||
dockerSubs := []*model.Subscription{}
|
dockerSubs := []*model.Subscription{}
|
||||||
for _, sub := range subs {
|
for _, sub := range subs {
|
||||||
if !strings.HasPrefix(sub.ProductID, "docker-ee") {
|
if !strings.HasPrefix(sub.ProductID, "docker") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -139,7 +139,7 @@ func (c *client) ListSubscriptionsDetails(ctx context.Context, authToken, docker
|
||||||
// filter out non docker licenses
|
// filter out non docker licenses
|
||||||
dockerSubs := []*model.SubscriptionDetail{}
|
dockerSubs := []*model.SubscriptionDetail{}
|
||||||
for _, sub := range subs {
|
for _, sub := range subs {
|
||||||
if !strings.HasPrefix(sub.ProductID, "docker-ee") {
|
if !strings.HasPrefix(sub.ProductID, "docker") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -71,11 +71,6 @@ type EncodeOptions struct {
|
||||||
|
|
||||||
// Encode creates a JWT string for the given identity.DockerIdentity.
|
// Encode creates a JWT string for the given identity.DockerIdentity.
|
||||||
func Encode(identity identity.DockerIdentity, options EncodeOptions) (string, error) {
|
func Encode(identity identity.DockerIdentity, options EncodeOptions) (string, error) {
|
||||||
// Note: we only support a RS256 signing method right now. If we want to support
|
|
||||||
// additional signing methods (for example, HS256), this could be specified as an
|
|
||||||
// encoding option.
|
|
||||||
token := jwt.New(jwt.SigningMethodRS256)
|
|
||||||
|
|
||||||
block, _ := pem.Decode(options.Certificate)
|
block, _ := pem.Decode(options.Certificate)
|
||||||
if block == nil {
|
if block == nil {
|
||||||
return "", fmt.Errorf("invalid key: failed to parse header")
|
return "", fmt.Errorf("invalid key: failed to parse header")
|
||||||
|
@ -84,35 +79,44 @@ func Encode(identity identity.DockerIdentity, options EncodeOptions) (string, er
|
||||||
encodedCert := base64.StdEncoding.EncodeToString(block.Bytes)
|
encodedCert := base64.StdEncoding.EncodeToString(block.Bytes)
|
||||||
x5cCerts := [1]string{encodedCert}
|
x5cCerts := [1]string{encodedCert}
|
||||||
|
|
||||||
token.Header[x5c] = x5cCerts
|
|
||||||
|
|
||||||
// non standard fields
|
// non standard fields
|
||||||
// Note: this is a required field
|
// Note: this is a required field
|
||||||
token.Claims[username] = identity.Username
|
claims := make(map[string]interface{})
|
||||||
token.Claims[email] = identity.Email
|
claims[username] = identity.Username
|
||||||
|
claims[email] = identity.Email
|
||||||
|
|
||||||
// standard JWT fields, consult the JWT spec for details
|
// standard JWT fields, consult the JWT spec for details
|
||||||
token.Claims[sub] = identity.DockerID
|
claims[sub] = identity.DockerID
|
||||||
|
|
||||||
if len(identity.Scopes) > 0 {
|
if len(identity.Scopes) > 0 {
|
||||||
token.Claims[scope] = strings.Join(identity.Scopes, " ")
|
claims[scope] = strings.Join(identity.Scopes, " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
jtiStr := options.Jti
|
jtiStr := options.Jti
|
||||||
if len(jtiStr) == 0 {
|
if len(jtiStr) == 0 {
|
||||||
jtiStr = "jti-" + uuid.New().String()
|
jtiStr = "jti-" + uuid.New().String()
|
||||||
}
|
}
|
||||||
token.Claims[jti] = jtiStr
|
claims[jti] = jtiStr
|
||||||
|
|
||||||
token.Claims[iat] = time.Now().Unix()
|
claims[iat] = time.Now().Unix()
|
||||||
token.Claims[exp] = options.Expiration
|
claims[exp] = options.Expiration
|
||||||
|
|
||||||
if options.IncludeLegacyClaims {
|
if options.IncludeLegacyClaims {
|
||||||
token.Claims[sessionid] = jtiStr
|
claims[sessionid] = jtiStr
|
||||||
token.Claims[userid] = identity.DockerID
|
claims[userid] = identity.DockerID
|
||||||
}
|
}
|
||||||
|
|
||||||
return token.SignedString(options.SigningKey)
|
// Note: we only support a RS256 signing method right now. If we want to support
|
||||||
|
// additional signing methods (for example, HS256), this could be specified as an
|
||||||
|
// encoding option.
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims(claims))
|
||||||
|
token.Header[x5c] = x5cCerts
|
||||||
|
|
||||||
|
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(options.SigningKey)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return token.SignedString(privateKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
// DecodeOptions holds JWT decoding options
|
// DecodeOptions holds JWT decoding options
|
||||||
|
@ -122,24 +126,30 @@ type DecodeOptions struct {
|
||||||
|
|
||||||
// Decode decodes the given JWT string, returning the decoded identity.DockerIdentity
|
// Decode decodes the given JWT string, returning the decoded identity.DockerIdentity
|
||||||
func Decode(tokenStr string, options DecodeOptions) (*identity.DockerIdentity, error) {
|
func Decode(tokenStr string, options DecodeOptions) (*identity.DockerIdentity, error) {
|
||||||
rootCerts := options.CertificateChain
|
token, err := jwt.Parse(tokenStr, keyFunc(options.CertificateChain))
|
||||||
token, err := jwt.Parse(tokenStr, keyFunc(rootCerts))
|
|
||||||
|
|
||||||
if err == nil && token.Valid {
|
if err != nil {
|
||||||
username, ok := token.Claims[username].(string)
|
if ve, ok := err.(*jwt.ValidationError); ok {
|
||||||
|
return nil, &ValidationError{VError: ve}
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("error decoding token: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
||||||
|
username, ok := claims[username].(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("%v claim not present", username)
|
return nil, fmt.Errorf("%v claim not present", username)
|
||||||
}
|
}
|
||||||
dockerID, ok := token.Claims[sub].(string)
|
dockerID, ok := claims[sub].(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("%v claim not present", sub)
|
return nil, fmt.Errorf("%v claim not present", sub)
|
||||||
}
|
}
|
||||||
|
|
||||||
// email is optional
|
// email is optional
|
||||||
email, _ := token.Claims[email].(string)
|
email, _ := claims[email].(string)
|
||||||
|
|
||||||
var scopes []string
|
var scopes []string
|
||||||
if scopeClaim, ok := token.Claims[scope]; ok {
|
if scopeClaim, ok := claims[scope]; ok {
|
||||||
sstr, ok := scopeClaim.(string)
|
sstr, ok := scopeClaim.(string)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("scope claim invalid")
|
return nil, fmt.Errorf("scope claim invalid")
|
||||||
|
@ -147,24 +157,16 @@ func Decode(tokenStr string, options DecodeOptions) (*identity.DockerIdentity, e
|
||||||
scopes = strings.Split(sstr, " ")
|
scopes = strings.Split(sstr, " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
identity := &identity.DockerIdentity{
|
return &identity.DockerIdentity{
|
||||||
Username: username,
|
Username: username,
|
||||||
DockerID: dockerID,
|
DockerID: dockerID,
|
||||||
Email: email,
|
Email: email,
|
||||||
Scopes: scopes,
|
Scopes: scopes,
|
||||||
}
|
}, nil
|
||||||
return identity, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// no error but an invalid token seems like a corner case, but just to be sure
|
// no error but an invalid token seems like a corner case, but just to be sure
|
||||||
if err == nil && !token.Valid {
|
|
||||||
return nil, fmt.Errorf("token was invalid")
|
return nil, fmt.Errorf("token was invalid")
|
||||||
}
|
|
||||||
|
|
||||||
if ve, ok := err.(*jwt.ValidationError); ok {
|
|
||||||
return nil, &ValidationError{VError: ve}
|
|
||||||
}
|
|
||||||
return nil, fmt.Errorf("error decoding token: %s", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsExpired returns true if the token has expired, false otherwise
|
// IsExpired returns true if the token has expired, false otherwise
|
||||||
|
@ -225,7 +227,7 @@ func keyFunc(roots *x509.CertPool) jwt.Keyfunc {
|
||||||
|
|
||||||
key := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
|
key := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
|
||||||
|
|
||||||
return key, nil
|
return jwt.ParseRSAPublicKeyFromPEM(key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -11,6 +11,21 @@ type CheckResponse struct {
|
||||||
ScanningEnabled bool `json:"scanningEnabled"`
|
ScanningEnabled bool `json:"scanningEnabled"`
|
||||||
Type string `json:"licenseType"`
|
Type string `json:"licenseType"`
|
||||||
Tier string `json:"tier"`
|
Tier string `json:"tier"`
|
||||||
|
|
||||||
|
SubscriptionID string `json:"subscription_id,omitempty"`
|
||||||
|
ProductID string `json:"product_id,omitempty"`
|
||||||
|
RatePlanID string `json:"rate_plan_id,omitempty"`
|
||||||
|
Version int `json:"version"`
|
||||||
|
GraceDays int `json:"grace_days,omitempty"`
|
||||||
|
Metadata *Metadata `json:"metadata,omitempty"`
|
||||||
|
PricingComponents PricingComponents `json:"pricing_components,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata holds non-essential license information, that is, anything that is not required by clients to ensure
|
||||||
|
// the license is valid
|
||||||
|
type Metadata struct {
|
||||||
|
Username string `json:"username,omitempty"`
|
||||||
|
Company string `json:"company,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IssuedLicense represents an issued license
|
// IssuedLicense represents an issued license
|
||||||
|
|
|
@ -31,6 +31,19 @@ type Subscription struct {
|
||||||
State string `json:"state"`
|
State string `json:"state"`
|
||||||
Eusa *EusaState `json:"eusa,omitempty"`
|
Eusa *EusaState `json:"eusa,omitempty"`
|
||||||
PricingComponents PricingComponents `json:"pricing_components"`
|
PricingComponents PricingComponents `json:"pricing_components"`
|
||||||
|
GraceDays int `json:"grace_days"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFeatureValue returns true if a given feature is among a subscription's pricing component entitlements along with
|
||||||
|
// it's corresponding value and false if it is not found
|
||||||
|
func (s *Subscription) GetFeatureValue(featureName string) (int, bool) {
|
||||||
|
for _, component := range s.PricingComponents {
|
||||||
|
if component.Name == featureName && component.Value > 0 {
|
||||||
|
return component.Value, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0, false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Subscription) String() string {
|
func (s *Subscription) String() string {
|
||||||
|
@ -61,7 +74,7 @@ func (s *Subscription) String() string {
|
||||||
for i, pc := range s.PricingComponents {
|
for i, pc := range s.PricingComponents {
|
||||||
pcStrs[i] = fmt.Sprintf("%d %s", pc.Value, pc.Name)
|
pcStrs[i] = fmt.Sprintf("%d %s", pc.Value, pc.Name)
|
||||||
}
|
}
|
||||||
quantityMsg := "Quantity: " + strings.Join(pcStrs, ", ")
|
componentsMsg := "Components: " + strings.Join(pcStrs, ", ")
|
||||||
if s.Name != "" {
|
if s.Name != "" {
|
||||||
nameMsg = fmt.Sprintf("License Name: %s\t", s.Name)
|
nameMsg = fmt.Sprintf("License Name: %s\t", s.Name)
|
||||||
} else if s.ProductRatePlan == "free-trial" {
|
} else if s.ProductRatePlan == "free-trial" {
|
||||||
|
@ -70,7 +83,7 @@ func (s *Subscription) String() string {
|
||||||
statusMsg = fmt.Sprintf("\tTo purchase go to %s", storeURL)
|
statusMsg = fmt.Sprintf("\tTo purchase go to %s", storeURL)
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Sprintf("%s%s\t%s%s", nameMsg, quantityMsg, expirationMsg, statusMsg)
|
return fmt.Sprintf("%s%s\t%s%s", nameMsg, componentsMsg, expirationMsg, statusMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscriptionDetail presents Subscription information to billing service clients.
|
// SubscriptionDetail presents Subscription information to billing service clients.
|
||||||
|
|
|
@ -122,59 +122,41 @@ func (c *client) LoadLocalLicense(ctx context.Context, clnt WrappedDockerClient)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return checkResponseToSubscription(checkResponse, parsedLicense.KeyID), nil
|
return checkResponseToSubscription(checkResponse), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkResponseToSubscription(checkResponse *model.CheckResponse, keyID string) *model.Subscription {
|
func checkResponseToSubscription(checkResponse *model.CheckResponse) *model.Subscription {
|
||||||
|
|
||||||
// TODO - this translation still needs some work
|
|
||||||
// Primary missing piece is how to distinguish from basic, vs std/advanced
|
|
||||||
var productID string
|
|
||||||
var ratePlan string
|
|
||||||
var state string
|
|
||||||
switch strings.ToLower(checkResponse.Tier) {
|
|
||||||
case "internal":
|
|
||||||
productID = "docker-ee-trial"
|
|
||||||
ratePlan = "free-trial"
|
|
||||||
case "production":
|
|
||||||
productID = "docker-ee"
|
|
||||||
if checkResponse.ScanningEnabled {
|
|
||||||
ratePlan = "nfr-advanced"
|
|
||||||
} else {
|
|
||||||
ratePlan = "nfr-standard"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Determine if the license has already expired
|
// Determine if the license has already expired
|
||||||
|
var state string
|
||||||
if checkResponse.Expiration.Before(time.Now()) {
|
if checkResponse.Expiration.Before(time.Now()) {
|
||||||
state = "expired"
|
state = "expired"
|
||||||
} else {
|
} else {
|
||||||
state = "active"
|
state = "active"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Translate the legacy structure into the new Subscription fields
|
// For backward compatibility, show information about old (per node) licenses
|
||||||
return &model.Subscription{
|
components := checkResponse.PricingComponents
|
||||||
// Name
|
if checkResponse.MaxEngines > 0 {
|
||||||
ID: keyID, // This is not actually the same, but is unique
|
components = append(components, &model.SubscriptionPricingComponent{
|
||||||
// DockerID
|
|
||||||
ProductID: productID,
|
|
||||||
ProductRatePlan: ratePlan,
|
|
||||||
// ProductRatePlanID
|
|
||||||
// Start
|
|
||||||
Expires: &checkResponse.Expiration,
|
|
||||||
State: state,
|
|
||||||
// Eusa
|
|
||||||
PricingComponents: model.PricingComponents{
|
|
||||||
{
|
|
||||||
Name: "Nodes",
|
Name: "Nodes",
|
||||||
Value: checkResponse.MaxEngines,
|
Value: checkResponse.MaxEngines,
|
||||||
},
|
})
|
||||||
},
|
}
|
||||||
|
|
||||||
|
// Translate the legacy structure into the new Subscription fields
|
||||||
|
return &model.Subscription{
|
||||||
|
ID: checkResponse.SubscriptionID,
|
||||||
|
ProductID: checkResponse.ProductID,
|
||||||
|
ProductRatePlanID: checkResponse.RatePlanID,
|
||||||
|
Expires: &checkResponse.Expiration,
|
||||||
|
State: state,
|
||||||
|
PricingComponents: components,
|
||||||
|
GraceDays: checkResponse.GraceDays,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) SummarizeLicense(checkResponse *model.CheckResponse, keyID string) *model.Subscription {
|
func (c *client) SummarizeLicense(checkResponse *model.CheckResponse) *model.Subscription {
|
||||||
return checkResponseToSubscription(checkResponse, keyID)
|
return checkResponseToSubscription(checkResponse)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getLatestNamedConfig looks for versioned instances of configs with the
|
// getLatestNamedConfig looks for versioned instances of configs with the
|
||||||
|
|
|
@ -42,6 +42,7 @@ func (c *client) listSubscriptions(ctx context.Context, params map[string]string
|
||||||
values.Set("docker_id", params["docker_id"])
|
values.Set("docker_id", params["docker_id"])
|
||||||
values.Set("partner_account_id", params["partner_account_id"])
|
values.Set("partner_account_id", params["partner_account_id"])
|
||||||
values.Set("origin", params["origin"])
|
values.Set("origin", params["origin"])
|
||||||
|
values.Set("include_orgs", "true")
|
||||||
|
|
||||||
url := c.baseURI
|
url := c.baseURI
|
||||||
url.Path += "/api/billing/v4/subscriptions"
|
url.Path += "/api/billing/v4/subscriptions"
|
||||||
|
|
Loading…
Reference in New Issue