├── .github
└── workflows
│ └── build.yml
├── .traefik.yml
├── LICENSE
├── README.md
├── go.mod
├── go.sum
├── jwks.go
├── jwt.go
├── jwt.png
├── jwt_test.go
├── openid_configuration.go
├── sonar-project.properties
├── testing
├── ec-public.pem
└── rootca.pem
└── vendor
├── github.com
├── danwakefield
│ └── fnmatch
│ │ ├── .gitignore
│ │ ├── LICENSE
│ │ ├── README.md
│ │ └── fnmatch.go
├── go-jose
│ └── go-jose
│ │ └── v3
│ │ ├── .gitignore
│ │ ├── .golangci.yml
│ │ ├── .travis.yml
│ │ ├── CHANGELOG.md
│ │ ├── CONTRIBUTING.md
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── SECURITY.md
│ │ ├── asymmetric.go
│ │ ├── cipher
│ │ ├── cbc_hmac.go
│ │ ├── concat_kdf.go
│ │ ├── ecdh_es.go
│ │ └── key_wrap.go
│ │ ├── crypter.go
│ │ ├── doc.go
│ │ ├── encoding.go
│ │ ├── json
│ │ ├── LICENSE
│ │ ├── README.md
│ │ ├── decode.go
│ │ ├── encode.go
│ │ ├── indent.go
│ │ ├── scanner.go
│ │ ├── stream.go
│ │ └── tags.go
│ │ ├── jwe.go
│ │ ├── jwk.go
│ │ ├── jws.go
│ │ ├── opaque.go
│ │ ├── shared.go
│ │ ├── signing.go
│ │ └── symmetric.go
├── golang-jwt
│ └── jwt
│ │ └── v5
│ │ ├── .gitignore
│ │ ├── LICENSE
│ │ ├── MIGRATION_GUIDE.md
│ │ ├── README.md
│ │ ├── SECURITY.md
│ │ ├── VERSION_HISTORY.md
│ │ ├── claims.go
│ │ ├── doc.go
│ │ ├── ecdsa.go
│ │ ├── ecdsa_utils.go
│ │ ├── ed25519.go
│ │ ├── ed25519_utils.go
│ │ ├── errors.go
│ │ ├── errors_go1_20.go
│ │ ├── errors_go_other.go
│ │ ├── hmac.go
│ │ ├── map_claims.go
│ │ ├── none.go
│ │ ├── parser.go
│ │ ├── parser_option.go
│ │ ├── registered_claims.go
│ │ ├── rsa.go
│ │ ├── rsa_pss.go
│ │ ├── rsa_utils.go
│ │ ├── signing_method.go
│ │ ├── staticcheck.conf
│ │ ├── token.go
│ │ ├── token_option.go
│ │ ├── types.go
│ │ └── validator.go
└── mitchellh
│ └── mapstructure
│ ├── CHANGELOG.md
│ ├── LICENSE
│ ├── README.md
│ ├── decode_hooks.go
│ ├── error.go
│ └── mapstructure.go
├── golang.org
└── x
│ └── crypto
│ ├── LICENSE
│ ├── PATENTS
│ └── pbkdf2
│ └── pbkdf2.go
├── gopkg.in
└── yaml.v3
│ ├── LICENSE
│ ├── NOTICE
│ ├── README.md
│ ├── apic.go
│ ├── decode.go
│ ├── emitterc.go
│ ├── encode.go
│ ├── parserc.go
│ ├── readerc.go
│ ├── resolve.go
│ ├── scannerc.go
│ ├── sorter.go
│ ├── writerc.go
│ ├── yaml.go
│ ├── yamlh.go
│ └── yamlprivateh.go
└── modules.txt
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a golang project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3 |
4 | name: Build
5 | on:
6 | push:
7 | branches:
8 | - master
9 | pull_request:
10 | branches:
11 | - master
12 |
13 | permissions:
14 | contents: read
15 |
16 | jobs:
17 | build:
18 | runs-on: ubuntu-latest
19 | steps:
20 | - uses: actions/checkout@v4
21 | with:
22 | fetch-depth: 0
23 |
24 | - name: Set up Go
25 | uses: actions/setup-go@v5
26 | with:
27 | go-version: '1.24'
28 |
29 | - name: Vendor
30 | run: |
31 | go get .
32 | go mod vendor
33 |
34 | - name: Test
35 | run: go test -v -coverprofile=coverage.out -json > report.json
36 |
37 | - name: Sonar Scan
38 | uses: SonarSource/sonarqube-scan-action@v5
39 | env:
40 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
41 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
42 |
--------------------------------------------------------------------------------
/.traefik.yml:
--------------------------------------------------------------------------------
1 | displayName: Dynamic JWT Validation Middleware
2 | type: middleware
3 | import: github.com/agilezebra/jwt-middleware
4 | summary: Validates JWTs for access control. Fetches keys dynamically from whitelisted issuer JWKS as needed. Supports flexible claim checks with optional wildcards.
5 | iconPath: jwt.png
6 | testData:
7 | issuers:
8 | - https://auth.example.com
9 | secret: ThisIsAPresharedSecret
10 | require:
11 | aud: test.example.com
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Brainn Wave Limited
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 | jwks.go under http://www.apache.org/licenses/LICENSE-2.0, originally CarePay
24 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/agilezebra/jwt-middleware
2 |
3 | go 1.24.1
4 |
5 | require (
6 | github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964
7 | github.com/go-jose/go-jose/v3 v3.0.4
8 | github.com/golang-jwt/jwt/v5 v5.2.2
9 | github.com/mitchellh/mapstructure v1.5.0
10 | gopkg.in/yaml.v3 v3.0.1
11 | )
12 |
13 | require golang.org/x/crypto v0.35.0 // indirect
14 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964 h1:y5HC9v93H5EPKqaS1UYVg1uYah5Xf51mBfIoWehClUQ=
2 | github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964/go.mod h1:Xd9hchkHSWYkEqJwUGisez3G1QY8Ryz0sdWrLPMGjLk=
3 | github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
4 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
5 | github.com/go-jose/go-jose/v3 v3.0.4 h1:Wp5HA7bLQcKnf6YYao/4kpRpVMp/yf6+pJKV8WFSaNY=
6 | github.com/go-jose/go-jose/v3 v3.0.4/go.mod h1:5b+7YgP7ZICgJDBdfjZaIt+H/9L9T/YQrVfLAMboGkQ=
7 | github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
8 | github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
9 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
10 | github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
11 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
12 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
13 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
15 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
16 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
17 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
18 | github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
19 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
20 | golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
21 | golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
22 | golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
23 | golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
24 | golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
25 | golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
26 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
27 | golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
28 | golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
29 | golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
30 | golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
31 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
32 | golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
33 | golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
34 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
35 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
36 | golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
37 | golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
38 | golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
39 | golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
40 | golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
41 | golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
42 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
43 | golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
44 | golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
45 | golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
46 | golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
47 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
48 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
49 | golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
50 | golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
51 | golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
52 | golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
53 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
54 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
55 | golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
56 | golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
57 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
58 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
59 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
60 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
61 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
62 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
63 |
--------------------------------------------------------------------------------
/jwks.go:
--------------------------------------------------------------------------------
1 | // This file contains code taken from github.com/team-carepay/traefik-jwt-plugin
2 | // We would like to simply use github.com/go-jose/go-jose/v3 for the JWKS instead but traefik's yaegi interpreter messes up the unmarshalling.
3 | package jwt_middleware
4 |
5 | import (
6 | "crypto/ecdsa"
7 | "crypto/elliptic"
8 | "crypto/rsa"
9 | "crypto/sha256"
10 | "encoding/base64"
11 | "encoding/json"
12 | "fmt"
13 | "log"
14 | "math/big"
15 | "net/http"
16 | "strings"
17 | )
18 |
19 | // JSONWebKey is a JSON web key returned by the JWKS request.
20 | type JSONWebKey struct {
21 | Kid string `json:"kid"`
22 | Kty string `json:"kty"`
23 | Alg string `json:"alg"`
24 | Use string `json:"use"`
25 | X5c []string `json:"x5c"`
26 | X5t string `json:"x5t"`
27 | N string `json:"n"`
28 | E string `json:"e"`
29 | K string `json:"k,omitempty"`
30 | X string `json:"x,omitempty"`
31 | Y string `json:"y,omitempty"`
32 | D string `json:"d,omitempty"`
33 | P string `json:"p,omitempty"`
34 | Q string `json:"q,omitempty"`
35 | Dp string `json:"dp,omitempty"`
36 | Dq string `json:"dq,omitempty"`
37 | Qi string `json:"qi,omitempty"`
38 | Crv string `json:"crv,omitempty"`
39 | }
40 |
41 | // JSONWebKeySet represents a set of JSON web keys.
42 | type JSONWebKeySet struct {
43 | Keys []JSONWebKey `json:"keys"`
44 | }
45 |
46 | // FetchJWKS fetches the JSON web keys from the given URL and returns a map kid -> key.
47 | func FetchJWKS(url string, client *http.Client) (map[string]any, error) {
48 | response, err := client.Get(url)
49 | if err != nil {
50 | return nil, err
51 | }
52 | defer response.Body.Close()
53 | if response.StatusCode != http.StatusOK {
54 | return nil, fmt.Errorf("got %d from %s", response.StatusCode, url)
55 | }
56 |
57 | var jwks JSONWebKeySet
58 | err = json.NewDecoder(response.Body).Decode(&jwks)
59 | if err != nil {
60 | return nil, fmt.Errorf("%s: %w", url, err)
61 | }
62 | keys := make(map[string]any, len(jwks.Keys))
63 | for _, jwk := range jwks.Keys {
64 | if jwk.Kid == "" {
65 | jwk.Kid = JWKThumbprint(jwk)
66 | }
67 | switch jwk.Kty {
68 | case "RSA":
69 | {
70 | nBytes, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(jwk.N, "="))
71 | if err != nil {
72 | log.Printf("error decoding N: %v for kid: %v", err, jwk.Kid)
73 | break
74 | }
75 | eBytes, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(jwk.E, "="))
76 | if err != nil {
77 | log.Printf("error decoding E: %v for kid: %v", err, jwk.Kid)
78 | break
79 | }
80 | keys[jwk.Kid] = &rsa.PublicKey{
81 | N: new(big.Int).SetBytes(nBytes),
82 | E: int(new(big.Int).SetBytes(eBytes).Uint64()),
83 | }
84 | }
85 | case "EC":
86 | {
87 | var curve elliptic.Curve
88 | switch jwk.Crv {
89 | case "P-256":
90 | curve = elliptic.P256()
91 | case "P-384":
92 | curve = elliptic.P384()
93 | case "P-521":
94 | curve = elliptic.P521()
95 | default:
96 | switch jwk.Alg {
97 | case "ES256":
98 | curve = elliptic.P256()
99 | case "ES384":
100 | curve = elliptic.P384()
101 | case "ES512":
102 | curve = elliptic.P521()
103 | default:
104 | curve = elliptic.P256()
105 | }
106 | }
107 | xBytes, err := base64.RawURLEncoding.DecodeString(jwk.X)
108 | if err != nil {
109 | break
110 | }
111 | yBytes, err := base64.RawURLEncoding.DecodeString(jwk.Y)
112 | if err != nil {
113 | break
114 | }
115 | keys[jwk.Kid] = &ecdsa.PublicKey{
116 | Curve: curve,
117 | X: new(big.Int).SetBytes(xBytes),
118 | Y: new(big.Int).SetBytes(yBytes),
119 | }
120 | }
121 | }
122 | }
123 |
124 | return keys, nil
125 | }
126 |
127 | // JWKThumbprint creates a JWK thumbprint out of pub
128 | // as specified in https://tools.ietf.org/html/rfc7638.
129 | func JWKThumbprint(jwk JSONWebKey) string {
130 | var text string
131 | switch jwk.Kty {
132 | case "RSA":
133 | text = fmt.Sprintf(`{"e":"%s","kty":"RSA","n":"%s"}`, jwk.E, jwk.N)
134 | case "EC":
135 | text = fmt.Sprintf(`{"crv":"P-256","kty":"EC","x":"%s","y":"%s"}`, jwk.X, jwk.Y)
136 | }
137 | bytes := sha256.Sum256([]byte(text))
138 | return base64.RawURLEncoding.EncodeToString(bytes[:])
139 | }
140 |
--------------------------------------------------------------------------------
/jwt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/agilezebra/jwt-middleware/bee314e889f3973a2fb3b9959a8a6012cd94e96c/jwt.png
--------------------------------------------------------------------------------
/openid_configuration.go:
--------------------------------------------------------------------------------
1 | package jwt_middleware
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "net/http"
7 | )
8 |
9 | type OpenIDConfiguration struct {
10 | JWKSURI string `json:"jwks_uri"`
11 | }
12 |
13 | // FetchOpenIDConfiguration fetches the OpenID configuration from the given URL.
14 | func FetchOpenIDConfiguration(url string, client *http.Client) (*OpenIDConfiguration, error) {
15 | response, err := client.Get(url)
16 | if err != nil {
17 | return nil, err
18 | }
19 | defer response.Body.Close()
20 |
21 | if response.StatusCode != http.StatusOK {
22 | return nil, fmt.Errorf("got %d from %s", response.StatusCode, url)
23 | }
24 | var config OpenIDConfiguration
25 | err = json.NewDecoder(response.Body).Decode(&config)
26 | if err != nil {
27 | return nil, fmt.Errorf("%s: %w", url, err)
28 | }
29 |
30 | return &config, nil
31 | }
32 |
--------------------------------------------------------------------------------
/sonar-project.properties:
--------------------------------------------------------------------------------
1 | sonar.projectKey=agilezebra_jwt-middleware
2 | sonar.organization=agilezebra
3 | sonar.projectName=jwt-middleware
4 | sonar.sources=.
5 | sonar.tests=.
6 | sonar.exclusions=**/*_test.go
7 | sonar.test.inclusions=**/*_test.go
8 | sonar.go.coverage.reportPaths=coverage.out
9 | sonar.go.tests.reportPaths=report.json
10 |
--------------------------------------------------------------------------------
/testing/ec-public.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN EC PUBLIC KEY-----
2 | MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEE7gFCo/g2PQmC3i5kIqVgCCzr2D1
3 | nbCeipqfvK1rkqmKfhb7rlVehfC7ITUAy8NIvQ/AsXClvgHDv55BfOoL6w==
4 | -----END EC PUBLIC KEY-----
5 |
--------------------------------------------------------------------------------
/testing/rootca.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIDJzCCAg+gAwIBAgIUDDYN8pGCpUC6tsqDW4meIXsmN04wDQYJKoZIhvcNAQEL
3 | BQAwIzELMAkGA1UEBhMCVUsxFDASBgNVBAoMC0FnaWxlIFplYnJhMB4XDTI1MDMx
4 | MTE0MTU1MloXDTM1MDMwOTE0MTU1MlowIzELMAkGA1UEBhMCVUsxFDASBgNVBAoM
5 | C0FnaWxlIFplYnJhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA70Gs
6 | A3QEKB94Eqyt+V07qDNtykhlyOLSiGIRk1/Slr5B1mTY8Mt88gg8MFldyVukjze+
7 | /5GT/lZ3plMMiA7wnpJ683iWqMVOzQTtYlgcMknnrRJhHuDIGmcdakudXl484emE
8 | 9iz+cWgl2cw1rb0rtNC1koQ90MohcTqW+5By0TUaulf80ZcJbGFG8LTqVKVJatET
9 | QedgrYR3tIR6VRtj7pnFZ1w9gZhpPL26mrMg3Wk3GHf/j48jebHVYbeuuSoBXJX8
10 | rGmfCtwzMWqyZvMU9MRP6KpPu20UIOuzau6JyD22RhlLSrX/1eI9Et0IMqEF/iM/
11 | EGpTGDJTeX3bJavzAQIDAQABo1MwUTAdBgNVHQ4EFgQUwR3igK8QvKXQ3JuGlYUc
12 | 1jHwBqUwHwYDVR0jBBgwFoAUwR3igK8QvKXQ3JuGlYUc1jHwBqUwDwYDVR0TAQH/
13 | BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAoEgu6gQTf8Br0Id7Jp6Oht6XSG0o
14 | RtYJ4SwWD0U1acJpWKgtTkBA9cfGMYngFzUe9Xmxt1iBSCJtbQ/SQj5x0vcXsoR0
15 | zWBnihf3XERnJOyLWR7cUCfVYEu0xFCNrc1m5Wzj4IG2NJBTtiIiAdnTbEcBd7hk
16 | f7Vy+al187qn3HQcwdRfMatjFrrM92tHvd79VJsZcgj8Yl3QcgZFIQ2O+PtrXxLR
17 | 2auMwVTxdRe0QUT6zvtZGf1niNH5s8DBVeDWqBArlC7M/HuLj6QOIMDEI2aC3yS1
18 | LT12fZ0MWBjfGc90EEJ9z4/CRUWMdtlOaLnXinyrvOH+SSTJD8xfwKqH6g==
19 | -----END CERTIFICATE-----
--------------------------------------------------------------------------------
/vendor/github.com/danwakefield/fnmatch/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled Object files, Static and Dynamic libs (Shared Objects)
2 | *.o
3 | *.a
4 | *.so
5 |
6 | # Folders
7 | _obj
8 | _test
9 |
10 | # Architecture specific extensions/prefixes
11 | *.[568vq]
12 | [568vq].out
13 |
14 | *.cgo1.go
15 | *.cgo2.c
16 | _cgo_defun.c
17 | _cgo_gotypes.go
18 | _cgo_export.*
19 |
20 | _testmain.go
21 |
22 | *.exe
23 | *.test
24 | *.prof
25 |
--------------------------------------------------------------------------------
/vendor/github.com/danwakefield/fnmatch/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2016, Daniel Wakefield
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without
5 | modification, are permitted provided that the following conditions are met:
6 |
7 | * Redistributions of source code must retain the above copyright notice, this
8 | list of conditions and the following disclaimer.
9 |
10 | * Redistributions in binary form must reproduce the above copyright notice,
11 | this list of conditions and the following disclaimer in the documentation
12 | and/or other materials provided with the distribution.
13 |
14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
15 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
18 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
21 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
22 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 |
--------------------------------------------------------------------------------
/vendor/github.com/danwakefield/fnmatch/README.md:
--------------------------------------------------------------------------------
1 | # fnmatch
2 | Updated clone of kballards golang fnmatch gist (https://gist.github.com/kballard/272720)
3 |
4 |
5 |
--------------------------------------------------------------------------------
/vendor/github.com/danwakefield/fnmatch/fnmatch.go:
--------------------------------------------------------------------------------
1 | // Provide string-matching based on fnmatch.3
2 | package fnmatch
3 |
4 | // There are a few issues that I believe to be bugs, but this implementation is
5 | // based as closely as possible on BSD fnmatch. These bugs are present in the
6 | // source of BSD fnmatch, and so are replicated here. The issues are as follows:
7 | //
8 | // * FNM_PERIOD is no longer observed after the first * in a pattern
9 | // This only applies to matches done with FNM_PATHNAME as well
10 | // * FNM_PERIOD doesn't apply to ranges. According to the documentation,
11 | // a period must be matched explicitly, but a range will match it too
12 |
13 | import (
14 | "unicode"
15 | "unicode/utf8"
16 | )
17 |
18 | const (
19 | FNM_NOESCAPE = (1 << iota)
20 | FNM_PATHNAME
21 | FNM_PERIOD
22 |
23 | FNM_LEADING_DIR
24 | FNM_CASEFOLD
25 |
26 | FNM_IGNORECASE = FNM_CASEFOLD
27 | FNM_FILE_NAME = FNM_PATHNAME
28 | )
29 |
30 | func unpackRune(str *string) rune {
31 | rune, size := utf8.DecodeRuneInString(*str)
32 | *str = (*str)[size:]
33 | return rune
34 | }
35 |
36 | // Matches the pattern against the string, with the given flags,
37 | // and returns true if the match is successful.
38 | // This function should match fnmatch.3 as closely as possible.
39 | func Match(pattern, s string, flags int) bool {
40 | // The implementation for this function was patterned after the BSD fnmatch.c
41 | // source found at http://src.gnu-darwin.org/src/contrib/csup/fnmatch.c.html
42 | noescape := (flags&FNM_NOESCAPE != 0)
43 | pathname := (flags&FNM_PATHNAME != 0)
44 | period := (flags&FNM_PERIOD != 0)
45 | leadingdir := (flags&FNM_LEADING_DIR != 0)
46 | casefold := (flags&FNM_CASEFOLD != 0)
47 | // the following is some bookkeeping that the original fnmatch.c implementation did not do
48 | // We are forced to do this because we're not keeping indexes into C strings but rather
49 | // processing utf8-encoded strings. Use a custom unpacker to maintain our state for us
50 | sAtStart := true
51 | sLastAtStart := true
52 | sLastSlash := false
53 | sLastUnpacked := rune(0)
54 | unpackS := func() rune {
55 | sLastSlash = (sLastUnpacked == '/')
56 | sLastUnpacked = unpackRune(&s)
57 | sLastAtStart = sAtStart
58 | sAtStart = false
59 | return sLastUnpacked
60 | }
61 | for len(pattern) > 0 {
62 | c := unpackRune(&pattern)
63 | switch c {
64 | case '?':
65 | if len(s) == 0 {
66 | return false
67 | }
68 | sc := unpackS()
69 | if pathname && sc == '/' {
70 | return false
71 | }
72 | if period && sc == '.' && (sLastAtStart || (pathname && sLastSlash)) {
73 | return false
74 | }
75 | case '*':
76 | // collapse multiple *'s
77 | // don't use unpackRune here, the only char we care to detect is ASCII
78 | for len(pattern) > 0 && pattern[0] == '*' {
79 | pattern = pattern[1:]
80 | }
81 | if period && s[0] == '.' && (sAtStart || (pathname && sLastUnpacked == '/')) {
82 | return false
83 | }
84 | // optimize for patterns with * at end or before /
85 | if len(pattern) == 0 {
86 | if pathname {
87 | return leadingdir || (strchr(s, '/') == -1)
88 | } else {
89 | return true
90 | }
91 | return !(pathname && strchr(s, '/') >= 0)
92 | } else if pathname && pattern[0] == '/' {
93 | offset := strchr(s, '/')
94 | if offset == -1 {
95 | return false
96 | } else {
97 | // we already know our pattern and string have a /, skip past it
98 | s = s[offset:] // use unpackS here to maintain our bookkeeping state
99 | unpackS()
100 | pattern = pattern[1:] // we know / is one byte long
101 | break
102 | }
103 | }
104 | // general case, recurse
105 | for test := s; len(test) > 0; unpackRune(&test) {
106 | // I believe the (flags &^ FNM_PERIOD) is a bug when FNM_PATHNAME is specified
107 | // but this follows exactly from how fnmatch.c implements it
108 | if Match(pattern, test, (flags &^ FNM_PERIOD)) {
109 | return true
110 | } else if pathname && test[0] == '/' {
111 | break
112 | }
113 | }
114 | return false
115 | case '[':
116 | if len(s) == 0 {
117 | return false
118 | }
119 | if pathname && s[0] == '/' {
120 | return false
121 | }
122 | sc := unpackS()
123 | if !rangematch(&pattern, sc, flags) {
124 | return false
125 | }
126 | case '\\':
127 | if !noescape {
128 | if len(pattern) > 0 {
129 | c = unpackRune(&pattern)
130 | }
131 | }
132 | fallthrough
133 | default:
134 | if len(s) == 0 {
135 | return false
136 | }
137 | sc := unpackS()
138 | switch {
139 | case sc == c:
140 | case casefold && unicode.ToLower(sc) == unicode.ToLower(c):
141 | default:
142 | return false
143 | }
144 | }
145 | }
146 | return len(s) == 0 || (leadingdir && s[0] == '/')
147 | }
148 |
149 | func rangematch(pattern *string, test rune, flags int) bool {
150 | if len(*pattern) == 0 {
151 | return false
152 | }
153 | casefold := (flags&FNM_CASEFOLD != 0)
154 | noescape := (flags&FNM_NOESCAPE != 0)
155 | if casefold {
156 | test = unicode.ToLower(test)
157 | }
158 | var negate, matched bool
159 | if (*pattern)[0] == '^' || (*pattern)[0] == '!' {
160 | negate = true
161 | (*pattern) = (*pattern)[1:]
162 | }
163 | for !matched && len(*pattern) > 1 && (*pattern)[0] != ']' {
164 | c := unpackRune(pattern)
165 | if !noescape && c == '\\' {
166 | if len(*pattern) > 1 {
167 | c = unpackRune(pattern)
168 | } else {
169 | return false
170 | }
171 | }
172 | if casefold {
173 | c = unicode.ToLower(c)
174 | }
175 | if (*pattern)[0] == '-' && len(*pattern) > 1 && (*pattern)[1] != ']' {
176 | unpackRune(pattern) // skip the -
177 | c2 := unpackRune(pattern)
178 | if !noescape && c2 == '\\' {
179 | if len(*pattern) > 0 {
180 | c2 = unpackRune(pattern)
181 | } else {
182 | return false
183 | }
184 | }
185 | if casefold {
186 | c2 = unicode.ToLower(c2)
187 | }
188 | // this really should be more intelligent, but it looks like
189 | // fnmatch.c does simple int comparisons, therefore we will as well
190 | if c <= test && test <= c2 {
191 | matched = true
192 | }
193 | } else if c == test {
194 | matched = true
195 | }
196 | }
197 | // skip past the rest of the pattern
198 | ok := false
199 | for !ok && len(*pattern) > 0 {
200 | c := unpackRune(pattern)
201 | if c == '\\' && len(*pattern) > 0 {
202 | unpackRune(pattern)
203 | } else if c == ']' {
204 | ok = true
205 | }
206 | }
207 | return ok && matched != negate
208 | }
209 |
210 | // define strchr because strings.Index() seems a bit overkill
211 | // returns the index of c in s, or -1 if there is no match
212 | func strchr(s string, c rune) int {
213 | for i, sc := range s {
214 | if sc == c {
215 | return i
216 | }
217 | }
218 | return -1
219 | }
220 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/.gitignore:
--------------------------------------------------------------------------------
1 | jose-util/jose-util
2 | jose-util.t.err
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/.golangci.yml:
--------------------------------------------------------------------------------
1 | # https://github.com/golangci/golangci-lint
2 |
3 | run:
4 | skip-files:
5 | - doc_test.go
6 | modules-download-mode: readonly
7 |
8 | linters:
9 | enable-all: true
10 | disable:
11 | - gochecknoglobals
12 | - goconst
13 | - lll
14 | - maligned
15 | - nakedret
16 | - scopelint
17 | - unparam
18 | - funlen # added in 1.18 (requires go-jose changes before it can be enabled)
19 |
20 | linters-settings:
21 | gocyclo:
22 | min-complexity: 35
23 |
24 | issues:
25 | exclude-rules:
26 | - text: "don't use ALL_CAPS in Go names"
27 | linters:
28 | - golint
29 | - text: "hardcoded credentials"
30 | linters:
31 | - gosec
32 | - text: "weak cryptographic primitive"
33 | linters:
34 | - gosec
35 | - path: json/
36 | linters:
37 | - dupl
38 | - errcheck
39 | - gocritic
40 | - gocyclo
41 | - golint
42 | - govet
43 | - ineffassign
44 | - staticcheck
45 | - structcheck
46 | - stylecheck
47 | - unused
48 | - path: _test\.go
49 | linters:
50 | - scopelint
51 | - path: jwk.go
52 | linters:
53 | - gocyclo
54 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/.travis.yml:
--------------------------------------------------------------------------------
1 | language: go
2 |
3 | matrix:
4 | fast_finish: true
5 | allow_failures:
6 | - go: tip
7 |
8 | go:
9 | - "1.13.x"
10 | - "1.14.x"
11 | - tip
12 |
13 | before_script:
14 | - export PATH=$HOME/.local/bin:$PATH
15 |
16 | before_install:
17 | - go get -u github.com/mattn/goveralls github.com/wadey/gocovmerge
18 | - curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh -s -- -b $(go env GOPATH)/bin v1.18.0
19 | - pip install cram --user
20 |
21 | script:
22 | - go test -v -covermode=count -coverprofile=profile.cov .
23 | - go test -v -covermode=count -coverprofile=cryptosigner/profile.cov ./cryptosigner
24 | - go test -v -covermode=count -coverprofile=cipher/profile.cov ./cipher
25 | - go test -v -covermode=count -coverprofile=jwt/profile.cov ./jwt
26 | - go test -v ./json # no coverage for forked encoding/json package
27 | - golangci-lint run
28 | - cd jose-util && go build && PATH=$PWD:$PATH cram -v jose-util.t # cram tests jose-util
29 | - cd ..
30 |
31 | after_success:
32 | - gocovmerge *.cov */*.cov > merged.coverprofile
33 | - goveralls -coverprofile merged.coverprofile -service=travis-ci
34 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # v4.0.1
2 |
3 | ## Fixed
4 |
5 | - An attacker could send a JWE containing compressed data that used large
6 | amounts of memory and CPU when decompressed by `Decrypt` or `DecryptMulti`.
7 | Those functions now return an error if the decompressed data would exceed
8 | 250kB or 10x the compressed size (whichever is larger). Thanks to
9 | Enze Wang@Alioth and Jianjun Chen@Zhongguancun Lab (@zer0yu and @chenjj)
10 | for reporting.
11 |
12 | # v4.0.0
13 |
14 | This release makes some breaking changes in order to more thoroughly
15 | address the vulnerabilities discussed in [Three New Attacks Against JSON Web
16 | Tokens][1], "Sign/encrypt confusion", "Billion hash attack", and "Polyglot
17 | token".
18 |
19 | ## Changed
20 |
21 | - Limit JWT encryption types (exclude password or public key types) (#78)
22 | - Enforce minimum length for HMAC keys (#85)
23 | - jwt: match any audience in a list, rather than requiring all audiences (#81)
24 | - jwt: accept only Compact Serialization (#75)
25 | - jws: Add expected algorithms for signatures (#74)
26 | - Require specifying expected algorithms for ParseEncrypted,
27 | ParseSigned, ParseDetached, jwt.ParseEncrypted, jwt.ParseSigned,
28 | jwt.ParseSignedAndEncrypted (#69, #74)
29 | - Usually there is a small, known set of appropriate algorithms for a program
30 | to use and it's a mistake to allow unexpected algorithms. For instance the
31 | "billion hash attack" relies in part on programs accepting the PBES2
32 | encryption algorithm and doing the necessary work even if they weren't
33 | specifically configured to allow PBES2.
34 | - Revert "Strip padding off base64 strings" (#82)
35 | - The specs require base64url encoding without padding.
36 | - Minimum supported Go version is now 1.21
37 |
38 | ## Added
39 |
40 | - ParseSignedCompact, ParseSignedJSON, ParseEncryptedCompact, ParseEncryptedJSON.
41 | - These allow parsing a specific serialization, as opposed to ParseSigned and
42 | ParseEncrypted, which try to automatically detect which serialization was
43 | provided. It's common to require a specific serialization for a specific
44 | protocol - for instance JWT requires Compact serialization.
45 |
46 | [1]: https://i.blackhat.com/BH-US-23/Presentations/US-23-Tervoort-Three-New-Attacks-Against-JSON-Web-Tokens.pdf
47 |
48 | # v3.0.3
49 |
50 | ## Fixed
51 |
52 | - Limit decompression output size to prevent a DoS. Backport from v4.0.1.
53 |
54 | # v3.0.2
55 |
56 | ## Fixed
57 |
58 | - DecryptMulti: handle decompression error (#19)
59 |
60 | ## Changed
61 |
62 | - jwe/CompactSerialize: improve performance (#67)
63 | - Increase the default number of PBKDF2 iterations to 600k (#48)
64 | - Return the proper algorithm for ECDSA keys (#45)
65 |
66 | ## Added
67 |
68 | - Add Thumbprint support for opaque signers (#38)
69 |
70 | # v3.0.1
71 |
72 | ## Fixed
73 |
74 | - Security issue: an attacker specifying a large "p2c" value can cause
75 | JSONWebEncryption.Decrypt and JSONWebEncryption.DecryptMulti to consume large
76 | amounts of CPU, causing a DoS. Thanks to Matt Schwager (@mschwager) for the
77 | disclosure and to Tom Tervoort for originally publishing the category of attack.
78 | https://i.blackhat.com/BH-US-23/Presentations/US-23-Tervoort-Three-New-Attacks-Against-JSON-Web-Tokens.pdf
79 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | If you would like to contribute code to go-jose you can do so through GitHub by
4 | forking the repository and sending a pull request.
5 |
6 | When submitting code, please make every effort to follow existing conventions
7 | and style in order to keep the code as readable as possible. Please also make
8 | sure all tests pass by running `go test`, and format your code with `go fmt`.
9 | We also recommend using `golint` and `errcheck`.
10 |
11 | Before your code can be accepted into the project you must also sign the
12 | Individual Contributor License Agreement. We use [cla-assistant.io][1] and you
13 | will be prompted to sign once a pull request is opened.
14 |
15 | [1]: https://cla-assistant.io/
16 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/README.md:
--------------------------------------------------------------------------------
1 | # Go JOSE
2 |
3 | ### Versions
4 |
5 | [Version 4](https://github.com/go-jose/go-jose)
6 | ([branch](https://github.com/go-jose/go-jose/),
7 | [doc](https://pkg.go.dev/github.com/go-jose/go-jose/v4), [releases](https://github.com/go-jose/go-jose/releases)) is the current stable version:
8 |
9 | import "github.com/go-jose/go-jose/v4"
10 |
11 | The old [square/go-jose](https://github.com/square/go-jose) repo contains the prior v1 and v2 versions, which
12 | are deprecated.
13 |
14 | ### Summary
15 |
16 | Package jose aims to provide an implementation of the Javascript Object Signing
17 | and Encryption set of standards. This includes support for JSON Web Encryption,
18 | JSON Web Signature, and JSON Web Token standards.
19 |
20 | **Disclaimer**: This library contains encryption software that is subject to
21 | the U.S. Export Administration Regulations. You may not export, re-export,
22 | transfer or download this code or any part of it in violation of any United
23 | States law, directive or regulation. In particular this software may not be
24 | exported or re-exported in any form or on any media to Iran, North Sudan,
25 | Syria, Cuba, or North Korea, or to denied persons or entities mentioned on any
26 | US maintained blocked list.
27 |
28 | ## Overview
29 |
30 | The implementation follows the
31 | [JSON Web Encryption](https://dx.doi.org/10.17487/RFC7516) (RFC 7516),
32 | [JSON Web Signature](https://dx.doi.org/10.17487/RFC7515) (RFC 7515), and
33 | [JSON Web Token](https://dx.doi.org/10.17487/RFC7519) (RFC 7519) specifications.
34 | Tables of supported algorithms are shown below. The library supports both
35 | the compact and JWS/JWE JSON Serialization formats, and has optional support for
36 | multiple recipients. It also comes with a small command-line utility
37 | ([`jose-util`](https://pkg.go.dev/github.com/go-jose/go-jose/jose-util))
38 | for dealing with JOSE messages in a shell.
39 |
40 | **Note**: We use a forked version of the `encoding/json` package from the Go
41 | standard library which uses case-sensitive matching for member names (instead
42 | of [case-insensitive matching](https://www.ietf.org/mail-archive/web/json/current/msg03763.html)).
43 | This is to avoid differences in interpretation of messages between go-jose and
44 | libraries in other languages.
45 |
46 | ### Supported algorithms
47 |
48 | See below for a table of supported algorithms. Algorithm identifiers match
49 | the names in the [JSON Web Algorithms](https://dx.doi.org/10.17487/RFC7518)
50 | standard where possible. The Godoc reference has a list of constants.
51 |
52 | Key encryption | Algorithm identifier(s)
53 | :------------------------- | :------------------------------
54 | RSA-PKCS#1v1.5 | RSA1_5
55 | RSA-OAEP | RSA-OAEP, RSA-OAEP-256
56 | AES key wrap | A128KW, A192KW, A256KW
57 | AES-GCM key wrap | A128GCMKW, A192GCMKW, A256GCMKW
58 | ECDH-ES + AES key wrap | ECDH-ES+A128KW, ECDH-ES+A192KW, ECDH-ES+A256KW
59 | ECDH-ES (direct) | ECDH-ES1
60 | Direct encryption | dir1
61 |
62 | 1. Not supported in multi-recipient mode
63 |
64 | Signing / MAC | Algorithm identifier(s)
65 | :------------------------- | :------------------------------
66 | RSASSA-PKCS#1v1.5 | RS256, RS384, RS512
67 | RSASSA-PSS | PS256, PS384, PS512
68 | HMAC | HS256, HS384, HS512
69 | ECDSA | ES256, ES384, ES512
70 | Ed25519 | EdDSA2
71 |
72 | 2. Only available in version 2 of the package
73 |
74 | Content encryption | Algorithm identifier(s)
75 | :------------------------- | :------------------------------
76 | AES-CBC+HMAC | A128CBC-HS256, A192CBC-HS384, A256CBC-HS512
77 | AES-GCM | A128GCM, A192GCM, A256GCM
78 |
79 | Compression | Algorithm identifiers(s)
80 | :------------------------- | -------------------------------
81 | DEFLATE (RFC 1951) | DEF
82 |
83 | ### Supported key types
84 |
85 | See below for a table of supported key types. These are understood by the
86 | library, and can be passed to corresponding functions such as `NewEncrypter` or
87 | `NewSigner`. Each of these keys can also be wrapped in a JWK if desired, which
88 | allows attaching a key id.
89 |
90 | Algorithm(s) | Corresponding types
91 | :------------------------- | -------------------------------
92 | RSA | *[rsa.PublicKey](https://pkg.go.dev/crypto/rsa/#PublicKey), *[rsa.PrivateKey](https://pkg.go.dev/crypto/rsa/#PrivateKey)
93 | ECDH, ECDSA | *[ecdsa.PublicKey](https://pkg.go.dev/crypto/ecdsa/#PublicKey), *[ecdsa.PrivateKey](https://pkg.go.dev/crypto/ecdsa/#PrivateKey)
94 | EdDSA1 | [ed25519.PublicKey](https://pkg.go.dev/crypto/ed25519#PublicKey), [ed25519.PrivateKey](https://pkg.go.dev/crypto/ed25519#PrivateKey)
95 | AES, HMAC | []byte
96 |
97 | 1. Only available in version 2 or later of the package
98 |
99 | ## Examples
100 |
101 | [](https://pkg.go.dev/github.com/go-jose/go-jose/v3)
102 | [](https://pkg.go.dev/github.com/go-jose/go-jose/v3/jwt)
103 |
104 | Examples can be found in the Godoc
105 | reference for this package. The
106 | [`jose-util`](https://github.com/go-jose/go-jose/tree/v3/jose-util)
107 | subdirectory also contains a small command-line utility which might be useful
108 | as an example as well.
109 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 | This document explains how to contact the Let's Encrypt security team to report security vulnerabilities.
3 |
4 | ## Supported Versions
5 | | Version | Supported |
6 | | ------- | ----------|
7 | | >= v3 | ✓ |
8 | | v2 | ✗ |
9 | | v1 | ✗ |
10 |
11 | ## Reporting a vulnerability
12 |
13 | Please see [https://letsencrypt.org/contact/#security](https://letsencrypt.org/contact/#security) for the email address to report a vulnerability. Ensure that the subject line for your report contains the word `vulnerability` and is descriptive. Your email should be acknowledged within 24 hours. If you do not receive a response within 24 hours, please follow-up again with another email.
14 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/cipher/cbc_hmac.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package josecipher
18 |
19 | import (
20 | "bytes"
21 | "crypto/cipher"
22 | "crypto/hmac"
23 | "crypto/sha256"
24 | "crypto/sha512"
25 | "crypto/subtle"
26 | "encoding/binary"
27 | "errors"
28 | "hash"
29 | )
30 |
31 | const (
32 | nonceBytes = 16
33 | )
34 |
35 | // NewCBCHMAC instantiates a new AEAD based on CBC+HMAC.
36 | func NewCBCHMAC(key []byte, newBlockCipher func([]byte) (cipher.Block, error)) (cipher.AEAD, error) {
37 | keySize := len(key) / 2
38 | integrityKey := key[:keySize]
39 | encryptionKey := key[keySize:]
40 |
41 | blockCipher, err := newBlockCipher(encryptionKey)
42 | if err != nil {
43 | return nil, err
44 | }
45 |
46 | var hash func() hash.Hash
47 | switch keySize {
48 | case 16:
49 | hash = sha256.New
50 | case 24:
51 | hash = sha512.New384
52 | case 32:
53 | hash = sha512.New
54 | }
55 |
56 | return &cbcAEAD{
57 | hash: hash,
58 | blockCipher: blockCipher,
59 | authtagBytes: keySize,
60 | integrityKey: integrityKey,
61 | }, nil
62 | }
63 |
64 | // An AEAD based on CBC+HMAC
65 | type cbcAEAD struct {
66 | hash func() hash.Hash
67 | authtagBytes int
68 | integrityKey []byte
69 | blockCipher cipher.Block
70 | }
71 |
72 | func (ctx *cbcAEAD) NonceSize() int {
73 | return nonceBytes
74 | }
75 |
76 | func (ctx *cbcAEAD) Overhead() int {
77 | // Maximum overhead is block size (for padding) plus auth tag length, where
78 | // the length of the auth tag is equivalent to the key size.
79 | return ctx.blockCipher.BlockSize() + ctx.authtagBytes
80 | }
81 |
82 | // Seal encrypts and authenticates the plaintext.
83 | func (ctx *cbcAEAD) Seal(dst, nonce, plaintext, data []byte) []byte {
84 | // Output buffer -- must take care not to mangle plaintext input.
85 | ciphertext := make([]byte, uint64(len(plaintext))+uint64(ctx.Overhead()))[:len(plaintext)]
86 | copy(ciphertext, plaintext)
87 | ciphertext = padBuffer(ciphertext, ctx.blockCipher.BlockSize())
88 |
89 | cbc := cipher.NewCBCEncrypter(ctx.blockCipher, nonce)
90 |
91 | cbc.CryptBlocks(ciphertext, ciphertext)
92 | authtag := ctx.computeAuthTag(data, nonce, ciphertext)
93 |
94 | ret, out := resize(dst, uint64(len(dst))+uint64(len(ciphertext))+uint64(len(authtag)))
95 | copy(out, ciphertext)
96 | copy(out[len(ciphertext):], authtag)
97 |
98 | return ret
99 | }
100 |
101 | // Open decrypts and authenticates the ciphertext.
102 | func (ctx *cbcAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
103 | if len(ciphertext) < ctx.authtagBytes {
104 | return nil, errors.New("go-jose/go-jose: invalid ciphertext (too short)")
105 | }
106 |
107 | offset := len(ciphertext) - ctx.authtagBytes
108 | expectedTag := ctx.computeAuthTag(data, nonce, ciphertext[:offset])
109 | match := subtle.ConstantTimeCompare(expectedTag, ciphertext[offset:])
110 | if match != 1 {
111 | return nil, errors.New("go-jose/go-jose: invalid ciphertext (auth tag mismatch)")
112 | }
113 |
114 | cbc := cipher.NewCBCDecrypter(ctx.blockCipher, nonce)
115 |
116 | // Make copy of ciphertext buffer, don't want to modify in place
117 | buffer := append([]byte{}, ciphertext[:offset]...)
118 |
119 | if len(buffer)%ctx.blockCipher.BlockSize() > 0 {
120 | return nil, errors.New("go-jose/go-jose: invalid ciphertext (invalid length)")
121 | }
122 |
123 | cbc.CryptBlocks(buffer, buffer)
124 |
125 | // Remove padding
126 | plaintext, err := unpadBuffer(buffer, ctx.blockCipher.BlockSize())
127 | if err != nil {
128 | return nil, err
129 | }
130 |
131 | ret, out := resize(dst, uint64(len(dst))+uint64(len(plaintext)))
132 | copy(out, plaintext)
133 |
134 | return ret, nil
135 | }
136 |
137 | // Compute an authentication tag
138 | func (ctx *cbcAEAD) computeAuthTag(aad, nonce, ciphertext []byte) []byte {
139 | buffer := make([]byte, uint64(len(aad))+uint64(len(nonce))+uint64(len(ciphertext))+8)
140 | n := 0
141 | n += copy(buffer, aad)
142 | n += copy(buffer[n:], nonce)
143 | n += copy(buffer[n:], ciphertext)
144 | binary.BigEndian.PutUint64(buffer[n:], uint64(len(aad))*8)
145 |
146 | // According to documentation, Write() on hash.Hash never fails.
147 | hmac := hmac.New(ctx.hash, ctx.integrityKey)
148 | _, _ = hmac.Write(buffer)
149 |
150 | return hmac.Sum(nil)[:ctx.authtagBytes]
151 | }
152 |
153 | // resize ensures that the given slice has a capacity of at least n bytes.
154 | // If the capacity of the slice is less than n, a new slice is allocated
155 | // and the existing data will be copied.
156 | func resize(in []byte, n uint64) (head, tail []byte) {
157 | if uint64(cap(in)) >= n {
158 | head = in[:n]
159 | } else {
160 | head = make([]byte, n)
161 | copy(head, in)
162 | }
163 |
164 | tail = head[len(in):]
165 | return
166 | }
167 |
168 | // Apply padding
169 | func padBuffer(buffer []byte, blockSize int) []byte {
170 | missing := blockSize - (len(buffer) % blockSize)
171 | ret, out := resize(buffer, uint64(len(buffer))+uint64(missing))
172 | padding := bytes.Repeat([]byte{byte(missing)}, missing)
173 | copy(out, padding)
174 | return ret
175 | }
176 |
177 | // Remove padding
178 | func unpadBuffer(buffer []byte, blockSize int) ([]byte, error) {
179 | if len(buffer)%blockSize != 0 {
180 | return nil, errors.New("go-jose/go-jose: invalid padding")
181 | }
182 |
183 | last := buffer[len(buffer)-1]
184 | count := int(last)
185 |
186 | if count == 0 || count > blockSize || count > len(buffer) {
187 | return nil, errors.New("go-jose/go-jose: invalid padding")
188 | }
189 |
190 | padding := bytes.Repeat([]byte{last}, count)
191 | if !bytes.HasSuffix(buffer, padding) {
192 | return nil, errors.New("go-jose/go-jose: invalid padding")
193 | }
194 |
195 | return buffer[:len(buffer)-count], nil
196 | }
197 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/cipher/concat_kdf.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package josecipher
18 |
19 | import (
20 | "crypto"
21 | "encoding/binary"
22 | "hash"
23 | "io"
24 | )
25 |
26 | type concatKDF struct {
27 | z, info []byte
28 | i uint32
29 | cache []byte
30 | hasher hash.Hash
31 | }
32 |
33 | // NewConcatKDF builds a KDF reader based on the given inputs.
34 | func NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader {
35 | buffer := make([]byte, uint64(len(algID))+uint64(len(ptyUInfo))+uint64(len(ptyVInfo))+uint64(len(supPubInfo))+uint64(len(supPrivInfo)))
36 | n := 0
37 | n += copy(buffer, algID)
38 | n += copy(buffer[n:], ptyUInfo)
39 | n += copy(buffer[n:], ptyVInfo)
40 | n += copy(buffer[n:], supPubInfo)
41 | copy(buffer[n:], supPrivInfo)
42 |
43 | hasher := hash.New()
44 |
45 | return &concatKDF{
46 | z: z,
47 | info: buffer,
48 | hasher: hasher,
49 | cache: []byte{},
50 | i: 1,
51 | }
52 | }
53 |
54 | func (ctx *concatKDF) Read(out []byte) (int, error) {
55 | copied := copy(out, ctx.cache)
56 | ctx.cache = ctx.cache[copied:]
57 |
58 | for copied < len(out) {
59 | ctx.hasher.Reset()
60 |
61 | // Write on a hash.Hash never fails
62 | _ = binary.Write(ctx.hasher, binary.BigEndian, ctx.i)
63 | _, _ = ctx.hasher.Write(ctx.z)
64 | _, _ = ctx.hasher.Write(ctx.info)
65 |
66 | hash := ctx.hasher.Sum(nil)
67 | chunkCopied := copy(out[copied:], hash)
68 | copied += chunkCopied
69 | ctx.cache = hash[chunkCopied:]
70 |
71 | ctx.i++
72 | }
73 |
74 | return copied, nil
75 | }
76 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/cipher/ecdh_es.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package josecipher
18 |
19 | import (
20 | "bytes"
21 | "crypto"
22 | "crypto/ecdsa"
23 | "crypto/elliptic"
24 | "encoding/binary"
25 | )
26 |
27 | // DeriveECDHES derives a shared encryption key using ECDH/ConcatKDF as described in JWE/JWA.
28 | // It is an error to call this function with a private/public key that are not on the same
29 | // curve. Callers must ensure that the keys are valid before calling this function. Output
30 | // size may be at most 1<<16 bytes (64 KiB).
31 | func DeriveECDHES(alg string, apuData, apvData []byte, priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey, size int) []byte {
32 | if size > 1<<16 {
33 | panic("ECDH-ES output size too large, must be less than or equal to 1<<16")
34 | }
35 |
36 | // algId, partyUInfo, partyVInfo inputs must be prefixed with the length
37 | algID := lengthPrefixed([]byte(alg))
38 | ptyUInfo := lengthPrefixed(apuData)
39 | ptyVInfo := lengthPrefixed(apvData)
40 |
41 | // suppPubInfo is the encoded length of the output size in bits
42 | supPubInfo := make([]byte, 4)
43 | binary.BigEndian.PutUint32(supPubInfo, uint32(size)*8)
44 |
45 | if !priv.PublicKey.Curve.IsOnCurve(pub.X, pub.Y) {
46 | panic("public key not on same curve as private key")
47 | }
48 |
49 | z, _ := priv.Curve.ScalarMult(pub.X, pub.Y, priv.D.Bytes())
50 | zBytes := z.Bytes()
51 |
52 | // Note that calling z.Bytes() on a big.Int may strip leading zero bytes from
53 | // the returned byte array. This can lead to a problem where zBytes will be
54 | // shorter than expected which breaks the key derivation. Therefore we must pad
55 | // to the full length of the expected coordinate here before calling the KDF.
56 | octSize := dSize(priv.Curve)
57 | if len(zBytes) != octSize {
58 | zBytes = append(bytes.Repeat([]byte{0}, octSize-len(zBytes)), zBytes...)
59 | }
60 |
61 | reader := NewConcatKDF(crypto.SHA256, zBytes, algID, ptyUInfo, ptyVInfo, supPubInfo, []byte{})
62 | key := make([]byte, size)
63 |
64 | // Read on the KDF will never fail
65 | _, _ = reader.Read(key)
66 |
67 | return key
68 | }
69 |
70 | // dSize returns the size in octets for a coordinate on a elliptic curve.
71 | func dSize(curve elliptic.Curve) int {
72 | order := curve.Params().P
73 | bitLen := order.BitLen()
74 | size := bitLen / 8
75 | if bitLen%8 != 0 {
76 | size++
77 | }
78 | return size
79 | }
80 |
81 | func lengthPrefixed(data []byte) []byte {
82 | out := make([]byte, len(data)+4)
83 | binary.BigEndian.PutUint32(out, uint32(len(data)))
84 | copy(out[4:], data)
85 | return out
86 | }
87 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/cipher/key_wrap.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package josecipher
18 |
19 | import (
20 | "crypto/cipher"
21 | "crypto/subtle"
22 | "encoding/binary"
23 | "errors"
24 | )
25 |
26 | var defaultIV = []byte{0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6}
27 |
28 | // KeyWrap implements NIST key wrapping; it wraps a content encryption key (cek) with the given block cipher.
29 | func KeyWrap(block cipher.Block, cek []byte) ([]byte, error) {
30 | if len(cek)%8 != 0 {
31 | return nil, errors.New("go-jose/go-jose: key wrap input must be 8 byte blocks")
32 | }
33 |
34 | n := len(cek) / 8
35 | r := make([][]byte, n)
36 |
37 | for i := range r {
38 | r[i] = make([]byte, 8)
39 | copy(r[i], cek[i*8:])
40 | }
41 |
42 | buffer := make([]byte, 16)
43 | tBytes := make([]byte, 8)
44 | copy(buffer, defaultIV)
45 |
46 | for t := 0; t < 6*n; t++ {
47 | copy(buffer[8:], r[t%n])
48 |
49 | block.Encrypt(buffer, buffer)
50 |
51 | binary.BigEndian.PutUint64(tBytes, uint64(t+1))
52 |
53 | for i := 0; i < 8; i++ {
54 | buffer[i] ^= tBytes[i]
55 | }
56 | copy(r[t%n], buffer[8:])
57 | }
58 |
59 | out := make([]byte, (n+1)*8)
60 | copy(out, buffer[:8])
61 | for i := range r {
62 | copy(out[(i+1)*8:], r[i])
63 | }
64 |
65 | return out, nil
66 | }
67 |
68 | // KeyUnwrap implements NIST key unwrapping; it unwraps a content encryption key (cek) with the given block cipher.
69 | func KeyUnwrap(block cipher.Block, ciphertext []byte) ([]byte, error) {
70 | if len(ciphertext)%8 != 0 {
71 | return nil, errors.New("go-jose/go-jose: key wrap input must be 8 byte blocks")
72 | }
73 |
74 | n := (len(ciphertext) / 8) - 1
75 | r := make([][]byte, n)
76 |
77 | for i := range r {
78 | r[i] = make([]byte, 8)
79 | copy(r[i], ciphertext[(i+1)*8:])
80 | }
81 |
82 | buffer := make([]byte, 16)
83 | tBytes := make([]byte, 8)
84 | copy(buffer[:8], ciphertext[:8])
85 |
86 | for t := 6*n - 1; t >= 0; t-- {
87 | binary.BigEndian.PutUint64(tBytes, uint64(t+1))
88 |
89 | for i := 0; i < 8; i++ {
90 | buffer[i] ^= tBytes[i]
91 | }
92 | copy(buffer[8:], r[t%n])
93 |
94 | block.Decrypt(buffer, buffer)
95 |
96 | copy(r[t%n], buffer[8:])
97 | }
98 |
99 | if subtle.ConstantTimeCompare(buffer[:8], defaultIV) == 0 {
100 | return nil, errors.New("go-jose/go-jose: failed to unwrap key")
101 | }
102 |
103 | out := make([]byte, n*8)
104 | for i := range r {
105 | copy(out[i*8:], r[i])
106 | }
107 |
108 | return out, nil
109 | }
110 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/doc.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | /*
18 | Package jose aims to provide an implementation of the Javascript Object Signing
19 | and Encryption set of standards. It implements encryption and signing based on
20 | the JSON Web Encryption and JSON Web Signature standards, with optional JSON Web
21 | Token support available in a sub-package. The library supports both the compact
22 | and JWS/JWE JSON Serialization formats, and has optional support for multiple
23 | recipients.
24 | */
25 | package jose
26 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/encoding.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package jose
18 |
19 | import (
20 | "bytes"
21 | "compress/flate"
22 | "encoding/base64"
23 | "encoding/binary"
24 | "fmt"
25 | "io"
26 | "math/big"
27 | "strings"
28 | "unicode"
29 |
30 | "github.com/go-jose/go-jose/v3/json"
31 | )
32 |
33 | // Helper function to serialize known-good objects.
34 | // Precondition: value is not a nil pointer.
35 | func mustSerializeJSON(value interface{}) []byte {
36 | out, err := json.Marshal(value)
37 | if err != nil {
38 | panic(err)
39 | }
40 | // We never want to serialize the top-level value "null," since it's not a
41 | // valid JOSE message. But if a caller passes in a nil pointer to this method,
42 | // MarshalJSON will happily serialize it as the top-level value "null". If
43 | // that value is then embedded in another operation, for instance by being
44 | // base64-encoded and fed as input to a signing algorithm
45 | // (https://github.com/go-jose/go-jose/issues/22), the result will be
46 | // incorrect. Because this method is intended for known-good objects, and a nil
47 | // pointer is not a known-good object, we are free to panic in this case.
48 | // Note: It's not possible to directly check whether the data pointed at by an
49 | // interface is a nil pointer, so we do this hacky workaround.
50 | // https://groups.google.com/forum/#!topic/golang-nuts/wnH302gBa4I
51 | if string(out) == "null" {
52 | panic("Tried to serialize a nil pointer.")
53 | }
54 | return out
55 | }
56 |
57 | // Strip all newlines and whitespace
58 | func stripWhitespace(data string) string {
59 | buf := strings.Builder{}
60 | buf.Grow(len(data))
61 | for _, r := range data {
62 | if !unicode.IsSpace(r) {
63 | buf.WriteRune(r)
64 | }
65 | }
66 | return buf.String()
67 | }
68 |
69 | // Perform compression based on algorithm
70 | func compress(algorithm CompressionAlgorithm, input []byte) ([]byte, error) {
71 | switch algorithm {
72 | case DEFLATE:
73 | return deflate(input)
74 | default:
75 | return nil, ErrUnsupportedAlgorithm
76 | }
77 | }
78 |
79 | // Perform decompression based on algorithm
80 | func decompress(algorithm CompressionAlgorithm, input []byte) ([]byte, error) {
81 | switch algorithm {
82 | case DEFLATE:
83 | return inflate(input)
84 | default:
85 | return nil, ErrUnsupportedAlgorithm
86 | }
87 | }
88 |
89 | // deflate compresses the input.
90 | func deflate(input []byte) ([]byte, error) {
91 | output := new(bytes.Buffer)
92 |
93 | // Writing to byte buffer, err is always nil
94 | writer, _ := flate.NewWriter(output, 1)
95 | _, _ = io.Copy(writer, bytes.NewBuffer(input))
96 |
97 | err := writer.Close()
98 | return output.Bytes(), err
99 | }
100 |
101 | // inflate decompresses the input.
102 | //
103 | // Errors if the decompressed data would be >250kB or >10x the size of the
104 | // compressed data, whichever is larger.
105 | func inflate(input []byte) ([]byte, error) {
106 | output := new(bytes.Buffer)
107 | reader := flate.NewReader(bytes.NewBuffer(input))
108 |
109 | maxCompressedSize := 10 * int64(len(input))
110 | if maxCompressedSize < 250000 {
111 | maxCompressedSize = 250000
112 | }
113 |
114 | limit := maxCompressedSize + 1
115 | n, err := io.CopyN(output, reader, limit)
116 | if err != nil && err != io.EOF {
117 | return nil, err
118 | }
119 | if n == limit {
120 | return nil, fmt.Errorf("uncompressed data would be too large (>%d bytes)", maxCompressedSize)
121 | }
122 |
123 | err = reader.Close()
124 | return output.Bytes(), err
125 | }
126 |
127 | // byteBuffer represents a slice of bytes that can be serialized to url-safe base64.
128 | type byteBuffer struct {
129 | data []byte
130 | }
131 |
132 | func newBuffer(data []byte) *byteBuffer {
133 | if data == nil {
134 | return nil
135 | }
136 | return &byteBuffer{
137 | data: data,
138 | }
139 | }
140 |
141 | func newFixedSizeBuffer(data []byte, length int) *byteBuffer {
142 | if len(data) > length {
143 | panic("go-jose/go-jose: invalid call to newFixedSizeBuffer (len(data) > length)")
144 | }
145 | pad := make([]byte, length-len(data))
146 | return newBuffer(append(pad, data...))
147 | }
148 |
149 | func newBufferFromInt(num uint64) *byteBuffer {
150 | data := make([]byte, 8)
151 | binary.BigEndian.PutUint64(data, num)
152 | return newBuffer(bytes.TrimLeft(data, "\x00"))
153 | }
154 |
155 | func (b *byteBuffer) MarshalJSON() ([]byte, error) {
156 | return json.Marshal(b.base64())
157 | }
158 |
159 | func (b *byteBuffer) UnmarshalJSON(data []byte) error {
160 | var encoded string
161 | err := json.Unmarshal(data, &encoded)
162 | if err != nil {
163 | return err
164 | }
165 |
166 | if encoded == "" {
167 | return nil
168 | }
169 |
170 | decoded, err := base64URLDecode(encoded)
171 | if err != nil {
172 | return err
173 | }
174 |
175 | *b = *newBuffer(decoded)
176 |
177 | return nil
178 | }
179 |
180 | func (b *byteBuffer) base64() string {
181 | return base64.RawURLEncoding.EncodeToString(b.data)
182 | }
183 |
184 | func (b *byteBuffer) bytes() []byte {
185 | // Handling nil here allows us to transparently handle nil slices when serializing.
186 | if b == nil {
187 | return nil
188 | }
189 | return b.data
190 | }
191 |
192 | func (b byteBuffer) bigInt() *big.Int {
193 | return new(big.Int).SetBytes(b.data)
194 | }
195 |
196 | func (b byteBuffer) toInt() int {
197 | return int(b.bigInt().Int64())
198 | }
199 |
200 | // base64URLDecode is implemented as defined in https://www.rfc-editor.org/rfc/rfc7515.html#appendix-C
201 | func base64URLDecode(value string) ([]byte, error) {
202 | value = strings.TrimRight(value, "=")
203 | return base64.RawURLEncoding.DecodeString(value)
204 | }
205 |
206 | func base64EncodeLen(sl []byte) int {
207 | return base64.RawURLEncoding.EncodedLen(len(sl))
208 | }
209 |
210 | func base64JoinWithDots(inputs ...[]byte) string {
211 | if len(inputs) == 0 {
212 | return ""
213 | }
214 |
215 | // Count of dots.
216 | totalCount := len(inputs) - 1
217 |
218 | for _, input := range inputs {
219 | totalCount += base64EncodeLen(input)
220 | }
221 |
222 | out := make([]byte, totalCount)
223 | startEncode := 0
224 | for i, input := range inputs {
225 | base64.RawURLEncoding.Encode(out[startEncode:], input)
226 |
227 | if i == len(inputs)-1 {
228 | continue
229 | }
230 |
231 | startEncode += base64EncodeLen(input)
232 | out[startEncode] = '.'
233 | startEncode++
234 | }
235 |
236 | return string(out)
237 | }
238 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/json/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2012 The Go Authors. All rights reserved.
2 |
3 | Redistribution and use in source and binary forms, with or without
4 | modification, are permitted provided that the following conditions are
5 | met:
6 |
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 | * Redistributions in binary form must reproduce the above
10 | copyright notice, this list of conditions and the following disclaimer
11 | in the documentation and/or other materials provided with the
12 | distribution.
13 | * Neither the name of Google Inc. nor the names of its
14 | contributors may be used to endorse or promote products derived from
15 | this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/json/README.md:
--------------------------------------------------------------------------------
1 | # Safe JSON
2 |
3 | This repository contains a fork of the `encoding/json` package from Go 1.6.
4 |
5 | The following changes were made:
6 |
7 | * Object deserialization uses case-sensitive member name matching instead of
8 | [case-insensitive matching](https://www.ietf.org/mail-archive/web/json/current/msg03763.html).
9 | This is to avoid differences in the interpretation of JOSE messages between
10 | go-jose and libraries written in other languages.
11 | * When deserializing a JSON object, we check for duplicate keys and reject the
12 | input whenever we detect a duplicate. Rather than trying to work with malformed
13 | data, we prefer to reject it right away.
14 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/json/indent.go:
--------------------------------------------------------------------------------
1 | // Copyright 2010 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package json
6 |
7 | import "bytes"
8 |
9 | // Compact appends to dst the JSON-encoded src with
10 | // insignificant space characters elided.
11 | func Compact(dst *bytes.Buffer, src []byte) error {
12 | return compact(dst, src, false)
13 | }
14 |
15 | func compact(dst *bytes.Buffer, src []byte, escape bool) error {
16 | origLen := dst.Len()
17 | var scan scanner
18 | scan.reset()
19 | start := 0
20 | for i, c := range src {
21 | if escape && (c == '<' || c == '>' || c == '&') {
22 | if start < i {
23 | dst.Write(src[start:i])
24 | }
25 | dst.WriteString(`\u00`)
26 | dst.WriteByte(hex[c>>4])
27 | dst.WriteByte(hex[c&0xF])
28 | start = i + 1
29 | }
30 | // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
31 | if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
32 | if start < i {
33 | dst.Write(src[start:i])
34 | }
35 | dst.WriteString(`\u202`)
36 | dst.WriteByte(hex[src[i+2]&0xF])
37 | start = i + 3
38 | }
39 | v := scan.step(&scan, c)
40 | if v >= scanSkipSpace {
41 | if v == scanError {
42 | break
43 | }
44 | if start < i {
45 | dst.Write(src[start:i])
46 | }
47 | start = i + 1
48 | }
49 | }
50 | if scan.eof() == scanError {
51 | dst.Truncate(origLen)
52 | return scan.err
53 | }
54 | if start < len(src) {
55 | dst.Write(src[start:])
56 | }
57 | return nil
58 | }
59 |
60 | func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
61 | dst.WriteByte('\n')
62 | dst.WriteString(prefix)
63 | for i := 0; i < depth; i++ {
64 | dst.WriteString(indent)
65 | }
66 | }
67 |
68 | // Indent appends to dst an indented form of the JSON-encoded src.
69 | // Each element in a JSON object or array begins on a new,
70 | // indented line beginning with prefix followed by one or more
71 | // copies of indent according to the indentation nesting.
72 | // The data appended to dst does not begin with the prefix nor
73 | // any indentation, to make it easier to embed inside other formatted JSON data.
74 | // Although leading space characters (space, tab, carriage return, newline)
75 | // at the beginning of src are dropped, trailing space characters
76 | // at the end of src are preserved and copied to dst.
77 | // For example, if src has no trailing spaces, neither will dst;
78 | // if src ends in a trailing newline, so will dst.
79 | func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
80 | origLen := dst.Len()
81 | var scan scanner
82 | scan.reset()
83 | needIndent := false
84 | depth := 0
85 | for _, c := range src {
86 | scan.bytes++
87 | v := scan.step(&scan, c)
88 | if v == scanSkipSpace {
89 | continue
90 | }
91 | if v == scanError {
92 | break
93 | }
94 | if needIndent && v != scanEndObject && v != scanEndArray {
95 | needIndent = false
96 | depth++
97 | newline(dst, prefix, indent, depth)
98 | }
99 |
100 | // Emit semantically uninteresting bytes
101 | // (in particular, punctuation in strings) unmodified.
102 | if v == scanContinue {
103 | dst.WriteByte(c)
104 | continue
105 | }
106 |
107 | // Add spacing around real punctuation.
108 | switch c {
109 | case '{', '[':
110 | // delay indent so that empty object and array are formatted as {} and [].
111 | needIndent = true
112 | dst.WriteByte(c)
113 |
114 | case ',':
115 | dst.WriteByte(c)
116 | newline(dst, prefix, indent, depth)
117 |
118 | case ':':
119 | dst.WriteByte(c)
120 | dst.WriteByte(' ')
121 |
122 | case '}', ']':
123 | if needIndent {
124 | // suppress indent in empty object/array
125 | needIndent = false
126 | } else {
127 | depth--
128 | newline(dst, prefix, indent, depth)
129 | }
130 | dst.WriteByte(c)
131 |
132 | default:
133 | dst.WriteByte(c)
134 | }
135 | }
136 | if scan.eof() == scanError {
137 | dst.Truncate(origLen)
138 | return scan.err
139 | }
140 | return nil
141 | }
142 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/json/tags.go:
--------------------------------------------------------------------------------
1 | // Copyright 2011 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | package json
6 |
7 | import (
8 | "strings"
9 | )
10 |
11 | // tagOptions is the string following a comma in a struct field's "json"
12 | // tag, or the empty string. It does not include the leading comma.
13 | type tagOptions string
14 |
15 | // parseTag splits a struct field's json tag into its name and
16 | // comma-separated options.
17 | func parseTag(tag string) (string, tagOptions) {
18 | if idx := strings.Index(tag, ","); idx != -1 {
19 | return tag[:idx], tagOptions(tag[idx+1:])
20 | }
21 | return tag, tagOptions("")
22 | }
23 |
24 | // Contains reports whether a comma-separated list of options
25 | // contains a particular substr flag. substr must be surrounded by a
26 | // string boundary or commas.
27 | func (o tagOptions) Contains(optionName string) bool {
28 | if len(o) == 0 {
29 | return false
30 | }
31 | s := string(o)
32 | for s != "" {
33 | var next string
34 | i := strings.Index(s, ",")
35 | if i >= 0 {
36 | s, next = s[:i], s[i+1:]
37 | }
38 | if s == optionName {
39 | return true
40 | }
41 | s = next
42 | }
43 | return false
44 | }
45 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/jwe.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2014 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package jose
18 |
19 | import (
20 | "encoding/base64"
21 | "fmt"
22 | "strings"
23 |
24 | "github.com/go-jose/go-jose/v3/json"
25 | )
26 |
27 | // rawJSONWebEncryption represents a raw JWE JSON object. Used for parsing/serializing.
28 | type rawJSONWebEncryption struct {
29 | Protected *byteBuffer `json:"protected,omitempty"`
30 | Unprotected *rawHeader `json:"unprotected,omitempty"`
31 | Header *rawHeader `json:"header,omitempty"`
32 | Recipients []rawRecipientInfo `json:"recipients,omitempty"`
33 | Aad *byteBuffer `json:"aad,omitempty"`
34 | EncryptedKey *byteBuffer `json:"encrypted_key,omitempty"`
35 | Iv *byteBuffer `json:"iv,omitempty"`
36 | Ciphertext *byteBuffer `json:"ciphertext,omitempty"`
37 | Tag *byteBuffer `json:"tag,omitempty"`
38 | }
39 |
40 | // rawRecipientInfo represents a raw JWE Per-Recipient header JSON object. Used for parsing/serializing.
41 | type rawRecipientInfo struct {
42 | Header *rawHeader `json:"header,omitempty"`
43 | EncryptedKey string `json:"encrypted_key,omitempty"`
44 | }
45 |
46 | // JSONWebEncryption represents an encrypted JWE object after parsing.
47 | type JSONWebEncryption struct {
48 | Header Header
49 | protected, unprotected *rawHeader
50 | recipients []recipientInfo
51 | aad, iv, ciphertext, tag []byte
52 | original *rawJSONWebEncryption
53 | }
54 |
55 | // recipientInfo represents a raw JWE Per-Recipient header JSON object after parsing.
56 | type recipientInfo struct {
57 | header *rawHeader
58 | encryptedKey []byte
59 | }
60 |
61 | // GetAuthData retrieves the (optional) authenticated data attached to the object.
62 | func (obj JSONWebEncryption) GetAuthData() []byte {
63 | if obj.aad != nil {
64 | out := make([]byte, len(obj.aad))
65 | copy(out, obj.aad)
66 | return out
67 | }
68 |
69 | return nil
70 | }
71 |
72 | // Get the merged header values
73 | func (obj JSONWebEncryption) mergedHeaders(recipient *recipientInfo) rawHeader {
74 | out := rawHeader{}
75 | out.merge(obj.protected)
76 | out.merge(obj.unprotected)
77 |
78 | if recipient != nil {
79 | out.merge(recipient.header)
80 | }
81 |
82 | return out
83 | }
84 |
85 | // Get the additional authenticated data from a JWE object.
86 | func (obj JSONWebEncryption) computeAuthData() []byte {
87 | var protected string
88 |
89 | switch {
90 | case obj.original != nil && obj.original.Protected != nil:
91 | protected = obj.original.Protected.base64()
92 | case obj.protected != nil:
93 | protected = base64.RawURLEncoding.EncodeToString(mustSerializeJSON((obj.protected)))
94 | default:
95 | protected = ""
96 | }
97 |
98 | output := []byte(protected)
99 | if obj.aad != nil {
100 | output = append(output, '.')
101 | output = append(output, []byte(base64.RawURLEncoding.EncodeToString(obj.aad))...)
102 | }
103 |
104 | return output
105 | }
106 |
107 | // ParseEncrypted parses an encrypted message in compact or JWE JSON Serialization format.
108 | func ParseEncrypted(input string) (*JSONWebEncryption, error) {
109 | input = stripWhitespace(input)
110 | if strings.HasPrefix(input, "{") {
111 | return parseEncryptedFull(input)
112 | }
113 |
114 | return parseEncryptedCompact(input)
115 | }
116 |
117 | // parseEncryptedFull parses a message in compact format.
118 | func parseEncryptedFull(input string) (*JSONWebEncryption, error) {
119 | var parsed rawJSONWebEncryption
120 | err := json.Unmarshal([]byte(input), &parsed)
121 | if err != nil {
122 | return nil, err
123 | }
124 |
125 | return parsed.sanitized()
126 | }
127 |
128 | // sanitized produces a cleaned-up JWE object from the raw JSON.
129 | func (parsed *rawJSONWebEncryption) sanitized() (*JSONWebEncryption, error) {
130 | obj := &JSONWebEncryption{
131 | original: parsed,
132 | unprotected: parsed.Unprotected,
133 | }
134 |
135 | // Check that there is not a nonce in the unprotected headers
136 | if parsed.Unprotected != nil {
137 | if nonce := parsed.Unprotected.getNonce(); nonce != "" {
138 | return nil, ErrUnprotectedNonce
139 | }
140 | }
141 | if parsed.Header != nil {
142 | if nonce := parsed.Header.getNonce(); nonce != "" {
143 | return nil, ErrUnprotectedNonce
144 | }
145 | }
146 |
147 | if parsed.Protected != nil && len(parsed.Protected.bytes()) > 0 {
148 | err := json.Unmarshal(parsed.Protected.bytes(), &obj.protected)
149 | if err != nil {
150 | return nil, fmt.Errorf("go-jose/go-jose: invalid protected header: %s, %s", err, parsed.Protected.base64())
151 | }
152 | }
153 |
154 | // Note: this must be called _after_ we parse the protected header,
155 | // otherwise fields from the protected header will not get picked up.
156 | var err error
157 | mergedHeaders := obj.mergedHeaders(nil)
158 | obj.Header, err = mergedHeaders.sanitized()
159 | if err != nil {
160 | return nil, fmt.Errorf("go-jose/go-jose: cannot sanitize merged headers: %v (%v)", err, mergedHeaders)
161 | }
162 |
163 | if len(parsed.Recipients) == 0 {
164 | obj.recipients = []recipientInfo{
165 | {
166 | header: parsed.Header,
167 | encryptedKey: parsed.EncryptedKey.bytes(),
168 | },
169 | }
170 | } else {
171 | obj.recipients = make([]recipientInfo, len(parsed.Recipients))
172 | for r := range parsed.Recipients {
173 | encryptedKey, err := base64URLDecode(parsed.Recipients[r].EncryptedKey)
174 | if err != nil {
175 | return nil, err
176 | }
177 |
178 | // Check that there is not a nonce in the unprotected header
179 | if parsed.Recipients[r].Header != nil && parsed.Recipients[r].Header.getNonce() != "" {
180 | return nil, ErrUnprotectedNonce
181 | }
182 |
183 | obj.recipients[r].header = parsed.Recipients[r].Header
184 | obj.recipients[r].encryptedKey = encryptedKey
185 | }
186 | }
187 |
188 | for _, recipient := range obj.recipients {
189 | headers := obj.mergedHeaders(&recipient)
190 | if headers.getAlgorithm() == "" || headers.getEncryption() == "" {
191 | return nil, fmt.Errorf("go-jose/go-jose: message is missing alg/enc headers")
192 | }
193 | }
194 |
195 | obj.iv = parsed.Iv.bytes()
196 | obj.ciphertext = parsed.Ciphertext.bytes()
197 | obj.tag = parsed.Tag.bytes()
198 | obj.aad = parsed.Aad.bytes()
199 |
200 | return obj, nil
201 | }
202 |
203 | // parseEncryptedCompact parses a message in compact format.
204 | func parseEncryptedCompact(input string) (*JSONWebEncryption, error) {
205 | // Five parts is four separators
206 | if strings.Count(input, ".") != 4 {
207 | return nil, fmt.Errorf("go-jose/go-jose: compact JWE format must have five parts")
208 | }
209 | parts := strings.SplitN(input, ".", 5)
210 |
211 | rawProtected, err := base64URLDecode(parts[0])
212 | if err != nil {
213 | return nil, err
214 | }
215 |
216 | encryptedKey, err := base64URLDecode(parts[1])
217 | if err != nil {
218 | return nil, err
219 | }
220 |
221 | iv, err := base64URLDecode(parts[2])
222 | if err != nil {
223 | return nil, err
224 | }
225 |
226 | ciphertext, err := base64URLDecode(parts[3])
227 | if err != nil {
228 | return nil, err
229 | }
230 |
231 | tag, err := base64URLDecode(parts[4])
232 | if err != nil {
233 | return nil, err
234 | }
235 |
236 | raw := &rawJSONWebEncryption{
237 | Protected: newBuffer(rawProtected),
238 | EncryptedKey: newBuffer(encryptedKey),
239 | Iv: newBuffer(iv),
240 | Ciphertext: newBuffer(ciphertext),
241 | Tag: newBuffer(tag),
242 | }
243 |
244 | return raw.sanitized()
245 | }
246 |
247 | // CompactSerialize serializes an object using the compact serialization format.
248 | func (obj JSONWebEncryption) CompactSerialize() (string, error) {
249 | if len(obj.recipients) != 1 || obj.unprotected != nil ||
250 | obj.protected == nil || obj.recipients[0].header != nil {
251 | return "", ErrNotSupported
252 | }
253 |
254 | serializedProtected := mustSerializeJSON(obj.protected)
255 |
256 | return base64JoinWithDots(
257 | serializedProtected,
258 | obj.recipients[0].encryptedKey,
259 | obj.iv,
260 | obj.ciphertext,
261 | obj.tag,
262 | ), nil
263 | }
264 |
265 | // FullSerialize serializes an object using the full JSON serialization format.
266 | func (obj JSONWebEncryption) FullSerialize() string {
267 | raw := rawJSONWebEncryption{
268 | Unprotected: obj.unprotected,
269 | Iv: newBuffer(obj.iv),
270 | Ciphertext: newBuffer(obj.ciphertext),
271 | EncryptedKey: newBuffer(obj.recipients[0].encryptedKey),
272 | Tag: newBuffer(obj.tag),
273 | Aad: newBuffer(obj.aad),
274 | Recipients: []rawRecipientInfo{},
275 | }
276 |
277 | if len(obj.recipients) > 1 {
278 | for _, recipient := range obj.recipients {
279 | info := rawRecipientInfo{
280 | Header: recipient.header,
281 | EncryptedKey: base64.RawURLEncoding.EncodeToString(recipient.encryptedKey),
282 | }
283 | raw.Recipients = append(raw.Recipients, info)
284 | }
285 | } else {
286 | // Use flattened serialization
287 | raw.Header = obj.recipients[0].header
288 | raw.EncryptedKey = newBuffer(obj.recipients[0].encryptedKey)
289 | }
290 |
291 | if obj.protected != nil {
292 | raw.Protected = newBuffer(mustSerializeJSON(obj.protected))
293 | }
294 |
295 | return string(mustSerializeJSON(raw))
296 | }
297 |
--------------------------------------------------------------------------------
/vendor/github.com/go-jose/go-jose/v3/opaque.go:
--------------------------------------------------------------------------------
1 | /*-
2 | * Copyright 2018 Square Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package jose
18 |
19 | // OpaqueSigner is an interface that supports signing payloads with opaque
20 | // private key(s). Private key operations performed by implementers may, for
21 | // example, occur in a hardware module. An OpaqueSigner may rotate signing keys
22 | // transparently to the user of this interface.
23 | type OpaqueSigner interface {
24 | // Public returns the public key of the current signing key.
25 | Public() *JSONWebKey
26 | // Algs returns a list of supported signing algorithms.
27 | Algs() []SignatureAlgorithm
28 | // SignPayload signs a payload with the current signing key using the given
29 | // algorithm.
30 | SignPayload(payload []byte, alg SignatureAlgorithm) ([]byte, error)
31 | }
32 |
33 | type opaqueSigner struct {
34 | signer OpaqueSigner
35 | }
36 |
37 | func newOpaqueSigner(alg SignatureAlgorithm, signer OpaqueSigner) (recipientSigInfo, error) {
38 | var algSupported bool
39 | for _, salg := range signer.Algs() {
40 | if alg == salg {
41 | algSupported = true
42 | break
43 | }
44 | }
45 | if !algSupported {
46 | return recipientSigInfo{}, ErrUnsupportedAlgorithm
47 | }
48 |
49 | return recipientSigInfo{
50 | sigAlg: alg,
51 | publicKey: signer.Public,
52 | signer: &opaqueSigner{
53 | signer: signer,
54 | },
55 | }, nil
56 | }
57 |
58 | func (o *opaqueSigner) signPayload(payload []byte, alg SignatureAlgorithm) (Signature, error) {
59 | out, err := o.signer.SignPayload(payload, alg)
60 | if err != nil {
61 | return Signature{}, err
62 | }
63 |
64 | return Signature{
65 | Signature: out,
66 | protected: &rawHeader{},
67 | }, nil
68 | }
69 |
70 | // OpaqueVerifier is an interface that supports verifying payloads with opaque
71 | // public key(s). An OpaqueSigner may rotate signing keys transparently to the
72 | // user of this interface.
73 | type OpaqueVerifier interface {
74 | VerifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error
75 | }
76 |
77 | type opaqueVerifier struct {
78 | verifier OpaqueVerifier
79 | }
80 |
81 | func (o *opaqueVerifier) verifyPayload(payload []byte, signature []byte, alg SignatureAlgorithm) error {
82 | return o.verifier.VerifyPayload(payload, signature, alg)
83 | }
84 |
85 | // OpaqueKeyEncrypter is an interface that supports encrypting keys with an opaque key.
86 | type OpaqueKeyEncrypter interface {
87 | // KeyID returns the kid
88 | KeyID() string
89 | // Algs returns a list of supported key encryption algorithms.
90 | Algs() []KeyAlgorithm
91 | // encryptKey encrypts the CEK using the given algorithm.
92 | encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error)
93 | }
94 |
95 | type opaqueKeyEncrypter struct {
96 | encrypter OpaqueKeyEncrypter
97 | }
98 |
99 | func newOpaqueKeyEncrypter(alg KeyAlgorithm, encrypter OpaqueKeyEncrypter) (recipientKeyInfo, error) {
100 | var algSupported bool
101 | for _, salg := range encrypter.Algs() {
102 | if alg == salg {
103 | algSupported = true
104 | break
105 | }
106 | }
107 | if !algSupported {
108 | return recipientKeyInfo{}, ErrUnsupportedAlgorithm
109 | }
110 |
111 | return recipientKeyInfo{
112 | keyID: encrypter.KeyID(),
113 | keyAlg: alg,
114 | keyEncrypter: &opaqueKeyEncrypter{
115 | encrypter: encrypter,
116 | },
117 | }, nil
118 | }
119 |
120 | func (oke *opaqueKeyEncrypter) encryptKey(cek []byte, alg KeyAlgorithm) (recipientInfo, error) {
121 | return oke.encrypter.encryptKey(cek, alg)
122 | }
123 |
124 | // OpaqueKeyDecrypter is an interface that supports decrypting keys with an opaque key.
125 | type OpaqueKeyDecrypter interface {
126 | DecryptKey(encryptedKey []byte, header Header) ([]byte, error)
127 | }
128 |
129 | type opaqueKeyDecrypter struct {
130 | decrypter OpaqueKeyDecrypter
131 | }
132 |
133 | func (okd *opaqueKeyDecrypter) decryptKey(headers rawHeader, recipient *recipientInfo, generator keyGenerator) ([]byte, error) {
134 | mergedHeaders := rawHeader{}
135 | mergedHeaders.merge(&headers)
136 | mergedHeaders.merge(recipient.header)
137 |
138 | header, err := mergedHeaders.sanitized()
139 | if err != nil {
140 | return nil, err
141 | }
142 |
143 | return okd.decrypter.DecryptKey(recipient.encryptedKey, header)
144 | }
145 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | bin
3 | .idea/
4 |
5 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2012 Dave Grijalva
2 | Copyright (c) 2021 golang-jwt maintainers
3 |
4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5 |
6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7 |
8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9 |
10 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md:
--------------------------------------------------------------------------------
1 | # Migration Guide (v5.0.0)
2 |
3 | Version `v5` contains a major rework of core functionalities in the `jwt-go`
4 | library. This includes support for several validation options as well as a
5 | re-design of the `Claims` interface. Lastly, we reworked how errors work under
6 | the hood, which should provide a better overall developer experience.
7 |
8 | Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0),
9 | the import path will be:
10 |
11 | "github.com/golang-jwt/jwt/v5"
12 |
13 | For most users, changing the import path *should* suffice. However, since we
14 | intentionally changed and cleaned some of the public API, existing programs
15 | might need to be updated. The following sections describe significant changes
16 | and corresponding updates for existing programs.
17 |
18 | ## Parsing and Validation Options
19 |
20 | Under the hood, a new `Validator` struct takes care of validating the claims. A
21 | long awaited feature has been the option to fine-tune the validation of tokens.
22 | This is now possible with several `ParserOption` functions that can be appended
23 | to most `Parse` functions, such as `ParseWithClaims`. The most important options
24 | and changes are:
25 | * Added `WithLeeway` to support specifying the leeway that is allowed when
26 | validating time-based claims, such as `exp` or `nbf`.
27 | * Changed default behavior to not check the `iat` claim. Usage of this claim
28 | is OPTIONAL according to the JWT RFC. The claim itself is also purely
29 | informational according to the RFC, so a strict validation failure is not
30 | recommended. If you want to check for sensible values in these claims,
31 | please use the `WithIssuedAt` parser option.
32 | * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for
33 | expected `aud`, `sub` and `iss`.
34 | * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow
35 | previously global settings to enable base64 strict encoding and the parsing
36 | of base64 strings with padding. The latter is strictly speaking against the
37 | standard, but unfortunately some of the major identity providers issue some
38 | of these incorrect tokens. Both options are disabled by default.
39 |
40 | ## Changes to the `Claims` interface
41 |
42 | ### Complete Restructuring
43 |
44 | Previously, the claims interface was satisfied with an implementation of a
45 | `Valid() error` function. This had several issues:
46 | * The different claim types (struct claims, map claims, etc.) then contained
47 | similar (but not 100 % identical) code of how this validation was done. This
48 | lead to a lot of (almost) duplicate code and was hard to maintain
49 | * It was not really semantically close to what a "claim" (or a set of claims)
50 | really is; which is a list of defined key/value pairs with a certain
51 | semantic meaning.
52 |
53 | Since all the validation functionality is now extracted into the validator, all
54 | `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface.
55 | Instead, the interface now represents a list of getters to retrieve values with
56 | a specific meaning. This allows us to completely decouple the validation logic
57 | with the underlying storage representation of the claim, which could be a
58 | struct, a map or even something stored in a database.
59 |
60 | ```go
61 | type Claims interface {
62 | GetExpirationTime() (*NumericDate, error)
63 | GetIssuedAt() (*NumericDate, error)
64 | GetNotBefore() (*NumericDate, error)
65 | GetIssuer() (string, error)
66 | GetSubject() (string, error)
67 | GetAudience() (ClaimStrings, error)
68 | }
69 | ```
70 |
71 | Users that previously directly called the `Valid` function on their claims,
72 | e.g., to perform validation independently of parsing/verifying a token, can now
73 | use the `jwt.NewValidator` function to create a `Validator` independently of the
74 | `Parser`.
75 |
76 | ```go
77 | var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second))
78 | v.Validate(myClaims)
79 | ```
80 |
81 | ### Supported Claim Types and Removal of `StandardClaims`
82 |
83 | The two standard claim types supported by this library, `MapClaims` and
84 | `RegisteredClaims` both implement the necessary functions of this interface. The
85 | old `StandardClaims` struct, which has already been deprecated in `v4` is now
86 | removed.
87 |
88 | Users using custom claims, in most cases, will not experience any changes in the
89 | behavior as long as they embedded `RegisteredClaims`. If they created a new
90 | claim type from scratch, they now need to implemented the proper getter
91 | functions.
92 |
93 | ### Migrating Application Specific Logic of the old `Valid`
94 |
95 | Previously, users could override the `Valid` method in a custom claim, for
96 | example to extend the validation with application-specific claims. However, this
97 | was always very dangerous, since once could easily disable the standard
98 | validation and signature checking.
99 |
100 | In order to avoid that, while still supporting the use-case, a new
101 | `ClaimsValidator` interface has been introduced. This interface consists of the
102 | `Validate() error` function. If the validator sees, that a `Claims` struct
103 | implements this interface, the errors returned to the `Validate` function will
104 | be *appended* to the regular standard validation. It is not possible to disable
105 | the standard validation anymore (even only by accident).
106 |
107 | Usage examples can be found in [example_test.go](./example_test.go), to build
108 | claims structs like the following.
109 |
110 | ```go
111 | // MyCustomClaims includes all registered claims, plus Foo.
112 | type MyCustomClaims struct {
113 | Foo string `json:"foo"`
114 | jwt.RegisteredClaims
115 | }
116 |
117 | // Validate can be used to execute additional application-specific claims
118 | // validation.
119 | func (m MyCustomClaims) Validate() error {
120 | if m.Foo != "bar" {
121 | return errors.New("must be foobar")
122 | }
123 |
124 | return nil
125 | }
126 | ```
127 |
128 | ## Changes to the `Token` and `Parser` struct
129 |
130 | The previously global functions `DecodeSegment` and `EncodeSegment` were moved
131 | to the `Parser` and `Token` struct respectively. This will allow us in the
132 | future to configure the behavior of these two based on options supplied on the
133 | parser or the token (creation). This also removes two previously global
134 | variables and moves them to parser options `WithStrictDecoding` and
135 | `WithPaddingAllowed`.
136 |
137 | In order to do that, we had to adjust the way signing methods work. Previously
138 | they were given a base64 encoded signature in `Verify` and were expected to
139 | return a base64 encoded version of the signature in `Sign`, both as a `string`.
140 | However, this made it necessary to have `DecodeSegment` and `EncodeSegment`
141 | global and was a less than perfect design because we were repeating
142 | encoding/decoding steps for all signing methods. Now, `Sign` and `Verify`
143 | operate on a decoded signature as a `[]byte`, which feels more natural for a
144 | cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of
145 | the final encoding/decoding part.
146 |
147 | In addition to that, we also changed the `Signature` field on `Token` from a
148 | `string` to `[]byte` and this is also now populated with the decoded form. This
149 | is also more consistent, because the other parts of the JWT, mainly `Header` and
150 | `Claims` were already stored in decoded form in `Token`. Only the signature was
151 | stored in base64 encoded form, which was redundant with the information in the
152 | `Raw` field, which contains the complete token as base64.
153 |
154 | ```go
155 | type Token struct {
156 | Raw string // Raw contains the raw token
157 | Method SigningMethod // Method is the signing method used or to be used
158 | Header map[string]interface{} // Header is the first segment of the token in decoded form
159 | Claims Claims // Claims is the second segment of the token in decoded form
160 | Signature []byte // Signature is the third segment of the token in decoded form
161 | Valid bool // Valid specifies if the token is valid
162 | }
163 | ```
164 |
165 | Most (if not all) of these changes should not impact the normal usage of this
166 | library. Only users directly accessing the `Signature` field as well as
167 | developers of custom signing methods should be affected.
168 |
169 | # Migration Guide (v4.0.0)
170 |
171 | Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0),
172 | the import path will be:
173 |
174 | "github.com/golang-jwt/jwt/v4"
175 |
176 | The `/v4` version will be backwards compatible with existing `v3.x.y` tags in
177 | this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should
178 | be a drop-in replacement, if you're having troubles migrating, please open an
179 | issue.
180 |
181 | You can replace all occurrences of `github.com/dgrijalva/jwt-go` or
182 | `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually
183 | or by using tools such as `sed` or `gofmt`.
184 |
185 | And then you'd typically run:
186 |
187 | ```
188 | go get github.com/golang-jwt/jwt/v4
189 | go mod tidy
190 | ```
191 |
192 | # Older releases (before v3.2.0)
193 |
194 | The original migration guide for older releases can be found at
195 | https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md.
196 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/README.md:
--------------------------------------------------------------------------------
1 | # jwt-go
2 |
3 | [](https://github.com/golang-jwt/jwt/actions/workflows/build.yml)
4 | [](https://pkg.go.dev/github.com/golang-jwt/jwt/v5)
6 | [](https://coveralls.io/github/golang-jwt/jwt?branch=main)
7 |
8 | A [go](http://www.golang.org) (or 'golang' for search engine friendliness)
9 | implementation of [JSON Web
10 | Tokens](https://datatracker.ietf.org/doc/html/rfc7519).
11 |
12 | Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0)
13 | this project adds Go module support, but maintains backward compatibility with
14 | older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the
15 | [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version
16 | v5.0.0 introduces major improvements to the validation of tokens, but is not
17 | entirely backward compatible.
18 |
19 | > After the original author of the library suggested migrating the maintenance
20 | > of `jwt-go`, a dedicated team of open source maintainers decided to clone the
21 | > existing library into this repository. See
22 | > [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a
23 | > detailed discussion on this topic.
24 |
25 |
26 | **SECURITY NOTICE:** Some older versions of Go have a security issue in the
27 | crypto/elliptic. The recommendation is to upgrade to at least 1.15 See issue
28 | [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more
29 | detail.
30 |
31 | **SECURITY NOTICE:** It's important that you [validate the `alg` presented is
32 | what you
33 | expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/).
34 | This library attempts to make it easy to do the right thing by requiring key
35 | types to match the expected alg, but you should take the extra step to verify it in
36 | your usage. See the examples provided.
37 |
38 | ### Supported Go versions
39 |
40 | Our support of Go versions is aligned with Go's [version release
41 | policy](https://golang.org/doc/devel/release#policy). So we will support a major
42 | version of Go until there are two newer major releases. We no longer support
43 | building jwt-go with unsupported Go versions, as these contain security
44 | vulnerabilities that will not be fixed.
45 |
46 | ## What the heck is a JWT?
47 |
48 | JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web
49 | Tokens.
50 |
51 | In short, it's a signed JSON object that does something useful (for example,
52 | authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is
53 | made of three parts, separated by `.`'s. The first two parts are JSON objects,
54 | that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648)
55 | encoded. The last part is the signature, encoded the same way.
56 |
57 | The first part is called the header. It contains the necessary information for
58 | verifying the last part, the signature. For example, which encryption method
59 | was used for signing and what key was used.
60 |
61 | The part in the middle is the interesting bit. It's called the Claims and
62 | contains the actual stuff you care about. Refer to [RFC
63 | 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about
64 | reserved keys and the proper way to add your own.
65 |
66 | ## What's in the box?
67 |
68 | This library supports the parsing and verification as well as the generation and
69 | signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA,
70 | RSA-PSS, and ECDSA, though hooks are present for adding your own.
71 |
72 | ## Installation Guidelines
73 |
74 | 1. To install the jwt package, you first need to have
75 | [Go](https://go.dev/doc/install) installed, then you can use the command
76 | below to add `jwt-go` as a dependency in your Go program.
77 |
78 | ```sh
79 | go get -u github.com/golang-jwt/jwt/v5
80 | ```
81 |
82 | 2. Import it in your code:
83 |
84 | ```go
85 | import "github.com/golang-jwt/jwt/v5"
86 | ```
87 |
88 | ## Usage
89 |
90 | A detailed usage guide, including how to sign and verify tokens can be found on
91 | our [documentation website](https://golang-jwt.github.io/jwt/usage/create/).
92 |
93 | ## Examples
94 |
95 | See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5)
96 | for examples of usage:
97 |
98 | * [Simple example of parsing and validating a
99 | token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac)
100 | * [Simple example of building and signing a
101 | token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac)
102 | * [Directory of
103 | Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples)
104 |
105 | ## Compliance
106 |
107 | This library was last reviewed to comply with [RFC
108 | 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few
109 | notable differences:
110 |
111 | * In order to protect against accidental use of [Unsecured
112 | JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using
113 | `alg=none` will only be accepted if the constant
114 | `jwt.UnsafeAllowNoneSignatureType` is provided as the key.
115 |
116 | ## Project Status & Versioning
117 |
118 | This library is considered production ready. Feedback and feature requests are
119 | appreciated. The API should be considered stable. There should be very few
120 | backward-incompatible changes outside of major version updates (and only with
121 | good reason).
122 |
123 | This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull
124 | requests will land on `main`. Periodically, versions will be tagged from
125 | `main`. You can find all the releases on [the project releases
126 | page](https://github.com/golang-jwt/jwt/releases).
127 |
128 | **BREAKING CHANGES:** A full list of breaking changes is available in
129 | `VERSION_HISTORY.md`. See [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information on updating
130 | your code.
131 |
132 | ## Extensions
133 |
134 | This library publishes all the necessary components for adding your own signing
135 | methods or key functions. Simply implement the `SigningMethod` interface and
136 | register a factory method using `RegisterSigningMethod` or provide a
137 | `jwt.Keyfunc`.
138 |
139 | A common use case would be integrating with different 3rd party signature
140 | providers, like key management services from various cloud providers or Hardware
141 | Security Modules (HSMs) or to implement additional standards.
142 |
143 | | Extension | Purpose | Repo |
144 | | --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
145 | | GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go |
146 | | AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms |
147 | | JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc |
148 |
149 | *Disclaimer*: Unless otherwise specified, these integrations are maintained by
150 | third parties and should not be considered as a primary offer by any of the
151 | mentioned cloud providers
152 |
153 | ## More
154 |
155 | Go package documentation can be found [on
156 | pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional
157 | documentation can be found on [our project
158 | page](https://golang-jwt.github.io/jwt/).
159 |
160 | The command line utility included in this project (cmd/jwt) provides a
161 | straightforward example of token creation and parsing as well as a useful tool
162 | for debugging your own integration. You'll also find several implementation
163 | examples in the documentation.
164 |
165 | [golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version
166 | of the JWT logo, which is distributed under the terms of the [MIT
167 | License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt).
168 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | As of November 2024 (and until this document is updated), the latest version `v5` is supported. In critical cases, we might supply back-ported patches for `v4`.
6 |
7 | ## Reporting a Vulnerability
8 |
9 | If you think you found a vulnerability, and even if you are not sure, please report it a [GitHub Security Advisory](https://github.com/golang-jwt/jwt/security/advisories/new). Please try be explicit, describe steps to reproduce the security issue with code example(s).
10 |
11 | You will receive a response within a timely manner. If the issue is confirmed, we will do our best to release a patch as soon as possible given the complexity of the problem.
12 |
13 | ## Public Discussions
14 |
15 | Please avoid publicly discussing a potential security vulnerability.
16 |
17 | Let's take this offline and find a solution first, this limits the potential impact as much as possible.
18 |
19 | We appreciate your help!
20 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md:
--------------------------------------------------------------------------------
1 | # `jwt-go` Version History
2 |
3 | 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 |
5 | ## 4.0.0
6 |
7 | * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`.
8 |
9 | ## 3.2.2
10 |
11 | * 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)).
12 | * 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)).
13 | * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)).
14 | * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)).
15 |
16 | ## 3.2.1
17 |
18 | * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code
19 | * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`
20 | * Fixed type confusing issue between `string` and `[]string` in `VerifyAudience` ([#12](https://github.com/golang-jwt/jwt/pull/12)). This fixes CVE-2020-26160
21 |
22 | #### 3.2.0
23 |
24 | * Added method `ParseUnverified` to allow users to split up the tasks of parsing and validation
25 | * HMAC signing method returns `ErrInvalidKeyType` instead of `ErrInvalidKey` where appropriate
26 | * Added options to `request.ParseFromRequest`, which allows for an arbitrary list of modifiers to parsing behavior. Initial set include `WithClaims` and `WithParser`. Existing usage of this function will continue to work as before.
27 | * Deprecated `ParseFromRequestWithClaims` to simplify API in the future.
28 |
29 | #### 3.1.0
30 |
31 | * Improvements to `jwt` command line tool
32 | * Added `SkipClaimsValidation` option to `Parser`
33 | * Documentation updates
34 |
35 | #### 3.0.0
36 |
37 | * **Compatibility Breaking Changes**: See MIGRATION_GUIDE.md for tips on updating your code
38 | * Dropped support for `[]byte` keys when using RSA signing methods. This convenience feature could contribute to security vulnerabilities involving mismatched key types with signing methods.
39 | * `ParseFromRequest` has been moved to `request` subpackage and usage has changed
40 | * The `Claims` property on `Token` is now type `Claims` instead of `map[string]interface{}`. The default value is type `MapClaims`, which is an alias to `map[string]interface{}`. This makes it possible to use a custom type when decoding claims.
41 | * Other Additions and Changes
42 | * Added `Claims` interface type to allow users to decode the claims into a custom type
43 | * Added `ParseWithClaims`, which takes a third argument of type `Claims`. Use this function instead of `Parse` if you have a custom type you'd like to decode into.
44 | * Dramatically improved the functionality and flexibility of `ParseFromRequest`, which is now in the `request` subpackage
45 | * Added `ParseFromRequestWithClaims` which is the `FromRequest` equivalent of `ParseWithClaims`
46 | * Added new interface type `Extractor`, which is used for extracting JWT strings from http requests. Used with `ParseFromRequest` and `ParseFromRequestWithClaims`.
47 | * Added several new, more specific, validation errors to error type bitmask
48 | * Moved examples from README to executable example files
49 | * Signing method registry is now thread safe
50 | * Added new property to `ValidationError`, which contains the raw error returned by calls made by parse/verify (such as those returned by keyfunc or json parser)
51 |
52 | #### 2.7.0
53 |
54 | This will likely be the last backwards compatible release before 3.0.0, excluding essential bug fixes.
55 |
56 | * Added new option `-show` to the `jwt` command that will just output the decoded token without verifying
57 | * Error text for expired tokens includes how long it's been expired
58 | * Fixed incorrect error returned from `ParseRSAPublicKeyFromPEM`
59 | * Documentation updates
60 |
61 | #### 2.6.0
62 |
63 | * Exposed inner error within ValidationError
64 | * Fixed validation errors when using UseJSONNumber flag
65 | * Added several unit tests
66 |
67 | #### 2.5.0
68 |
69 | * Added support for signing method none. You shouldn't use this. The API tries to make this clear.
70 | * Updated/fixed some documentation
71 | * Added more helpful error message when trying to parse tokens that begin with `BEARER `
72 |
73 | #### 2.4.0
74 |
75 | * Added new type, Parser, to allow for configuration of various parsing parameters
76 | * You can now specify a list of valid signing methods. Anything outside this set will be rejected.
77 | * You can now opt to use the `json.Number` type instead of `float64` when parsing token JSON
78 | * Added support for [Travis CI](https://travis-ci.org/dgrijalva/jwt-go)
79 | * Fixed some bugs with ECDSA parsing
80 |
81 | #### 2.3.0
82 |
83 | * Added support for ECDSA signing methods
84 | * Added support for RSA PSS signing methods (requires go v1.4)
85 |
86 | #### 2.2.0
87 |
88 | * Gracefully handle a `nil` `Keyfunc` being passed to `Parse`. Result will now be the parsed token and an error, instead of a panic.
89 |
90 | #### 2.1.0
91 |
92 | Backwards compatible API change that was missed in 2.0.0.
93 |
94 | * The `SignedString` method on `Token` now takes `interface{}` instead of `[]byte`
95 |
96 | #### 2.0.0
97 |
98 | There were two major reasons for breaking backwards compatibility with this update. The first was a refactor required to expand the width of the RSA and HMAC-SHA signing implementations. There will likely be no required code changes to support this change.
99 |
100 | The second update, while unfortunately requiring a small change in integration, is required to open up this library to other signing methods. Not all keys used for all signing methods have a single standard on-disk representation. Requiring `[]byte` as the type for all keys proved too limiting. Additionally, this implementation allows for pre-parsed tokens to be reused, which might matter in an application that parses a high volume of tokens with a small set of keys. Backwards compatibilty has been maintained for passing `[]byte` to the RSA signing methods, but they will also accept `*rsa.PublicKey` and `*rsa.PrivateKey`.
101 |
102 | It is likely the only integration change required here will be to change `func(t *jwt.Token) ([]byte, error)` to `func(t *jwt.Token) (interface{}, error)` when calling `Parse`.
103 |
104 | * **Compatibility Breaking Changes**
105 | * `SigningMethodHS256` is now `*SigningMethodHMAC` instead of `type struct`
106 | * `SigningMethodRS256` is now `*SigningMethodRSA` instead of `type struct`
107 | * `KeyFunc` now returns `interface{}` instead of `[]byte`
108 | * `SigningMethod.Sign` now takes `interface{}` instead of `[]byte` for the key
109 | * `SigningMethod.Verify` now takes `interface{}` instead of `[]byte` for the key
110 | * Renamed type `SigningMethodHS256` to `SigningMethodHMAC`. Specific sizes are now just instances of this type.
111 | * Added public package global `SigningMethodHS256`
112 | * Added public package global `SigningMethodHS384`
113 | * Added public package global `SigningMethodHS512`
114 | * Renamed type `SigningMethodRS256` to `SigningMethodRSA`. Specific sizes are now just instances of this type.
115 | * Added public package global `SigningMethodRS256`
116 | * Added public package global `SigningMethodRS384`
117 | * Added public package global `SigningMethodRS512`
118 | * Moved sample private key for HMAC tests from an inline value to a file on disk. Value is unchanged.
119 | * Refactored the RSA implementation to be easier to read
120 | * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM`
121 |
122 | ## 1.0.2
123 |
124 | * Fixed bug in parsing public keys from certificates
125 | * Added more tests around the parsing of keys for RS256
126 | * Code refactoring in RS256 implementation. No functional changes
127 |
128 | ## 1.0.1
129 |
130 | * Fixed panic if RS256 signing method was passed an invalid key
131 |
132 | ## 1.0.0
133 |
134 | * First versioned release
135 | * API stabilized
136 | * Supports creating, signing, parsing, and validating JWT tokens
137 | * Supports RS256 and HS256 signing methods
138 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/claims.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | // Claims represent any form of a JWT Claims Set according to
4 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a
5 | // common basis for validation, it is required that an implementation is able to
6 | // supply at least the claim names provided in
7 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`,
8 | // `iat`, `nbf`, `iss`, `sub` and `aud`.
9 | type Claims interface {
10 | GetExpirationTime() (*NumericDate, error)
11 | GetIssuedAt() (*NumericDate, error)
12 | GetNotBefore() (*NumericDate, error)
13 | GetIssuer() (string, error)
14 | GetSubject() (string, error)
15 | GetAudience() (ClaimStrings, error)
16 | }
17 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/doc.go:
--------------------------------------------------------------------------------
1 | // Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html
2 | //
3 | // See README.md for more info.
4 | package jwt
5 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "crypto/ecdsa"
6 | "crypto/rand"
7 | "errors"
8 | "math/big"
9 | )
10 |
11 | var (
12 | // Sadly this is missing from crypto/ecdsa compared to crypto/rsa
13 | ErrECDSAVerification = errors.New("crypto/ecdsa: verification error")
14 | )
15 |
16 | // SigningMethodECDSA implements the ECDSA family of signing methods.
17 | // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification
18 | type SigningMethodECDSA struct {
19 | Name string
20 | Hash crypto.Hash
21 | KeySize int
22 | CurveBits int
23 | }
24 |
25 | // Specific instances for EC256 and company
26 | var (
27 | SigningMethodES256 *SigningMethodECDSA
28 | SigningMethodES384 *SigningMethodECDSA
29 | SigningMethodES512 *SigningMethodECDSA
30 | )
31 |
32 | func init() {
33 | // ES256
34 | SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256}
35 | RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod {
36 | return SigningMethodES256
37 | })
38 |
39 | // ES384
40 | SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384}
41 | RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod {
42 | return SigningMethodES384
43 | })
44 |
45 | // ES512
46 | SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521}
47 | RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod {
48 | return SigningMethodES512
49 | })
50 | }
51 |
52 | func (m *SigningMethodECDSA) Alg() string {
53 | return m.Name
54 | }
55 |
56 | // Verify implements token verification for the SigningMethod.
57 | // For this verify method, key must be an ecdsa.PublicKey struct
58 | func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error {
59 | // Get the key
60 | var ecdsaKey *ecdsa.PublicKey
61 | switch k := key.(type) {
62 | case *ecdsa.PublicKey:
63 | ecdsaKey = k
64 | default:
65 | return newError("ECDSA verify expects *ecdsa.PublicKey", ErrInvalidKeyType)
66 | }
67 |
68 | if len(sig) != 2*m.KeySize {
69 | return ErrECDSAVerification
70 | }
71 |
72 | r := big.NewInt(0).SetBytes(sig[:m.KeySize])
73 | s := big.NewInt(0).SetBytes(sig[m.KeySize:])
74 |
75 | // Create hasher
76 | if !m.Hash.Available() {
77 | return ErrHashUnavailable
78 | }
79 | hasher := m.Hash.New()
80 | hasher.Write([]byte(signingString))
81 |
82 | // Verify the signature
83 | if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus {
84 | return nil
85 | }
86 |
87 | return ErrECDSAVerification
88 | }
89 |
90 | // Sign implements token signing for the SigningMethod.
91 | // For this signing method, key must be an ecdsa.PrivateKey struct
92 | func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) {
93 | // Get the key
94 | var ecdsaKey *ecdsa.PrivateKey
95 | switch k := key.(type) {
96 | case *ecdsa.PrivateKey:
97 | ecdsaKey = k
98 | default:
99 | return nil, newError("ECDSA sign expects *ecdsa.PrivateKey", ErrInvalidKeyType)
100 | }
101 |
102 | // Create the hasher
103 | if !m.Hash.Available() {
104 | return nil, ErrHashUnavailable
105 | }
106 |
107 | hasher := m.Hash.New()
108 | hasher.Write([]byte(signingString))
109 |
110 | // Sign the string and return r, s
111 | if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil {
112 | curveBits := ecdsaKey.Curve.Params().BitSize
113 |
114 | if m.CurveBits != curveBits {
115 | return nil, ErrInvalidKey
116 | }
117 |
118 | keyBytes := curveBits / 8
119 | if curveBits%8 > 0 {
120 | keyBytes += 1
121 | }
122 |
123 | // We serialize the outputs (r and s) into big-endian byte arrays
124 | // padded with zeros on the left to make sure the sizes work out.
125 | // Output must be 2*keyBytes long.
126 | out := make([]byte, 2*keyBytes)
127 | r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output.
128 | s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output.
129 |
130 | return out, nil
131 | } else {
132 | return nil, err
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto/ecdsa"
5 | "crypto/x509"
6 | "encoding/pem"
7 | "errors"
8 | )
9 |
10 | var (
11 | ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key")
12 | ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key")
13 | )
14 |
15 | // ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure
16 | func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) {
17 | var err error
18 |
19 | // Parse PEM block
20 | var block *pem.Block
21 | if block, _ = pem.Decode(key); block == nil {
22 | return nil, ErrKeyMustBePEMEncoded
23 | }
24 |
25 | // Parse the key
26 | var parsedKey interface{}
27 | if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil {
28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
29 | return nil, err
30 | }
31 | }
32 |
33 | var pkey *ecdsa.PrivateKey
34 | var ok bool
35 | if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok {
36 | return nil, ErrNotECPrivateKey
37 | }
38 |
39 | return pkey, nil
40 | }
41 |
42 | // ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key
43 | func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) {
44 | var err error
45 |
46 | // Parse PEM block
47 | var block *pem.Block
48 | if block, _ = pem.Decode(key); block == nil {
49 | return nil, ErrKeyMustBePEMEncoded
50 | }
51 |
52 | // Parse the key
53 | var parsedKey interface{}
54 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
55 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
56 | parsedKey = cert.PublicKey
57 | } else {
58 | return nil, err
59 | }
60 | }
61 |
62 | var pkey *ecdsa.PublicKey
63 | var ok bool
64 | if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok {
65 | return nil, ErrNotECPublicKey
66 | }
67 |
68 | return pkey, nil
69 | }
70 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/ed25519.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "crypto/ed25519"
6 | "crypto/rand"
7 | "errors"
8 | )
9 |
10 | var (
11 | ErrEd25519Verification = errors.New("ed25519: verification error")
12 | )
13 |
14 | // SigningMethodEd25519 implements the EdDSA family.
15 | // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification
16 | type SigningMethodEd25519 struct{}
17 |
18 | // Specific instance for EdDSA
19 | var (
20 | SigningMethodEdDSA *SigningMethodEd25519
21 | )
22 |
23 | func init() {
24 | SigningMethodEdDSA = &SigningMethodEd25519{}
25 | RegisterSigningMethod(SigningMethodEdDSA.Alg(), func() SigningMethod {
26 | return SigningMethodEdDSA
27 | })
28 | }
29 |
30 | func (m *SigningMethodEd25519) Alg() string {
31 | return "EdDSA"
32 | }
33 |
34 | // Verify implements token verification for the SigningMethod.
35 | // For this verify method, key must be an ed25519.PublicKey
36 | func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error {
37 | var ed25519Key ed25519.PublicKey
38 | var ok bool
39 |
40 | if ed25519Key, ok = key.(ed25519.PublicKey); !ok {
41 | return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType)
42 | }
43 |
44 | if len(ed25519Key) != ed25519.PublicKeySize {
45 | return ErrInvalidKey
46 | }
47 |
48 | // Verify the signature
49 | if !ed25519.Verify(ed25519Key, []byte(signingString), sig) {
50 | return ErrEd25519Verification
51 | }
52 |
53 | return nil
54 | }
55 |
56 | // Sign implements token signing for the SigningMethod.
57 | // For this signing method, key must be an ed25519.PrivateKey
58 | func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) {
59 | var ed25519Key crypto.Signer
60 | var ok bool
61 |
62 | if ed25519Key, ok = key.(crypto.Signer); !ok {
63 | return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType)
64 | }
65 |
66 | if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok {
67 | return nil, ErrInvalidKey
68 | }
69 |
70 | // Sign the string and return the result. ed25519 performs a two-pass hash
71 | // as part of its algorithm. Therefore, we need to pass a non-prehashed
72 | // message into the Sign function, as indicated by crypto.Hash(0)
73 | sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0))
74 | if err != nil {
75 | return nil, err
76 | }
77 |
78 | return sig, nil
79 | }
80 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "crypto/ed25519"
6 | "crypto/x509"
7 | "encoding/pem"
8 | "errors"
9 | )
10 |
11 | var (
12 | ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key")
13 | ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key")
14 | )
15 |
16 | // ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key
17 | func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) {
18 | var err error
19 |
20 | // Parse PEM block
21 | var block *pem.Block
22 | if block, _ = pem.Decode(key); block == nil {
23 | return nil, ErrKeyMustBePEMEncoded
24 | }
25 |
26 | // Parse the key
27 | var parsedKey interface{}
28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
29 | return nil, err
30 | }
31 |
32 | var pkey ed25519.PrivateKey
33 | var ok bool
34 | if pkey, ok = parsedKey.(ed25519.PrivateKey); !ok {
35 | return nil, ErrNotEdPrivateKey
36 | }
37 |
38 | return pkey, nil
39 | }
40 |
41 | // ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key
42 | func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) {
43 | var err error
44 |
45 | // Parse PEM block
46 | var block *pem.Block
47 | if block, _ = pem.Decode(key); block == nil {
48 | return nil, ErrKeyMustBePEMEncoded
49 | }
50 |
51 | // Parse the key
52 | var parsedKey interface{}
53 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
54 | return nil, err
55 | }
56 |
57 | var pkey ed25519.PublicKey
58 | var ok bool
59 | if pkey, ok = parsedKey.(ed25519.PublicKey); !ok {
60 | return nil, ErrNotEdPublicKey
61 | }
62 |
63 | return pkey, nil
64 | }
65 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/errors.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "errors"
5 | "strings"
6 | )
7 |
8 | var (
9 | ErrInvalidKey = errors.New("key is invalid")
10 | ErrInvalidKeyType = errors.New("key is of invalid type")
11 | ErrHashUnavailable = errors.New("the requested hash function is unavailable")
12 | ErrTokenMalformed = errors.New("token is malformed")
13 | ErrTokenUnverifiable = errors.New("token is unverifiable")
14 | ErrTokenSignatureInvalid = errors.New("token signature is invalid")
15 | ErrTokenRequiredClaimMissing = errors.New("token is missing required claim")
16 | ErrTokenInvalidAudience = errors.New("token has invalid audience")
17 | ErrTokenExpired = errors.New("token is expired")
18 | ErrTokenUsedBeforeIssued = errors.New("token used before issued")
19 | ErrTokenInvalidIssuer = errors.New("token has invalid issuer")
20 | ErrTokenInvalidSubject = errors.New("token has invalid subject")
21 | ErrTokenNotValidYet = errors.New("token is not valid yet")
22 | ErrTokenInvalidId = errors.New("token has invalid id")
23 | ErrTokenInvalidClaims = errors.New("token has invalid claims")
24 | ErrInvalidType = errors.New("invalid type for claim")
25 | )
26 |
27 | // joinedError is an error type that works similar to what [errors.Join]
28 | // produces, with the exception that it has a nice error string; mainly its
29 | // error messages are concatenated using a comma, rather than a newline.
30 | type joinedError struct {
31 | errs []error
32 | }
33 |
34 | func (je joinedError) Error() string {
35 | msg := []string{}
36 | for _, err := range je.errs {
37 | msg = append(msg, err.Error())
38 | }
39 |
40 | return strings.Join(msg, ", ")
41 | }
42 |
43 | // joinErrors joins together multiple errors. Useful for scenarios where
44 | // multiple errors next to each other occur, e.g., in claims validation.
45 | func joinErrors(errs ...error) error {
46 | return &joinedError{
47 | errs: errs,
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go:
--------------------------------------------------------------------------------
1 | //go:build go1.20
2 | // +build go1.20
3 |
4 | package jwt
5 |
6 | import (
7 | "fmt"
8 | )
9 |
10 | // Unwrap implements the multiple error unwrapping for this error type, which is
11 | // possible in Go 1.20.
12 | func (je joinedError) Unwrap() []error {
13 | return je.errs
14 | }
15 |
16 | // newError creates a new error message with a detailed error message. The
17 | // message will be prefixed with the contents of the supplied error type.
18 | // Additionally, more errors, that provide more context can be supplied which
19 | // will be appended to the message. This makes use of Go 1.20's possibility to
20 | // include more than one %w formatting directive in [fmt.Errorf].
21 | //
22 | // For example,
23 | //
24 | // newError("no keyfunc was provided", ErrTokenUnverifiable)
25 | //
26 | // will produce the error string
27 | //
28 | // "token is unverifiable: no keyfunc was provided"
29 | func newError(message string, err error, more ...error) error {
30 | var format string
31 | var args []any
32 | if message != "" {
33 | format = "%w: %s"
34 | args = []any{err, message}
35 | } else {
36 | format = "%w"
37 | args = []any{err}
38 | }
39 |
40 | for _, e := range more {
41 | format += ": %w"
42 | args = append(args, e)
43 | }
44 |
45 | err = fmt.Errorf(format, args...)
46 | return err
47 | }
48 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go:
--------------------------------------------------------------------------------
1 | //go:build !go1.20
2 | // +build !go1.20
3 |
4 | package jwt
5 |
6 | import (
7 | "errors"
8 | "fmt"
9 | )
10 |
11 | // Is implements checking for multiple errors using [errors.Is], since multiple
12 | // error unwrapping is not possible in versions less than Go 1.20.
13 | func (je joinedError) Is(err error) bool {
14 | for _, e := range je.errs {
15 | if errors.Is(e, err) {
16 | return true
17 | }
18 | }
19 |
20 | return false
21 | }
22 |
23 | // wrappedErrors is a workaround for wrapping multiple errors in environments
24 | // where Go 1.20 is not available. It basically uses the already implemented
25 | // functionality of joinedError to handle multiple errors with supplies a
26 | // custom error message that is identical to the one we produce in Go 1.20 using
27 | // multiple %w directives.
28 | type wrappedErrors struct {
29 | msg string
30 | joinedError
31 | }
32 |
33 | // Error returns the stored error string
34 | func (we wrappedErrors) Error() string {
35 | return we.msg
36 | }
37 |
38 | // newError creates a new error message with a detailed error message. The
39 | // message will be prefixed with the contents of the supplied error type.
40 | // Additionally, more errors, that provide more context can be supplied which
41 | // will be appended to the message. Since we cannot use of Go 1.20's possibility
42 | // to include more than one %w formatting directive in [fmt.Errorf], we have to
43 | // emulate that.
44 | //
45 | // For example,
46 | //
47 | // newError("no keyfunc was provided", ErrTokenUnverifiable)
48 | //
49 | // will produce the error string
50 | //
51 | // "token is unverifiable: no keyfunc was provided"
52 | func newError(message string, err error, more ...error) error {
53 | // We cannot wrap multiple errors here with %w, so we have to be a little
54 | // bit creative. Basically, we are using %s instead of %w to produce the
55 | // same error message and then throw the result into a custom error struct.
56 | var format string
57 | var args []any
58 | if message != "" {
59 | format = "%s: %s"
60 | args = []any{err, message}
61 | } else {
62 | format = "%s"
63 | args = []any{err}
64 | }
65 | errs := []error{err}
66 |
67 | for _, e := range more {
68 | format += ": %s"
69 | args = append(args, e)
70 | errs = append(errs, e)
71 | }
72 |
73 | err = &wrappedErrors{
74 | msg: fmt.Sprintf(format, args...),
75 | joinedError: joinedError{errs: errs},
76 | }
77 | return err
78 | }
79 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/hmac.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "crypto/hmac"
6 | "errors"
7 | )
8 |
9 | // SigningMethodHMAC implements the HMAC-SHA family of signing methods.
10 | // Expects key type of []byte for both signing and validation
11 | type SigningMethodHMAC struct {
12 | Name string
13 | Hash crypto.Hash
14 | }
15 |
16 | // Specific instances for HS256 and company
17 | var (
18 | SigningMethodHS256 *SigningMethodHMAC
19 | SigningMethodHS384 *SigningMethodHMAC
20 | SigningMethodHS512 *SigningMethodHMAC
21 | ErrSignatureInvalid = errors.New("signature is invalid")
22 | )
23 |
24 | func init() {
25 | // HS256
26 | SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256}
27 | RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod {
28 | return SigningMethodHS256
29 | })
30 |
31 | // HS384
32 | SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384}
33 | RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod {
34 | return SigningMethodHS384
35 | })
36 |
37 | // HS512
38 | SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512}
39 | RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod {
40 | return SigningMethodHS512
41 | })
42 | }
43 |
44 | func (m *SigningMethodHMAC) Alg() string {
45 | return m.Name
46 | }
47 |
48 | // Verify implements token verification for the SigningMethod. Returns nil if
49 | // the signature is valid. Key must be []byte.
50 | //
51 | // Note it is not advised to provide a []byte which was converted from a 'human
52 | // readable' string using a subset of ASCII characters. To maximize entropy, you
53 | // should ideally be providing a []byte key which was produced from a
54 | // cryptographically random source, e.g. crypto/rand. Additional information
55 | // about this, and why we intentionally are not supporting string as a key can
56 | // be found on our usage guide
57 | // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types.
58 | func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error {
59 | // Verify the key is the right type
60 | keyBytes, ok := key.([]byte)
61 | if !ok {
62 | return newError("HMAC verify expects []byte", ErrInvalidKeyType)
63 | }
64 |
65 | // Can we use the specified hashing method?
66 | if !m.Hash.Available() {
67 | return ErrHashUnavailable
68 | }
69 |
70 | // This signing method is symmetric, so we validate the signature
71 | // by reproducing the signature from the signing string and key, then
72 | // comparing that against the provided signature.
73 | hasher := hmac.New(m.Hash.New, keyBytes)
74 | hasher.Write([]byte(signingString))
75 | if !hmac.Equal(sig, hasher.Sum(nil)) {
76 | return ErrSignatureInvalid
77 | }
78 |
79 | // No validation errors. Signature is good.
80 | return nil
81 | }
82 |
83 | // Sign implements token signing for the SigningMethod. Key must be []byte.
84 | //
85 | // Note it is not advised to provide a []byte which was converted from a 'human
86 | // readable' string using a subset of ASCII characters. To maximize entropy, you
87 | // should ideally be providing a []byte key which was produced from a
88 | // cryptographically random source, e.g. crypto/rand. Additional information
89 | // about this, and why we intentionally are not supporting string as a key can
90 | // be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/.
91 | func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) {
92 | if keyBytes, ok := key.([]byte); ok {
93 | if !m.Hash.Available() {
94 | return nil, ErrHashUnavailable
95 | }
96 |
97 | hasher := hmac.New(m.Hash.New, keyBytes)
98 | hasher.Write([]byte(signingString))
99 |
100 | return hasher.Sum(nil), nil
101 | }
102 |
103 | return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType)
104 | }
105 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/map_claims.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | )
7 |
8 | // MapClaims is a claims type that uses the map[string]interface{} for JSON
9 | // decoding. This is the default claims type if you don't supply one
10 | type MapClaims map[string]interface{}
11 |
12 | // GetExpirationTime implements the Claims interface.
13 | func (m MapClaims) GetExpirationTime() (*NumericDate, error) {
14 | return m.parseNumericDate("exp")
15 | }
16 |
17 | // GetNotBefore implements the Claims interface.
18 | func (m MapClaims) GetNotBefore() (*NumericDate, error) {
19 | return m.parseNumericDate("nbf")
20 | }
21 |
22 | // GetIssuedAt implements the Claims interface.
23 | func (m MapClaims) GetIssuedAt() (*NumericDate, error) {
24 | return m.parseNumericDate("iat")
25 | }
26 |
27 | // GetAudience implements the Claims interface.
28 | func (m MapClaims) GetAudience() (ClaimStrings, error) {
29 | return m.parseClaimsString("aud")
30 | }
31 |
32 | // GetIssuer implements the Claims interface.
33 | func (m MapClaims) GetIssuer() (string, error) {
34 | return m.parseString("iss")
35 | }
36 |
37 | // GetSubject implements the Claims interface.
38 | func (m MapClaims) GetSubject() (string, error) {
39 | return m.parseString("sub")
40 | }
41 |
42 | // parseNumericDate tries to parse a key in the map claims type as a number
43 | // date. This will succeed, if the underlying type is either a [float64] or a
44 | // [json.Number]. Otherwise, nil will be returned.
45 | func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) {
46 | v, ok := m[key]
47 | if !ok {
48 | return nil, nil
49 | }
50 |
51 | switch exp := v.(type) {
52 | case float64:
53 | if exp == 0 {
54 | return nil, nil
55 | }
56 |
57 | return newNumericDateFromSeconds(exp), nil
58 | case json.Number:
59 | v, _ := exp.Float64()
60 |
61 | return newNumericDateFromSeconds(v), nil
62 | }
63 |
64 | return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType)
65 | }
66 |
67 | // parseClaimsString tries to parse a key in the map claims type as a
68 | // [ClaimsStrings] type, which can either be a string or an array of string.
69 | func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) {
70 | var cs []string
71 | switch v := m[key].(type) {
72 | case string:
73 | cs = append(cs, v)
74 | case []string:
75 | cs = v
76 | case []interface{}:
77 | for _, a := range v {
78 | vs, ok := a.(string)
79 | if !ok {
80 | return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType)
81 | }
82 | cs = append(cs, vs)
83 | }
84 | }
85 |
86 | return cs, nil
87 | }
88 |
89 | // parseString tries to parse a key in the map claims type as a [string] type.
90 | // If the key does not exist, an empty string is returned. If the key has the
91 | // wrong type, an error is returned.
92 | func (m MapClaims) parseString(key string) (string, error) {
93 | var (
94 | ok bool
95 | raw interface{}
96 | iss string
97 | )
98 | raw, ok = m[key]
99 | if !ok {
100 | return "", nil
101 | }
102 |
103 | iss, ok = raw.(string)
104 | if !ok {
105 | return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType)
106 | }
107 |
108 | return iss, nil
109 | }
110 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/none.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | // SigningMethodNone implements the none signing method. This is required by the spec
4 | // but you probably should never use it.
5 | var SigningMethodNone *signingMethodNone
6 |
7 | const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed"
8 |
9 | var NoneSignatureTypeDisallowedError error
10 |
11 | type signingMethodNone struct{}
12 | type unsafeNoneMagicConstant string
13 |
14 | func init() {
15 | SigningMethodNone = &signingMethodNone{}
16 | NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable)
17 |
18 | RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod {
19 | return SigningMethodNone
20 | })
21 | }
22 |
23 | func (m *signingMethodNone) Alg() string {
24 | return "none"
25 | }
26 |
27 | // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key
28 | func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) {
29 | // Key must be UnsafeAllowNoneSignatureType to prevent accidentally
30 | // accepting 'none' signing method
31 | if _, ok := key.(unsafeNoneMagicConstant); !ok {
32 | return NoneSignatureTypeDisallowedError
33 | }
34 | // If signing method is none, signature must be an empty string
35 | if len(sig) != 0 {
36 | return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable)
37 | }
38 |
39 | // Accept 'none' signing method.
40 | return nil
41 | }
42 |
43 | // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key
44 | func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) {
45 | if _, ok := key.(unsafeNoneMagicConstant); ok {
46 | return []byte{}, nil
47 | }
48 |
49 | return nil, NoneSignatureTypeDisallowedError
50 | }
51 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/parser_option.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import "time"
4 |
5 | // ParserOption is used to implement functional-style options that modify the
6 | // behavior of the parser. To add new options, just create a function (ideally
7 | // beginning with With or Without) that returns an anonymous function that takes
8 | // a *Parser type as input and manipulates its configuration accordingly.
9 | type ParserOption func(*Parser)
10 |
11 | // WithValidMethods is an option to supply algorithm methods that the parser
12 | // will check. Only those methods will be considered valid. It is heavily
13 | // encouraged to use this option in order to prevent attacks such as
14 | // https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/.
15 | func WithValidMethods(methods []string) ParserOption {
16 | return func(p *Parser) {
17 | p.validMethods = methods
18 | }
19 | }
20 |
21 | // WithJSONNumber is an option to configure the underlying JSON parser with
22 | // UseNumber.
23 | func WithJSONNumber() ParserOption {
24 | return func(p *Parser) {
25 | p.useJSONNumber = true
26 | }
27 | }
28 |
29 | // WithoutClaimsValidation is an option to disable claims validation. This
30 | // option should only be used if you exactly know what you are doing.
31 | func WithoutClaimsValidation() ParserOption {
32 | return func(p *Parser) {
33 | p.skipClaimsValidation = true
34 | }
35 | }
36 |
37 | // WithLeeway returns the ParserOption for specifying the leeway window.
38 | func WithLeeway(leeway time.Duration) ParserOption {
39 | return func(p *Parser) {
40 | p.validator.leeway = leeway
41 | }
42 | }
43 |
44 | // WithTimeFunc returns the ParserOption for specifying the time func. The
45 | // primary use-case for this is testing. If you are looking for a way to account
46 | // for clock-skew, WithLeeway should be used instead.
47 | func WithTimeFunc(f func() time.Time) ParserOption {
48 | return func(p *Parser) {
49 | p.validator.timeFunc = f
50 | }
51 | }
52 |
53 | // WithIssuedAt returns the ParserOption to enable verification
54 | // of issued-at.
55 | func WithIssuedAt() ParserOption {
56 | return func(p *Parser) {
57 | p.validator.verifyIat = true
58 | }
59 | }
60 |
61 | // WithExpirationRequired returns the ParserOption to make exp claim required.
62 | // By default exp claim is optional.
63 | func WithExpirationRequired() ParserOption {
64 | return func(p *Parser) {
65 | p.validator.requireExp = true
66 | }
67 | }
68 |
69 | // WithAudience configures the validator to require the specified audience in
70 | // the `aud` claim. Validation will fail if the audience is not listed in the
71 | // token or the `aud` claim is missing.
72 | //
73 | // NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is
74 | // application-specific. Since this validation API is helping developers in
75 | // writing secure application, we decided to REQUIRE the existence of the claim,
76 | // if an audience is expected.
77 | func WithAudience(aud string) ParserOption {
78 | return func(p *Parser) {
79 | p.validator.expectedAud = aud
80 | }
81 | }
82 |
83 | // WithIssuer configures the validator to require the specified issuer in the
84 | // `iss` claim. Validation will fail if a different issuer is specified in the
85 | // token or the `iss` claim is missing.
86 | //
87 | // NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is
88 | // application-specific. Since this validation API is helping developers in
89 | // writing secure application, we decided to REQUIRE the existence of the claim,
90 | // if an issuer is expected.
91 | func WithIssuer(iss string) ParserOption {
92 | return func(p *Parser) {
93 | p.validator.expectedIss = iss
94 | }
95 | }
96 |
97 | // WithSubject configures the validator to require the specified subject in the
98 | // `sub` claim. Validation will fail if a different subject is specified in the
99 | // token or the `sub` claim is missing.
100 | //
101 | // NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is
102 | // application-specific. Since this validation API is helping developers in
103 | // writing secure application, we decided to REQUIRE the existence of the claim,
104 | // if a subject is expected.
105 | func WithSubject(sub string) ParserOption {
106 | return func(p *Parser) {
107 | p.validator.expectedSub = sub
108 | }
109 | }
110 |
111 | // WithPaddingAllowed will enable the codec used for decoding JWTs to allow
112 | // padding. Note that the JWS RFC7515 states that the tokens will utilize a
113 | // Base64url encoding with no padding. Unfortunately, some implementations of
114 | // JWT are producing non-standard tokens, and thus require support for decoding.
115 | func WithPaddingAllowed() ParserOption {
116 | return func(p *Parser) {
117 | p.decodePaddingAllowed = true
118 | }
119 | }
120 |
121 | // WithStrictDecoding will switch the codec used for decoding JWTs into strict
122 | // mode. In this mode, the decoder requires that trailing padding bits are zero,
123 | // as described in RFC 4648 section 3.5.
124 | func WithStrictDecoding() ParserOption {
125 | return func(p *Parser) {
126 | p.decodeStrict = true
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | // RegisteredClaims are a structured version of the JWT Claims Set,
4 | // restricted to Registered Claim Names, as referenced at
5 | // https://datatracker.ietf.org/doc/html/rfc7519#section-4.1
6 | //
7 | // This type can be used on its own, but then additional private and
8 | // public claims embedded in the JWT will not be parsed. The typical use-case
9 | // therefore is to embedded this in a user-defined claim type.
10 | //
11 | // See examples for how to use this with your own claim types.
12 | type RegisteredClaims struct {
13 | // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1
14 | Issuer string `json:"iss,omitempty"`
15 |
16 | // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2
17 | Subject string `json:"sub,omitempty"`
18 |
19 | // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3
20 | Audience ClaimStrings `json:"aud,omitempty"`
21 |
22 | // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4
23 | ExpiresAt *NumericDate `json:"exp,omitempty"`
24 |
25 | // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5
26 | NotBefore *NumericDate `json:"nbf,omitempty"`
27 |
28 | // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6
29 | IssuedAt *NumericDate `json:"iat,omitempty"`
30 |
31 | // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7
32 | ID string `json:"jti,omitempty"`
33 | }
34 |
35 | // GetExpirationTime implements the Claims interface.
36 | func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) {
37 | return c.ExpiresAt, nil
38 | }
39 |
40 | // GetNotBefore implements the Claims interface.
41 | func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) {
42 | return c.NotBefore, nil
43 | }
44 |
45 | // GetIssuedAt implements the Claims interface.
46 | func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) {
47 | return c.IssuedAt, nil
48 | }
49 |
50 | // GetAudience implements the Claims interface.
51 | func (c RegisteredClaims) GetAudience() (ClaimStrings, error) {
52 | return c.Audience, nil
53 | }
54 |
55 | // GetIssuer implements the Claims interface.
56 | func (c RegisteredClaims) GetIssuer() (string, error) {
57 | return c.Issuer, nil
58 | }
59 |
60 | // GetSubject implements the Claims interface.
61 | func (c RegisteredClaims) GetSubject() (string, error) {
62 | return c.Subject, nil
63 | }
64 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/rsa.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "crypto/rand"
6 | "crypto/rsa"
7 | )
8 |
9 | // SigningMethodRSA implements the RSA family of signing methods.
10 | // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation
11 | type SigningMethodRSA struct {
12 | Name string
13 | Hash crypto.Hash
14 | }
15 |
16 | // Specific instances for RS256 and company
17 | var (
18 | SigningMethodRS256 *SigningMethodRSA
19 | SigningMethodRS384 *SigningMethodRSA
20 | SigningMethodRS512 *SigningMethodRSA
21 | )
22 |
23 | func init() {
24 | // RS256
25 | SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256}
26 | RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod {
27 | return SigningMethodRS256
28 | })
29 |
30 | // RS384
31 | SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384}
32 | RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod {
33 | return SigningMethodRS384
34 | })
35 |
36 | // RS512
37 | SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512}
38 | RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod {
39 | return SigningMethodRS512
40 | })
41 | }
42 |
43 | func (m *SigningMethodRSA) Alg() string {
44 | return m.Name
45 | }
46 |
47 | // Verify implements token verification for the SigningMethod
48 | // For this signing method, must be an *rsa.PublicKey structure.
49 | func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error {
50 | var rsaKey *rsa.PublicKey
51 | var ok bool
52 |
53 | if rsaKey, ok = key.(*rsa.PublicKey); !ok {
54 | return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType)
55 | }
56 |
57 | // Create hasher
58 | if !m.Hash.Available() {
59 | return ErrHashUnavailable
60 | }
61 | hasher := m.Hash.New()
62 | hasher.Write([]byte(signingString))
63 |
64 | // Verify the signature
65 | return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig)
66 | }
67 |
68 | // Sign implements token signing for the SigningMethod
69 | // For this signing method, must be an *rsa.PrivateKey structure.
70 | func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) {
71 | var rsaKey *rsa.PrivateKey
72 | var ok bool
73 |
74 | // Validate type of key
75 | if rsaKey, ok = key.(*rsa.PrivateKey); !ok {
76 | return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType)
77 | }
78 |
79 | // Create the hasher
80 | if !m.Hash.Available() {
81 | return nil, ErrHashUnavailable
82 | }
83 |
84 | hasher := m.Hash.New()
85 | hasher.Write([]byte(signingString))
86 |
87 | // Sign the string and return the encoded bytes
88 | if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil {
89 | return sigBytes, nil
90 | } else {
91 | return nil, err
92 | }
93 | }
94 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go:
--------------------------------------------------------------------------------
1 | //go:build go1.4
2 | // +build go1.4
3 |
4 | package jwt
5 |
6 | import (
7 | "crypto"
8 | "crypto/rand"
9 | "crypto/rsa"
10 | )
11 |
12 | // SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods
13 | type SigningMethodRSAPSS struct {
14 | *SigningMethodRSA
15 | Options *rsa.PSSOptions
16 | // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS.
17 | // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow
18 | // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously.
19 | // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details.
20 | VerifyOptions *rsa.PSSOptions
21 | }
22 |
23 | // Specific instances for RS/PS and company.
24 | var (
25 | SigningMethodPS256 *SigningMethodRSAPSS
26 | SigningMethodPS384 *SigningMethodRSAPSS
27 | SigningMethodPS512 *SigningMethodRSAPSS
28 | )
29 |
30 | func init() {
31 | // PS256
32 | SigningMethodPS256 = &SigningMethodRSAPSS{
33 | SigningMethodRSA: &SigningMethodRSA{
34 | Name: "PS256",
35 | Hash: crypto.SHA256,
36 | },
37 | Options: &rsa.PSSOptions{
38 | SaltLength: rsa.PSSSaltLengthEqualsHash,
39 | },
40 | VerifyOptions: &rsa.PSSOptions{
41 | SaltLength: rsa.PSSSaltLengthAuto,
42 | },
43 | }
44 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod {
45 | return SigningMethodPS256
46 | })
47 |
48 | // PS384
49 | SigningMethodPS384 = &SigningMethodRSAPSS{
50 | SigningMethodRSA: &SigningMethodRSA{
51 | Name: "PS384",
52 | Hash: crypto.SHA384,
53 | },
54 | Options: &rsa.PSSOptions{
55 | SaltLength: rsa.PSSSaltLengthEqualsHash,
56 | },
57 | VerifyOptions: &rsa.PSSOptions{
58 | SaltLength: rsa.PSSSaltLengthAuto,
59 | },
60 | }
61 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod {
62 | return SigningMethodPS384
63 | })
64 |
65 | // PS512
66 | SigningMethodPS512 = &SigningMethodRSAPSS{
67 | SigningMethodRSA: &SigningMethodRSA{
68 | Name: "PS512",
69 | Hash: crypto.SHA512,
70 | },
71 | Options: &rsa.PSSOptions{
72 | SaltLength: rsa.PSSSaltLengthEqualsHash,
73 | },
74 | VerifyOptions: &rsa.PSSOptions{
75 | SaltLength: rsa.PSSSaltLengthAuto,
76 | },
77 | }
78 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod {
79 | return SigningMethodPS512
80 | })
81 | }
82 |
83 | // Verify implements token verification for the SigningMethod.
84 | // For this verify method, key must be an rsa.PublicKey struct
85 | func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error {
86 | var rsaKey *rsa.PublicKey
87 | switch k := key.(type) {
88 | case *rsa.PublicKey:
89 | rsaKey = k
90 | default:
91 | return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType)
92 | }
93 |
94 | // Create hasher
95 | if !m.Hash.Available() {
96 | return ErrHashUnavailable
97 | }
98 | hasher := m.Hash.New()
99 | hasher.Write([]byte(signingString))
100 |
101 | opts := m.Options
102 | if m.VerifyOptions != nil {
103 | opts = m.VerifyOptions
104 | }
105 |
106 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts)
107 | }
108 |
109 | // Sign implements token signing for the SigningMethod.
110 | // For this signing method, key must be an rsa.PrivateKey struct
111 | func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) {
112 | var rsaKey *rsa.PrivateKey
113 |
114 | switch k := key.(type) {
115 | case *rsa.PrivateKey:
116 | rsaKey = k
117 | default:
118 | return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType)
119 | }
120 |
121 | // Create the hasher
122 | if !m.Hash.Available() {
123 | return nil, ErrHashUnavailable
124 | }
125 |
126 | hasher := m.Hash.New()
127 | hasher.Write([]byte(signingString))
128 |
129 | // Sign the string and return the encoded bytes
130 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil {
131 | return sigBytes, nil
132 | } else {
133 | return nil, err
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto/rsa"
5 | "crypto/x509"
6 | "encoding/pem"
7 | "errors"
8 | )
9 |
10 | var (
11 | ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key")
12 | ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key")
13 | ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key")
14 | )
15 |
16 | // ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key
17 | func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
18 | var err error
19 |
20 | // Parse PEM block
21 | var block *pem.Block
22 | if block, _ = pem.Decode(key); block == nil {
23 | return nil, ErrKeyMustBePEMEncoded
24 | }
25 |
26 | var parsedKey interface{}
27 | if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
28 | if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil {
29 | return nil, err
30 | }
31 | }
32 |
33 | var pkey *rsa.PrivateKey
34 | var ok bool
35 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
36 | return nil, ErrNotRSAPrivateKey
37 | }
38 |
39 | return pkey, nil
40 | }
41 |
42 | // ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password
43 | //
44 | // Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock
45 | // function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative
46 | // in the Go standard library for now. See https://github.com/golang/go/issues/8860.
47 | func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) {
48 | var err error
49 |
50 | // Parse PEM block
51 | var block *pem.Block
52 | if block, _ = pem.Decode(key); block == nil {
53 | return nil, ErrKeyMustBePEMEncoded
54 | }
55 |
56 | var parsedKey interface{}
57 |
58 | var blockDecrypted []byte
59 | if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil {
60 | return nil, err
61 | }
62 |
63 | if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil {
64 | if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil {
65 | return nil, err
66 | }
67 | }
68 |
69 | var pkey *rsa.PrivateKey
70 | var ok bool
71 | if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
72 | return nil, ErrNotRSAPrivateKey
73 | }
74 |
75 | return pkey, nil
76 | }
77 |
78 | // ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key
79 | func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
80 | var err error
81 |
82 | // Parse PEM block
83 | var block *pem.Block
84 | if block, _ = pem.Decode(key); block == nil {
85 | return nil, ErrKeyMustBePEMEncoded
86 | }
87 |
88 | // Parse the key
89 | var parsedKey interface{}
90 | if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil {
91 | if cert, err := x509.ParseCertificate(block.Bytes); err == nil {
92 | parsedKey = cert.PublicKey
93 | } else {
94 | if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil {
95 | return nil, err
96 | }
97 | }
98 | }
99 |
100 | var pkey *rsa.PublicKey
101 | var ok bool
102 | if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
103 | return nil, ErrNotRSAPublicKey
104 | }
105 |
106 | return pkey, nil
107 | }
108 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/signing_method.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "sync"
5 | )
6 |
7 | var signingMethods = map[string]func() SigningMethod{}
8 | var signingMethodLock = new(sync.RWMutex)
9 |
10 | // SigningMethod can be used add new methods for signing or verifying tokens. It
11 | // takes a decoded signature as an input in the Verify function and produces a
12 | // signature in Sign. The signature is then usually base64 encoded as part of a
13 | // JWT.
14 | type SigningMethod interface {
15 | Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid
16 | Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error
17 | Alg() string // returns the alg identifier for this method (example: 'HS256')
18 | }
19 |
20 | // RegisterSigningMethod registers the "alg" name and a factory function for signing method.
21 | // This is typically done during init() in the method's implementation
22 | func RegisterSigningMethod(alg string, f func() SigningMethod) {
23 | signingMethodLock.Lock()
24 | defer signingMethodLock.Unlock()
25 |
26 | signingMethods[alg] = f
27 | }
28 |
29 | // GetSigningMethod retrieves a signing method from an "alg" string
30 | func GetSigningMethod(alg string) (method SigningMethod) {
31 | signingMethodLock.RLock()
32 | defer signingMethodLock.RUnlock()
33 |
34 | if methodF, ok := signingMethods[alg]; ok {
35 | method = methodF()
36 | }
37 | return
38 | }
39 |
40 | // GetAlgorithms returns a list of registered "alg" names
41 | func GetAlgorithms() (algs []string) {
42 | signingMethodLock.RLock()
43 | defer signingMethodLock.RUnlock()
44 |
45 | for alg := range signingMethods {
46 | algs = append(algs, alg)
47 | }
48 | return
49 | }
50 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf:
--------------------------------------------------------------------------------
1 | checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"]
2 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/token.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "crypto"
5 | "encoding/base64"
6 | "encoding/json"
7 | )
8 |
9 | // Keyfunc will be used by the Parse methods as a callback function to supply
10 | // the key for verification. The function receives the parsed, but unverified
11 | // Token. This allows you to use properties in the Header of the token (such as
12 | // `kid`) to identify which key to use.
13 | //
14 | // The returned interface{} may be a single key or a VerificationKeySet containing
15 | // multiple keys.
16 | type Keyfunc func(*Token) (interface{}, error)
17 |
18 | // VerificationKey represents a public or secret key for verifying a token's signature.
19 | type VerificationKey interface {
20 | crypto.PublicKey | []uint8
21 | }
22 |
23 | // VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token.
24 | type VerificationKeySet struct {
25 | Keys []VerificationKey
26 | }
27 |
28 | // Token represents a JWT Token. Different fields will be used depending on
29 | // whether you're creating or parsing/verifying a token.
30 | type Token struct {
31 | Raw string // Raw contains the raw token. Populated when you [Parse] a token
32 | Method SigningMethod // Method is the signing method used or to be used
33 | Header map[string]interface{} // Header is the first segment of the token in decoded form
34 | Claims Claims // Claims is the second segment of the token in decoded form
35 | Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token
36 | Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token
37 | }
38 |
39 | // New creates a new [Token] with the specified signing method and an empty map
40 | // of claims. Additional options can be specified, but are currently unused.
41 | func New(method SigningMethod, opts ...TokenOption) *Token {
42 | return NewWithClaims(method, MapClaims{}, opts...)
43 | }
44 |
45 | // NewWithClaims creates a new [Token] with the specified signing method and
46 | // claims. Additional options can be specified, but are currently unused.
47 | func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token {
48 | return &Token{
49 | Header: map[string]interface{}{
50 | "typ": "JWT",
51 | "alg": method.Alg(),
52 | },
53 | Claims: claims,
54 | Method: method,
55 | }
56 | }
57 |
58 | // SignedString creates and returns a complete, signed JWT. The token is signed
59 | // using the SigningMethod specified in the token. Please refer to
60 | // https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types
61 | // for an overview of the different signing methods and their respective key
62 | // types.
63 | func (t *Token) SignedString(key interface{}) (string, error) {
64 | sstr, err := t.SigningString()
65 | if err != nil {
66 | return "", err
67 | }
68 |
69 | sig, err := t.Method.Sign(sstr, key)
70 | if err != nil {
71 | return "", err
72 | }
73 |
74 | return sstr + "." + t.EncodeSegment(sig), nil
75 | }
76 |
77 | // SigningString generates the signing string. This is the most expensive part
78 | // of the whole deal. Unless you need this for something special, just go
79 | // straight for the SignedString.
80 | func (t *Token) SigningString() (string, error) {
81 | h, err := json.Marshal(t.Header)
82 | if err != nil {
83 | return "", err
84 | }
85 |
86 | c, err := json.Marshal(t.Claims)
87 | if err != nil {
88 | return "", err
89 | }
90 |
91 | return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil
92 | }
93 |
94 | // EncodeSegment encodes a JWT specific base64url encoding with padding
95 | // stripped. In the future, this function might take into account a
96 | // [TokenOption]. Therefore, this function exists as a method of [Token], rather
97 | // than a global function.
98 | func (*Token) EncodeSegment(seg []byte) string {
99 | return base64.RawURLEncoding.EncodeToString(seg)
100 | }
101 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/token_option.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | // TokenOption is a reserved type, which provides some forward compatibility,
4 | // if we ever want to introduce token creation-related options.
5 | type TokenOption func(*Token)
6 |
--------------------------------------------------------------------------------
/vendor/github.com/golang-jwt/jwt/v5/types.go:
--------------------------------------------------------------------------------
1 | package jwt
2 |
3 | import (
4 | "encoding/json"
5 | "fmt"
6 | "math"
7 | "strconv"
8 | "time"
9 | )
10 |
11 | // TimePrecision sets the precision of times and dates within this library. This
12 | // has an influence on the precision of times when comparing expiry or other
13 | // related time fields. Furthermore, it is also the precision of times when
14 | // serializing.
15 | //
16 | // For backwards compatibility the default precision is set to seconds, so that
17 | // no fractional timestamps are generated.
18 | var TimePrecision = time.Second
19 |
20 | // MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type,
21 | // especially its MarshalJSON function.
22 | //
23 | // If it is set to true (the default), it will always serialize the type as an
24 | // array of strings, even if it just contains one element, defaulting to the
25 | // behavior of the underlying []string. If it is set to false, it will serialize
26 | // to a single string, if it contains one element. Otherwise, it will serialize
27 | // to an array of strings.
28 | var MarshalSingleStringAsArray = true
29 |
30 | // NumericDate represents a JSON numeric date value, as referenced at
31 | // https://datatracker.ietf.org/doc/html/rfc7519#section-2.
32 | type NumericDate struct {
33 | time.Time
34 | }
35 |
36 | // NewNumericDate constructs a new *NumericDate from a standard library time.Time struct.
37 | // It will truncate the timestamp according to the precision specified in TimePrecision.
38 | func NewNumericDate(t time.Time) *NumericDate {
39 | return &NumericDate{t.Truncate(TimePrecision)}
40 | }
41 |
42 | // newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a
43 | // UNIX epoch with the float fraction representing non-integer seconds.
44 | func newNumericDateFromSeconds(f float64) *NumericDate {
45 | round, frac := math.Modf(f)
46 | return NewNumericDate(time.Unix(int64(round), int64(frac*1e9)))
47 | }
48 |
49 | // MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch
50 | // represented in NumericDate to a byte array, using the precision specified in TimePrecision.
51 | func (date NumericDate) MarshalJSON() (b []byte, err error) {
52 | var prec int
53 | if TimePrecision < time.Second {
54 | prec = int(math.Log10(float64(time.Second) / float64(TimePrecision)))
55 | }
56 | truncatedDate := date.Truncate(TimePrecision)
57 |
58 | // For very large timestamps, UnixNano would overflow an int64, but this
59 | // function requires nanosecond level precision, so we have to use the
60 | // following technique to get round the issue:
61 | //
62 | // 1. Take the normal unix timestamp to form the whole number part of the
63 | // output,
64 | // 2. Take the result of the Nanosecond function, which returns the offset
65 | // within the second of the particular unix time instance, to form the
66 | // decimal part of the output
67 | // 3. Concatenate them to produce the final result
68 | seconds := strconv.FormatInt(truncatedDate.Unix(), 10)
69 | nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64)
70 |
71 | output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...)
72 |
73 | return output, nil
74 | }
75 |
76 | // UnmarshalJSON is an implementation of the json.RawMessage interface and
77 | // deserializes a [NumericDate] from a JSON representation, i.e. a
78 | // [json.Number]. This number represents an UNIX epoch with either integer or
79 | // non-integer seconds.
80 | func (date *NumericDate) UnmarshalJSON(b []byte) (err error) {
81 | var (
82 | number json.Number
83 | f float64
84 | )
85 |
86 | if err = json.Unmarshal(b, &number); err != nil {
87 | return fmt.Errorf("could not parse NumericData: %w", err)
88 | }
89 |
90 | if f, err = number.Float64(); err != nil {
91 | return fmt.Errorf("could not convert json number value to float: %w", err)
92 | }
93 |
94 | n := newNumericDateFromSeconds(f)
95 | *date = *n
96 |
97 | return nil
98 | }
99 |
100 | // ClaimStrings is basically just a slice of strings, but it can be either
101 | // serialized from a string array or just a string. This type is necessary,
102 | // since the "aud" claim can either be a single string or an array.
103 | type ClaimStrings []string
104 |
105 | func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) {
106 | var value interface{}
107 |
108 | if err = json.Unmarshal(data, &value); err != nil {
109 | return err
110 | }
111 |
112 | var aud []string
113 |
114 | switch v := value.(type) {
115 | case string:
116 | aud = append(aud, v)
117 | case []string:
118 | aud = ClaimStrings(v)
119 | case []interface{}:
120 | for _, vv := range v {
121 | vs, ok := vv.(string)
122 | if !ok {
123 | return ErrInvalidType
124 | }
125 | aud = append(aud, vs)
126 | }
127 | case nil:
128 | return nil
129 | default:
130 | return ErrInvalidType
131 | }
132 |
133 | *s = aud
134 |
135 | return
136 | }
137 |
138 | func (s ClaimStrings) MarshalJSON() (b []byte, err error) {
139 | // This handles a special case in the JWT RFC. If the string array, e.g.
140 | // used by the "aud" field, only contains one element, it MAY be serialized
141 | // as a single string. This may or may not be desired based on the ecosystem
142 | // of other JWT library used, so we make it configurable by the variable
143 | // MarshalSingleStringAsArray.
144 | if len(s) == 1 && !MarshalSingleStringAsArray {
145 | return json.Marshal(s[0])
146 | }
147 |
148 | return json.Marshal([]string(s))
149 | }
150 |
--------------------------------------------------------------------------------
/vendor/github.com/mitchellh/mapstructure/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## 1.5.0
2 |
3 | * New option `IgnoreUntaggedFields` to ignore decoding to any fields
4 | without `mapstructure` (or the configured tag name) set [GH-277]
5 | * New option `ErrorUnset` which makes it an error if any fields
6 | in a target struct are not set by the decoding process. [GH-225]
7 | * New function `OrComposeDecodeHookFunc` to help compose decode hooks. [GH-240]
8 | * Decoding to slice from array no longer crashes [GH-265]
9 | * Decode nested struct pointers to map [GH-271]
10 | * Fix issue where `,squash` was ignored if `Squash` option was set. [GH-280]
11 | * Fix issue where fields with `,omitempty` would sometimes decode
12 | into a map with an empty string key [GH-281]
13 |
14 | ## 1.4.3
15 |
16 | * Fix cases where `json.Number` didn't decode properly [GH-261]
17 |
18 | ## 1.4.2
19 |
20 | * Custom name matchers to support any sort of casing, formatting, etc. for
21 | field names. [GH-250]
22 | * Fix possible panic in ComposeDecodeHookFunc [GH-251]
23 |
24 | ## 1.4.1
25 |
26 | * Fix regression where `*time.Time` value would be set to empty and not be sent
27 | to decode hooks properly [GH-232]
28 |
29 | ## 1.4.0
30 |
31 | * A new decode hook type `DecodeHookFuncValue` has been added that has
32 | access to the full values. [GH-183]
33 | * Squash is now supported with embedded fields that are struct pointers [GH-205]
34 | * Empty strings will convert to 0 for all numeric types when weakly decoding [GH-206]
35 |
36 | ## 1.3.3
37 |
38 | * Decoding maps from maps creates a settable value for decode hooks [GH-203]
39 |
40 | ## 1.3.2
41 |
42 | * Decode into interface type with a struct value is supported [GH-187]
43 |
44 | ## 1.3.1
45 |
46 | * Squash should only squash embedded structs. [GH-194]
47 |
48 | ## 1.3.0
49 |
50 | * Added `",omitempty"` support. This will ignore zero values in the source
51 | structure when encoding. [GH-145]
52 |
53 | ## 1.2.3
54 |
55 | * Fix duplicate entries in Keys list with pointer values. [GH-185]
56 |
57 | ## 1.2.2
58 |
59 | * Do not add unsettable (unexported) values to the unused metadata key
60 | or "remain" value. [GH-150]
61 |
62 | ## 1.2.1
63 |
64 | * Go modules checksum mismatch fix
65 |
66 | ## 1.2.0
67 |
68 | * Added support to capture unused values in a field using the `",remain"` value
69 | in the mapstructure tag. There is an example to showcase usage.
70 | * Added `DecoderConfig` option to always squash embedded structs
71 | * `json.Number` can decode into `uint` types
72 | * Empty slices are preserved and not replaced with nil slices
73 | * Fix panic that can occur in when decoding a map into a nil slice of structs
74 | * Improved package documentation for godoc
75 |
76 | ## 1.1.2
77 |
78 | * Fix error when decode hook decodes interface implementation into interface
79 | type. [GH-140]
80 |
81 | ## 1.1.1
82 |
83 | * Fix panic that can happen in `decodePtr`
84 |
85 | ## 1.1.0
86 |
87 | * Added `StringToIPHookFunc` to convert `string` to `net.IP` and `net.IPNet` [GH-133]
88 | * Support struct to struct decoding [GH-137]
89 | * If source map value is nil, then destination map value is nil (instead of empty)
90 | * If source slice value is nil, then destination slice value is nil (instead of empty)
91 | * If source pointer is nil, then destination pointer is set to nil (instead of
92 | allocated zero value of type)
93 |
94 | ## 1.0.0
95 |
96 | * Initial tagged stable release.
97 |
--------------------------------------------------------------------------------
/vendor/github.com/mitchellh/mapstructure/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2013 Mitchell Hashimoto
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/vendor/github.com/mitchellh/mapstructure/README.md:
--------------------------------------------------------------------------------
1 | # mapstructure [](https://godoc.org/github.com/mitchellh/mapstructure)
2 |
3 | mapstructure is a Go library for decoding generic map values to structures
4 | and vice versa, while providing helpful error handling.
5 |
6 | This library is most useful when decoding values from some data stream (JSON,
7 | Gob, etc.) where you don't _quite_ know the structure of the underlying data
8 | until you read a part of it. You can therefore read a `map[string]interface{}`
9 | and use this library to decode it into the proper underlying native Go
10 | structure.
11 |
12 | ## Installation
13 |
14 | Standard `go get`:
15 |
16 | ```
17 | $ go get github.com/mitchellh/mapstructure
18 | ```
19 |
20 | ## Usage & Example
21 |
22 | For usage and examples see the [Godoc](http://godoc.org/github.com/mitchellh/mapstructure).
23 |
24 | The `Decode` function has examples associated with it there.
25 |
26 | ## But Why?!
27 |
28 | Go offers fantastic standard libraries for decoding formats such as JSON.
29 | The standard method is to have a struct pre-created, and populate that struct
30 | from the bytes of the encoded format. This is great, but the problem is if
31 | you have configuration or an encoding that changes slightly depending on
32 | specific fields. For example, consider this JSON:
33 |
34 | ```json
35 | {
36 | "type": "person",
37 | "name": "Mitchell"
38 | }
39 | ```
40 |
41 | Perhaps we can't populate a specific structure without first reading
42 | the "type" field from the JSON. We could always do two passes over the
43 | decoding of the JSON (reading the "type" first, and the rest later).
44 | However, it is much simpler to just decode this into a `map[string]interface{}`
45 | structure, read the "type" key, then use something like this library
46 | to decode it into the proper structure.
47 |
--------------------------------------------------------------------------------
/vendor/github.com/mitchellh/mapstructure/decode_hooks.go:
--------------------------------------------------------------------------------
1 | package mapstructure
2 |
3 | import (
4 | "encoding"
5 | "errors"
6 | "fmt"
7 | "net"
8 | "reflect"
9 | "strconv"
10 | "strings"
11 | "time"
12 | )
13 |
14 | // typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns
15 | // it into the proper DecodeHookFunc type, such as DecodeHookFuncType.
16 | func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc {
17 | // Create variables here so we can reference them with the reflect pkg
18 | var f1 DecodeHookFuncType
19 | var f2 DecodeHookFuncKind
20 | var f3 DecodeHookFuncValue
21 |
22 | // Fill in the variables into this interface and the rest is done
23 | // automatically using the reflect package.
24 | potential := []interface{}{f1, f2, f3}
25 |
26 | v := reflect.ValueOf(h)
27 | vt := v.Type()
28 | for _, raw := range potential {
29 | pt := reflect.ValueOf(raw).Type()
30 | if vt.ConvertibleTo(pt) {
31 | return v.Convert(pt).Interface()
32 | }
33 | }
34 |
35 | return nil
36 | }
37 |
38 | // DecodeHookExec executes the given decode hook. This should be used
39 | // since it'll naturally degrade to the older backwards compatible DecodeHookFunc
40 | // that took reflect.Kind instead of reflect.Type.
41 | func DecodeHookExec(
42 | raw DecodeHookFunc,
43 | from reflect.Value, to reflect.Value) (interface{}, error) {
44 |
45 | switch f := typedDecodeHook(raw).(type) {
46 | case DecodeHookFuncType:
47 | return f(from.Type(), to.Type(), from.Interface())
48 | case DecodeHookFuncKind:
49 | return f(from.Kind(), to.Kind(), from.Interface())
50 | case DecodeHookFuncValue:
51 | return f(from, to)
52 | default:
53 | return nil, errors.New("invalid decode hook signature")
54 | }
55 | }
56 |
57 | // ComposeDecodeHookFunc creates a single DecodeHookFunc that
58 | // automatically composes multiple DecodeHookFuncs.
59 | //
60 | // The composed funcs are called in order, with the result of the
61 | // previous transformation.
62 | func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
63 | return func(f reflect.Value, t reflect.Value) (interface{}, error) {
64 | var err error
65 | data := f.Interface()
66 |
67 | newFrom := f
68 | for _, f1 := range fs {
69 | data, err = DecodeHookExec(f1, newFrom, t)
70 | if err != nil {
71 | return nil, err
72 | }
73 | newFrom = reflect.ValueOf(data)
74 | }
75 |
76 | return data, nil
77 | }
78 | }
79 |
80 | // OrComposeDecodeHookFunc executes all input hook functions until one of them returns no error. In that case its value is returned.
81 | // If all hooks return an error, OrComposeDecodeHookFunc returns an error concatenating all error messages.
82 | func OrComposeDecodeHookFunc(ff ...DecodeHookFunc) DecodeHookFunc {
83 | return func(a, b reflect.Value) (interface{}, error) {
84 | var allErrs string
85 | var out interface{}
86 | var err error
87 |
88 | for _, f := range ff {
89 | out, err = DecodeHookExec(f, a, b)
90 | if err != nil {
91 | allErrs += err.Error() + "\n"
92 | continue
93 | }
94 |
95 | return out, nil
96 | }
97 |
98 | return nil, errors.New(allErrs)
99 | }
100 | }
101 |
102 | // StringToSliceHookFunc returns a DecodeHookFunc that converts
103 | // string to []string by splitting on the given sep.
104 | func StringToSliceHookFunc(sep string) DecodeHookFunc {
105 | return func(
106 | f reflect.Kind,
107 | t reflect.Kind,
108 | data interface{}) (interface{}, error) {
109 | if f != reflect.String || t != reflect.Slice {
110 | return data, nil
111 | }
112 |
113 | raw := data.(string)
114 | if raw == "" {
115 | return []string{}, nil
116 | }
117 |
118 | return strings.Split(raw, sep), nil
119 | }
120 | }
121 |
122 | // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
123 | // strings to time.Duration.
124 | func StringToTimeDurationHookFunc() DecodeHookFunc {
125 | return func(
126 | f reflect.Type,
127 | t reflect.Type,
128 | data interface{}) (interface{}, error) {
129 | if f.Kind() != reflect.String {
130 | return data, nil
131 | }
132 | if t != reflect.TypeOf(time.Duration(5)) {
133 | return data, nil
134 | }
135 |
136 | // Convert it by parsing
137 | return time.ParseDuration(data.(string))
138 | }
139 | }
140 |
141 | // StringToIPHookFunc returns a DecodeHookFunc that converts
142 | // strings to net.IP
143 | func StringToIPHookFunc() DecodeHookFunc {
144 | return func(
145 | f reflect.Type,
146 | t reflect.Type,
147 | data interface{}) (interface{}, error) {
148 | if f.Kind() != reflect.String {
149 | return data, nil
150 | }
151 | if t != reflect.TypeOf(net.IP{}) {
152 | return data, nil
153 | }
154 |
155 | // Convert it by parsing
156 | ip := net.ParseIP(data.(string))
157 | if ip == nil {
158 | return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
159 | }
160 |
161 | return ip, nil
162 | }
163 | }
164 |
165 | // StringToIPNetHookFunc returns a DecodeHookFunc that converts
166 | // strings to net.IPNet
167 | func StringToIPNetHookFunc() DecodeHookFunc {
168 | return func(
169 | f reflect.Type,
170 | t reflect.Type,
171 | data interface{}) (interface{}, error) {
172 | if f.Kind() != reflect.String {
173 | return data, nil
174 | }
175 | if t != reflect.TypeOf(net.IPNet{}) {
176 | return data, nil
177 | }
178 |
179 | // Convert it by parsing
180 | _, net, err := net.ParseCIDR(data.(string))
181 | return net, err
182 | }
183 | }
184 |
185 | // StringToTimeHookFunc returns a DecodeHookFunc that converts
186 | // strings to time.Time.
187 | func StringToTimeHookFunc(layout string) DecodeHookFunc {
188 | return func(
189 | f reflect.Type,
190 | t reflect.Type,
191 | data interface{}) (interface{}, error) {
192 | if f.Kind() != reflect.String {
193 | return data, nil
194 | }
195 | if t != reflect.TypeOf(time.Time{}) {
196 | return data, nil
197 | }
198 |
199 | // Convert it by parsing
200 | return time.Parse(layout, data.(string))
201 | }
202 | }
203 |
204 | // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to
205 | // the decoder.
206 | //
207 | // Note that this is significantly different from the WeaklyTypedInput option
208 | // of the DecoderConfig.
209 | func WeaklyTypedHook(
210 | f reflect.Kind,
211 | t reflect.Kind,
212 | data interface{}) (interface{}, error) {
213 | dataVal := reflect.ValueOf(data)
214 | switch t {
215 | case reflect.String:
216 | switch f {
217 | case reflect.Bool:
218 | if dataVal.Bool() {
219 | return "1", nil
220 | }
221 | return "0", nil
222 | case reflect.Float32:
223 | return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
224 | case reflect.Int:
225 | return strconv.FormatInt(dataVal.Int(), 10), nil
226 | case reflect.Slice:
227 | dataType := dataVal.Type()
228 | elemKind := dataType.Elem().Kind()
229 | if elemKind == reflect.Uint8 {
230 | return string(dataVal.Interface().([]uint8)), nil
231 | }
232 | case reflect.Uint:
233 | return strconv.FormatUint(dataVal.Uint(), 10), nil
234 | }
235 | }
236 |
237 | return data, nil
238 | }
239 |
240 | func RecursiveStructToMapHookFunc() DecodeHookFunc {
241 | return func(f reflect.Value, t reflect.Value) (interface{}, error) {
242 | if f.Kind() != reflect.Struct {
243 | return f.Interface(), nil
244 | }
245 |
246 | var i interface{} = struct{}{}
247 | if t.Type() != reflect.TypeOf(&i).Elem() {
248 | return f.Interface(), nil
249 | }
250 |
251 | m := make(map[string]interface{})
252 | t.Set(reflect.ValueOf(m))
253 |
254 | return f.Interface(), nil
255 | }
256 | }
257 |
258 | // TextUnmarshallerHookFunc returns a DecodeHookFunc that applies
259 | // strings to the UnmarshalText function, when the target type
260 | // implements the encoding.TextUnmarshaler interface
261 | func TextUnmarshallerHookFunc() DecodeHookFuncType {
262 | return func(
263 | f reflect.Type,
264 | t reflect.Type,
265 | data interface{}) (interface{}, error) {
266 | if f.Kind() != reflect.String {
267 | return data, nil
268 | }
269 | result := reflect.New(t).Interface()
270 | unmarshaller, ok := result.(encoding.TextUnmarshaler)
271 | if !ok {
272 | return data, nil
273 | }
274 | if err := unmarshaller.UnmarshalText([]byte(data.(string))); err != nil {
275 | return nil, err
276 | }
277 | return result, nil
278 | }
279 | }
280 |
--------------------------------------------------------------------------------
/vendor/github.com/mitchellh/mapstructure/error.go:
--------------------------------------------------------------------------------
1 | package mapstructure
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "sort"
7 | "strings"
8 | )
9 |
10 | // Error implements the error interface and can represents multiple
11 | // errors that occur in the course of a single decode.
12 | type Error struct {
13 | Errors []string
14 | }
15 |
16 | func (e *Error) Error() string {
17 | points := make([]string, len(e.Errors))
18 | for i, err := range e.Errors {
19 | points[i] = fmt.Sprintf("* %s", err)
20 | }
21 |
22 | sort.Strings(points)
23 | return fmt.Sprintf(
24 | "%d error(s) decoding:\n\n%s",
25 | len(e.Errors), strings.Join(points, "\n"))
26 | }
27 |
28 | // WrappedErrors implements the errwrap.Wrapper interface to make this
29 | // return value more useful with the errwrap and go-multierror libraries.
30 | func (e *Error) WrappedErrors() []error {
31 | if e == nil {
32 | return nil
33 | }
34 |
35 | result := make([]error, len(e.Errors))
36 | for i, e := range e.Errors {
37 | result[i] = errors.New(e)
38 | }
39 |
40 | return result
41 | }
42 |
43 | func appendErrors(errors []string, err error) []string {
44 | switch e := err.(type) {
45 | case *Error:
46 | return append(errors, e.Errors...)
47 | default:
48 | return append(errors, e.Error())
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/vendor/golang.org/x/crypto/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright 2009 The Go Authors.
2 |
3 | Redistribution and use in source and binary forms, with or without
4 | modification, are permitted provided that the following conditions are
5 | met:
6 |
7 | * Redistributions of source code must retain the above copyright
8 | notice, this list of conditions and the following disclaimer.
9 | * Redistributions in binary form must reproduce the above
10 | copyright notice, this list of conditions and the following disclaimer
11 | in the documentation and/or other materials provided with the
12 | distribution.
13 | * Neither the name of Google LLC nor the names of its
14 | contributors may be used to endorse or promote products derived from
15 | this software without specific prior written permission.
16 |
17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 |
--------------------------------------------------------------------------------
/vendor/golang.org/x/crypto/PATENTS:
--------------------------------------------------------------------------------
1 | Additional IP Rights Grant (Patents)
2 |
3 | "This implementation" means the copyrightable works distributed by
4 | Google as part of the Go project.
5 |
6 | Google hereby grants to You a perpetual, worldwide, non-exclusive,
7 | no-charge, royalty-free, irrevocable (except as stated in this section)
8 | patent license to make, have made, use, offer to sell, sell, import,
9 | transfer and otherwise run, modify and propagate the contents of this
10 | implementation of Go, where such license applies only to those patent
11 | claims, both currently owned or controlled by Google and acquired in
12 | the future, licensable by Google that are necessarily infringed by this
13 | implementation of Go. This grant does not include claims that would be
14 | infringed only as a consequence of further modification of this
15 | implementation. If you or your agent or exclusive licensee institute or
16 | order or agree to the institution of patent litigation against any
17 | entity (including a cross-claim or counterclaim in a lawsuit) alleging
18 | that this implementation of Go or any code incorporated within this
19 | implementation of Go constitutes direct or contributory patent
20 | infringement, or inducement of patent infringement, then any patent
21 | rights granted to you under this License for this implementation of Go
22 | shall terminate as of the date such litigation is filed.
23 |
--------------------------------------------------------------------------------
/vendor/golang.org/x/crypto/pbkdf2/pbkdf2.go:
--------------------------------------------------------------------------------
1 | // Copyright 2012 The Go Authors. All rights reserved.
2 | // Use of this source code is governed by a BSD-style
3 | // license that can be found in the LICENSE file.
4 |
5 | /*
6 | Package pbkdf2 implements the key derivation function PBKDF2 as defined in RFC
7 | 2898 / PKCS #5 v2.0.
8 |
9 | A key derivation function is useful when encrypting data based on a password
10 | or any other not-fully-random data. It uses a pseudorandom function to derive
11 | a secure encryption key based on the password.
12 |
13 | While v2.0 of the standard defines only one pseudorandom function to use,
14 | HMAC-SHA1, the drafted v2.1 specification allows use of all five FIPS Approved
15 | Hash Functions SHA-1, SHA-224, SHA-256, SHA-384 and SHA-512 for HMAC. To
16 | choose, you can pass the `New` functions from the different SHA packages to
17 | pbkdf2.Key.
18 | */
19 | package pbkdf2
20 |
21 | import (
22 | "crypto/hmac"
23 | "hash"
24 | )
25 |
26 | // Key derives a key from the password, salt and iteration count, returning a
27 | // []byte of length keylen that can be used as cryptographic key. The key is
28 | // derived based on the method described as PBKDF2 with the HMAC variant using
29 | // the supplied hash function.
30 | //
31 | // For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you
32 | // can get a derived key for e.g. AES-256 (which needs a 32-byte key) by
33 | // doing:
34 | //
35 | // dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New)
36 | //
37 | // Remember to get a good random salt. At least 8 bytes is recommended by the
38 | // RFC.
39 | //
40 | // Using a higher iteration count will increase the cost of an exhaustive
41 | // search but will also make derivation proportionally slower.
42 | func Key(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
43 | prf := hmac.New(h, password)
44 | hashLen := prf.Size()
45 | numBlocks := (keyLen + hashLen - 1) / hashLen
46 |
47 | var buf [4]byte
48 | dk := make([]byte, 0, numBlocks*hashLen)
49 | U := make([]byte, hashLen)
50 | for block := 1; block <= numBlocks; block++ {
51 | // N.B.: || means concatenation, ^ means XOR
52 | // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
53 | // U_1 = PRF(password, salt || uint(i))
54 | prf.Reset()
55 | prf.Write(salt)
56 | buf[0] = byte(block >> 24)
57 | buf[1] = byte(block >> 16)
58 | buf[2] = byte(block >> 8)
59 | buf[3] = byte(block)
60 | prf.Write(buf[:4])
61 | dk = prf.Sum(dk)
62 | T := dk[len(dk)-hashLen:]
63 | copy(U, T)
64 |
65 | // U_n = PRF(password, U_(n-1))
66 | for n := 2; n <= iter; n++ {
67 | prf.Reset()
68 | prf.Write(U)
69 | U = U[:0]
70 | U = prf.Sum(U)
71 | for x := range U {
72 | T[x] ^= U[x]
73 | }
74 | }
75 | }
76 | return dk[:keyLen]
77 | }
78 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | This project is covered by two different licenses: MIT and Apache.
3 |
4 | #### MIT License ####
5 |
6 | The following files were ported to Go from C files of libyaml, and thus
7 | are still covered by their original MIT license, with the additional
8 | copyright staring in 2011 when the project was ported over:
9 |
10 | apic.go emitterc.go parserc.go readerc.go scannerc.go
11 | writerc.go yamlh.go yamlprivateh.go
12 |
13 | Copyright (c) 2006-2010 Kirill Simonov
14 | Copyright (c) 2006-2011 Kirill Simonov
15 |
16 | Permission is hereby granted, free of charge, to any person obtaining a copy of
17 | this software and associated documentation files (the "Software"), to deal in
18 | the Software without restriction, including without limitation the rights to
19 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
20 | of the Software, and to permit persons to whom the Software is furnished to do
21 | so, subject to the following conditions:
22 |
23 | The above copyright notice and this permission notice shall be included in all
24 | copies or substantial portions of the Software.
25 |
26 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32 | SOFTWARE.
33 |
34 | ### Apache License ###
35 |
36 | All the remaining project files are covered by the Apache license:
37 |
38 | Copyright (c) 2011-2019 Canonical Ltd
39 |
40 | Licensed under the Apache License, Version 2.0 (the "License");
41 | you may not use this file except in compliance with the License.
42 | You may obtain a copy of the License at
43 |
44 | http://www.apache.org/licenses/LICENSE-2.0
45 |
46 | Unless required by applicable law or agreed to in writing, software
47 | distributed under the License is distributed on an "AS IS" BASIS,
48 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
49 | See the License for the specific language governing permissions and
50 | limitations under the License.
51 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright 2011-2016 Canonical Ltd.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/README.md:
--------------------------------------------------------------------------------
1 | # YAML support for the Go language
2 |
3 | Introduction
4 | ------------
5 |
6 | The yaml package enables Go programs to comfortably encode and decode YAML
7 | values. It was developed within [Canonical](https://www.canonical.com) as
8 | part of the [juju](https://juju.ubuntu.com) project, and is based on a
9 | pure Go port of the well-known [libyaml](http://pyyaml.org/wiki/LibYAML)
10 | C library to parse and generate YAML data quickly and reliably.
11 |
12 | Compatibility
13 | -------------
14 |
15 | The yaml package supports most of YAML 1.2, but preserves some behavior
16 | from 1.1 for backwards compatibility.
17 |
18 | Specifically, as of v3 of the yaml package:
19 |
20 | - YAML 1.1 bools (_yes/no, on/off_) are supported as long as they are being
21 | decoded into a typed bool value. Otherwise they behave as a string. Booleans
22 | in YAML 1.2 are _true/false_ only.
23 | - Octals encode and decode as _0777_ per YAML 1.1, rather than _0o777_
24 | as specified in YAML 1.2, because most parsers still use the old format.
25 | Octals in the _0o777_ format are supported though, so new files work.
26 | - Does not support base-60 floats. These are gone from YAML 1.2, and were
27 | actually never supported by this package as it's clearly a poor choice.
28 |
29 | and offers backwards
30 | compatibility with YAML 1.1 in some cases.
31 | 1.2, including support for
32 | anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
33 | implemented, and base-60 floats from YAML 1.1 are purposefully not
34 | supported since they're a poor design and are gone in YAML 1.2.
35 |
36 | Installation and usage
37 | ----------------------
38 |
39 | The import path for the package is *gopkg.in/yaml.v3*.
40 |
41 | To install it, run:
42 |
43 | go get gopkg.in/yaml.v3
44 |
45 | API documentation
46 | -----------------
47 |
48 | If opened in a browser, the import path itself leads to the API documentation:
49 |
50 | - [https://gopkg.in/yaml.v3](https://gopkg.in/yaml.v3)
51 |
52 | API stability
53 | -------------
54 |
55 | The package API for yaml v3 will remain stable as described in [gopkg.in](https://gopkg.in).
56 |
57 |
58 | License
59 | -------
60 |
61 | The yaml package is licensed under the MIT and Apache License 2.0 licenses.
62 | Please see the LICENSE file for details.
63 |
64 |
65 | Example
66 | -------
67 |
68 | ```Go
69 | package main
70 |
71 | import (
72 | "fmt"
73 | "log"
74 |
75 | "gopkg.in/yaml.v3"
76 | )
77 |
78 | var data = `
79 | a: Easy!
80 | b:
81 | c: 2
82 | d: [3, 4]
83 | `
84 |
85 | // Note: struct fields must be public in order for unmarshal to
86 | // correctly populate the data.
87 | type T struct {
88 | A string
89 | B struct {
90 | RenamedC int `yaml:"c"`
91 | D []int `yaml:",flow"`
92 | }
93 | }
94 |
95 | func main() {
96 | t := T{}
97 |
98 | err := yaml.Unmarshal([]byte(data), &t)
99 | if err != nil {
100 | log.Fatalf("error: %v", err)
101 | }
102 | fmt.Printf("--- t:\n%v\n\n", t)
103 |
104 | d, err := yaml.Marshal(&t)
105 | if err != nil {
106 | log.Fatalf("error: %v", err)
107 | }
108 | fmt.Printf("--- t dump:\n%s\n\n", string(d))
109 |
110 | m := make(map[interface{}]interface{})
111 |
112 | err = yaml.Unmarshal([]byte(data), &m)
113 | if err != nil {
114 | log.Fatalf("error: %v", err)
115 | }
116 | fmt.Printf("--- m:\n%v\n\n", m)
117 |
118 | d, err = yaml.Marshal(&m)
119 | if err != nil {
120 | log.Fatalf("error: %v", err)
121 | }
122 | fmt.Printf("--- m dump:\n%s\n\n", string(d))
123 | }
124 | ```
125 |
126 | This example will generate the following output:
127 |
128 | ```
129 | --- t:
130 | {Easy! {2 [3 4]}}
131 |
132 | --- t dump:
133 | a: Easy!
134 | b:
135 | c: 2
136 | d: [3, 4]
137 |
138 |
139 | --- m:
140 | map[a:Easy! b:map[c:2 d:[3 4]]]
141 |
142 | --- m dump:
143 | a: Easy!
144 | b:
145 | c: 2
146 | d:
147 | - 3
148 | - 4
149 | ```
150 |
151 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/resolve.go:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) 2011-2019 Canonical Ltd
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 |
16 | package yaml
17 |
18 | import (
19 | "encoding/base64"
20 | "math"
21 | "regexp"
22 | "strconv"
23 | "strings"
24 | "time"
25 | )
26 |
27 | type resolveMapItem struct {
28 | value interface{}
29 | tag string
30 | }
31 |
32 | var resolveTable = make([]byte, 256)
33 | var resolveMap = make(map[string]resolveMapItem)
34 |
35 | func init() {
36 | t := resolveTable
37 | t[int('+')] = 'S' // Sign
38 | t[int('-')] = 'S'
39 | for _, c := range "0123456789" {
40 | t[int(c)] = 'D' // Digit
41 | }
42 | for _, c := range "yYnNtTfFoO~" {
43 | t[int(c)] = 'M' // In map
44 | }
45 | t[int('.')] = '.' // Float (potentially in map)
46 |
47 | var resolveMapList = []struct {
48 | v interface{}
49 | tag string
50 | l []string
51 | }{
52 | {true, boolTag, []string{"true", "True", "TRUE"}},
53 | {false, boolTag, []string{"false", "False", "FALSE"}},
54 | {nil, nullTag, []string{"", "~", "null", "Null", "NULL"}},
55 | {math.NaN(), floatTag, []string{".nan", ".NaN", ".NAN"}},
56 | {math.Inf(+1), floatTag, []string{".inf", ".Inf", ".INF"}},
57 | {math.Inf(+1), floatTag, []string{"+.inf", "+.Inf", "+.INF"}},
58 | {math.Inf(-1), floatTag, []string{"-.inf", "-.Inf", "-.INF"}},
59 | {"<<", mergeTag, []string{"<<"}},
60 | }
61 |
62 | m := resolveMap
63 | for _, item := range resolveMapList {
64 | for _, s := range item.l {
65 | m[s] = resolveMapItem{item.v, item.tag}
66 | }
67 | }
68 | }
69 |
70 | const (
71 | nullTag = "!!null"
72 | boolTag = "!!bool"
73 | strTag = "!!str"
74 | intTag = "!!int"
75 | floatTag = "!!float"
76 | timestampTag = "!!timestamp"
77 | seqTag = "!!seq"
78 | mapTag = "!!map"
79 | binaryTag = "!!binary"
80 | mergeTag = "!!merge"
81 | )
82 |
83 | var longTags = make(map[string]string)
84 | var shortTags = make(map[string]string)
85 |
86 | func init() {
87 | for _, stag := range []string{nullTag, boolTag, strTag, intTag, floatTag, timestampTag, seqTag, mapTag, binaryTag, mergeTag} {
88 | ltag := longTag(stag)
89 | longTags[stag] = ltag
90 | shortTags[ltag] = stag
91 | }
92 | }
93 |
94 | const longTagPrefix = "tag:yaml.org,2002:"
95 |
96 | func shortTag(tag string) string {
97 | if strings.HasPrefix(tag, longTagPrefix) {
98 | if stag, ok := shortTags[tag]; ok {
99 | return stag
100 | }
101 | return "!!" + tag[len(longTagPrefix):]
102 | }
103 | return tag
104 | }
105 |
106 | func longTag(tag string) string {
107 | if strings.HasPrefix(tag, "!!") {
108 | if ltag, ok := longTags[tag]; ok {
109 | return ltag
110 | }
111 | return longTagPrefix + tag[2:]
112 | }
113 | return tag
114 | }
115 |
116 | func resolvableTag(tag string) bool {
117 | switch tag {
118 | case "", strTag, boolTag, intTag, floatTag, nullTag, timestampTag:
119 | return true
120 | }
121 | return false
122 | }
123 |
124 | var yamlStyleFloat = regexp.MustCompile(`^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$`)
125 |
126 | func resolve(tag string, in string) (rtag string, out interface{}) {
127 | tag = shortTag(tag)
128 | if !resolvableTag(tag) {
129 | return tag, in
130 | }
131 |
132 | defer func() {
133 | switch tag {
134 | case "", rtag, strTag, binaryTag:
135 | return
136 | case floatTag:
137 | if rtag == intTag {
138 | switch v := out.(type) {
139 | case int64:
140 | rtag = floatTag
141 | out = float64(v)
142 | return
143 | case int:
144 | rtag = floatTag
145 | out = float64(v)
146 | return
147 | }
148 | }
149 | }
150 | failf("cannot decode %s `%s` as a %s", shortTag(rtag), in, shortTag(tag))
151 | }()
152 |
153 | // Any data is accepted as a !!str or !!binary.
154 | // Otherwise, the prefix is enough of a hint about what it might be.
155 | hint := byte('N')
156 | if in != "" {
157 | hint = resolveTable[in[0]]
158 | }
159 | if hint != 0 && tag != strTag && tag != binaryTag {
160 | // Handle things we can lookup in a map.
161 | if item, ok := resolveMap[in]; ok {
162 | return item.tag, item.value
163 | }
164 |
165 | // Base 60 floats are a bad idea, were dropped in YAML 1.2, and
166 | // are purposefully unsupported here. They're still quoted on
167 | // the way out for compatibility with other parser, though.
168 |
169 | switch hint {
170 | case 'M':
171 | // We've already checked the map above.
172 |
173 | case '.':
174 | // Not in the map, so maybe a normal float.
175 | floatv, err := strconv.ParseFloat(in, 64)
176 | if err == nil {
177 | return floatTag, floatv
178 | }
179 |
180 | case 'D', 'S':
181 | // Int, float, or timestamp.
182 | // Only try values as a timestamp if the value is unquoted or there's an explicit
183 | // !!timestamp tag.
184 | if tag == "" || tag == timestampTag {
185 | t, ok := parseTimestamp(in)
186 | if ok {
187 | return timestampTag, t
188 | }
189 | }
190 |
191 | plain := strings.Replace(in, "_", "", -1)
192 | intv, err := strconv.ParseInt(plain, 0, 64)
193 | if err == nil {
194 | if intv == int64(int(intv)) {
195 | return intTag, int(intv)
196 | } else {
197 | return intTag, intv
198 | }
199 | }
200 | uintv, err := strconv.ParseUint(plain, 0, 64)
201 | if err == nil {
202 | return intTag, uintv
203 | }
204 | if yamlStyleFloat.MatchString(plain) {
205 | floatv, err := strconv.ParseFloat(plain, 64)
206 | if err == nil {
207 | return floatTag, floatv
208 | }
209 | }
210 | if strings.HasPrefix(plain, "0b") {
211 | intv, err := strconv.ParseInt(plain[2:], 2, 64)
212 | if err == nil {
213 | if intv == int64(int(intv)) {
214 | return intTag, int(intv)
215 | } else {
216 | return intTag, intv
217 | }
218 | }
219 | uintv, err := strconv.ParseUint(plain[2:], 2, 64)
220 | if err == nil {
221 | return intTag, uintv
222 | }
223 | } else if strings.HasPrefix(plain, "-0b") {
224 | intv, err := strconv.ParseInt("-"+plain[3:], 2, 64)
225 | if err == nil {
226 | if true || intv == int64(int(intv)) {
227 | return intTag, int(intv)
228 | } else {
229 | return intTag, intv
230 | }
231 | }
232 | }
233 | // Octals as introduced in version 1.2 of the spec.
234 | // Octals from the 1.1 spec, spelled as 0777, are still
235 | // decoded by default in v3 as well for compatibility.
236 | // May be dropped in v4 depending on how usage evolves.
237 | if strings.HasPrefix(plain, "0o") {
238 | intv, err := strconv.ParseInt(plain[2:], 8, 64)
239 | if err == nil {
240 | if intv == int64(int(intv)) {
241 | return intTag, int(intv)
242 | } else {
243 | return intTag, intv
244 | }
245 | }
246 | uintv, err := strconv.ParseUint(plain[2:], 8, 64)
247 | if err == nil {
248 | return intTag, uintv
249 | }
250 | } else if strings.HasPrefix(plain, "-0o") {
251 | intv, err := strconv.ParseInt("-"+plain[3:], 8, 64)
252 | if err == nil {
253 | if true || intv == int64(int(intv)) {
254 | return intTag, int(intv)
255 | } else {
256 | return intTag, intv
257 | }
258 | }
259 | }
260 | default:
261 | panic("internal error: missing handler for resolver table: " + string(rune(hint)) + " (with " + in + ")")
262 | }
263 | }
264 | return strTag, in
265 | }
266 |
267 | // encodeBase64 encodes s as base64 that is broken up into multiple lines
268 | // as appropriate for the resulting length.
269 | func encodeBase64(s string) string {
270 | const lineLen = 70
271 | encLen := base64.StdEncoding.EncodedLen(len(s))
272 | lines := encLen/lineLen + 1
273 | buf := make([]byte, encLen*2+lines)
274 | in := buf[0:encLen]
275 | out := buf[encLen:]
276 | base64.StdEncoding.Encode(in, []byte(s))
277 | k := 0
278 | for i := 0; i < len(in); i += lineLen {
279 | j := i + lineLen
280 | if j > len(in) {
281 | j = len(in)
282 | }
283 | k += copy(out[k:], in[i:j])
284 | if lines > 1 {
285 | out[k] = '\n'
286 | k++
287 | }
288 | }
289 | return string(out[:k])
290 | }
291 |
292 | // This is a subset of the formats allowed by the regular expression
293 | // defined at http://yaml.org/type/timestamp.html.
294 | var allowedTimestampFormats = []string{
295 | "2006-1-2T15:4:5.999999999Z07:00", // RCF3339Nano with short date fields.
296 | "2006-1-2t15:4:5.999999999Z07:00", // RFC3339Nano with short date fields and lower-case "t".
297 | "2006-1-2 15:4:5.999999999", // space separated with no time zone
298 | "2006-1-2", // date only
299 | // Notable exception: time.Parse cannot handle: "2001-12-14 21:59:43.10 -5"
300 | // from the set of examples.
301 | }
302 |
303 | // parseTimestamp parses s as a timestamp string and
304 | // returns the timestamp and reports whether it succeeded.
305 | // Timestamp formats are defined at http://yaml.org/type/timestamp.html
306 | func parseTimestamp(s string) (time.Time, bool) {
307 | // TODO write code to check all the formats supported by
308 | // http://yaml.org/type/timestamp.html instead of using time.Parse.
309 |
310 | // Quick check: all date formats start with YYYY-.
311 | i := 0
312 | for ; i < len(s); i++ {
313 | if c := s[i]; c < '0' || c > '9' {
314 | break
315 | }
316 | }
317 | if i != 4 || i == len(s) || s[i] != '-' {
318 | return time.Time{}, false
319 | }
320 | for _, format := range allowedTimestampFormats {
321 | if t, err := time.Parse(format, s); err == nil {
322 | return t, true
323 | }
324 | }
325 | return time.Time{}, false
326 | }
327 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/sorter.go:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) 2011-2019 Canonical Ltd
3 | //
4 | // Licensed under the Apache License, Version 2.0 (the "License");
5 | // you may not use this file except in compliance with the License.
6 | // You may obtain a copy of the License at
7 | //
8 | // http://www.apache.org/licenses/LICENSE-2.0
9 | //
10 | // Unless required by applicable law or agreed to in writing, software
11 | // distributed under the License is distributed on an "AS IS" BASIS,
12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | // See the License for the specific language governing permissions and
14 | // limitations under the License.
15 |
16 | package yaml
17 |
18 | import (
19 | "reflect"
20 | "unicode"
21 | )
22 |
23 | type keyList []reflect.Value
24 |
25 | func (l keyList) Len() int { return len(l) }
26 | func (l keyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
27 | func (l keyList) Less(i, j int) bool {
28 | a := l[i]
29 | b := l[j]
30 | ak := a.Kind()
31 | bk := b.Kind()
32 | for (ak == reflect.Interface || ak == reflect.Ptr) && !a.IsNil() {
33 | a = a.Elem()
34 | ak = a.Kind()
35 | }
36 | for (bk == reflect.Interface || bk == reflect.Ptr) && !b.IsNil() {
37 | b = b.Elem()
38 | bk = b.Kind()
39 | }
40 | af, aok := keyFloat(a)
41 | bf, bok := keyFloat(b)
42 | if aok && bok {
43 | if af != bf {
44 | return af < bf
45 | }
46 | if ak != bk {
47 | return ak < bk
48 | }
49 | return numLess(a, b)
50 | }
51 | if ak != reflect.String || bk != reflect.String {
52 | return ak < bk
53 | }
54 | ar, br := []rune(a.String()), []rune(b.String())
55 | digits := false
56 | for i := 0; i < len(ar) && i < len(br); i++ {
57 | if ar[i] == br[i] {
58 | digits = unicode.IsDigit(ar[i])
59 | continue
60 | }
61 | al := unicode.IsLetter(ar[i])
62 | bl := unicode.IsLetter(br[i])
63 | if al && bl {
64 | return ar[i] < br[i]
65 | }
66 | if al || bl {
67 | if digits {
68 | return al
69 | } else {
70 | return bl
71 | }
72 | }
73 | var ai, bi int
74 | var an, bn int64
75 | if ar[i] == '0' || br[i] == '0' {
76 | for j := i - 1; j >= 0 && unicode.IsDigit(ar[j]); j-- {
77 | if ar[j] != '0' {
78 | an = 1
79 | bn = 1
80 | break
81 | }
82 | }
83 | }
84 | for ai = i; ai < len(ar) && unicode.IsDigit(ar[ai]); ai++ {
85 | an = an*10 + int64(ar[ai]-'0')
86 | }
87 | for bi = i; bi < len(br) && unicode.IsDigit(br[bi]); bi++ {
88 | bn = bn*10 + int64(br[bi]-'0')
89 | }
90 | if an != bn {
91 | return an < bn
92 | }
93 | if ai != bi {
94 | return ai < bi
95 | }
96 | return ar[i] < br[i]
97 | }
98 | return len(ar) < len(br)
99 | }
100 |
101 | // keyFloat returns a float value for v if it is a number/bool
102 | // and whether it is a number/bool or not.
103 | func keyFloat(v reflect.Value) (f float64, ok bool) {
104 | switch v.Kind() {
105 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
106 | return float64(v.Int()), true
107 | case reflect.Float32, reflect.Float64:
108 | return v.Float(), true
109 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
110 | return float64(v.Uint()), true
111 | case reflect.Bool:
112 | if v.Bool() {
113 | return 1, true
114 | }
115 | return 0, true
116 | }
117 | return 0, false
118 | }
119 |
120 | // numLess returns whether a < b.
121 | // a and b must necessarily have the same kind.
122 | func numLess(a, b reflect.Value) bool {
123 | switch a.Kind() {
124 | case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
125 | return a.Int() < b.Int()
126 | case reflect.Float32, reflect.Float64:
127 | return a.Float() < b.Float()
128 | case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
129 | return a.Uint() < b.Uint()
130 | case reflect.Bool:
131 | return !a.Bool() && b.Bool()
132 | }
133 | panic("not a number")
134 | }
135 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/writerc.go:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) 2011-2019 Canonical Ltd
3 | // Copyright (c) 2006-2010 Kirill Simonov
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | // this software and associated documentation files (the "Software"), to deal in
7 | // the Software without restriction, including without limitation the rights to
8 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 | // of the Software, and to permit persons to whom the Software is furnished to do
10 | // so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in all
13 | // copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | // SOFTWARE.
22 |
23 | package yaml
24 |
25 | // Set the writer error and return false.
26 | func yaml_emitter_set_writer_error(emitter *yaml_emitter_t, problem string) bool {
27 | emitter.error = yaml_WRITER_ERROR
28 | emitter.problem = problem
29 | return false
30 | }
31 |
32 | // Flush the output buffer.
33 | func yaml_emitter_flush(emitter *yaml_emitter_t) bool {
34 | if emitter.write_handler == nil {
35 | panic("write handler not set")
36 | }
37 |
38 | // Check if the buffer is empty.
39 | if emitter.buffer_pos == 0 {
40 | return true
41 | }
42 |
43 | if err := emitter.write_handler(emitter, emitter.buffer[:emitter.buffer_pos]); err != nil {
44 | return yaml_emitter_set_writer_error(emitter, "write error: "+err.Error())
45 | }
46 | emitter.buffer_pos = 0
47 | return true
48 | }
49 |
--------------------------------------------------------------------------------
/vendor/gopkg.in/yaml.v3/yamlprivateh.go:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) 2011-2019 Canonical Ltd
3 | // Copyright (c) 2006-2010 Kirill Simonov
4 | //
5 | // Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | // this software and associated documentation files (the "Software"), to deal in
7 | // the Software without restriction, including without limitation the rights to
8 | // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 | // of the Software, and to permit persons to whom the Software is furnished to do
10 | // so, subject to the following conditions:
11 | //
12 | // The above copyright notice and this permission notice shall be included in all
13 | // copies or substantial portions of the Software.
14 | //
15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | // SOFTWARE.
22 |
23 | package yaml
24 |
25 | const (
26 | // The size of the input raw buffer.
27 | input_raw_buffer_size = 512
28 |
29 | // The size of the input buffer.
30 | // It should be possible to decode the whole raw buffer.
31 | input_buffer_size = input_raw_buffer_size * 3
32 |
33 | // The size of the output buffer.
34 | output_buffer_size = 128
35 |
36 | // The size of the output raw buffer.
37 | // It should be possible to encode the whole output buffer.
38 | output_raw_buffer_size = (output_buffer_size*2 + 2)
39 |
40 | // The size of other stacks and queues.
41 | initial_stack_size = 16
42 | initial_queue_size = 16
43 | initial_string_size = 16
44 | )
45 |
46 | // Check if the character at the specified position is an alphabetical
47 | // character, a digit, '_', or '-'.
48 | func is_alpha(b []byte, i int) bool {
49 | return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'Z' || b[i] >= 'a' && b[i] <= 'z' || b[i] == '_' || b[i] == '-'
50 | }
51 |
52 | // Check if the character at the specified position is a digit.
53 | func is_digit(b []byte, i int) bool {
54 | return b[i] >= '0' && b[i] <= '9'
55 | }
56 |
57 | // Get the value of a digit.
58 | func as_digit(b []byte, i int) int {
59 | return int(b[i]) - '0'
60 | }
61 |
62 | // Check if the character at the specified position is a hex-digit.
63 | func is_hex(b []byte, i int) bool {
64 | return b[i] >= '0' && b[i] <= '9' || b[i] >= 'A' && b[i] <= 'F' || b[i] >= 'a' && b[i] <= 'f'
65 | }
66 |
67 | // Get the value of a hex-digit.
68 | func as_hex(b []byte, i int) int {
69 | bi := b[i]
70 | if bi >= 'A' && bi <= 'F' {
71 | return int(bi) - 'A' + 10
72 | }
73 | if bi >= 'a' && bi <= 'f' {
74 | return int(bi) - 'a' + 10
75 | }
76 | return int(bi) - '0'
77 | }
78 |
79 | // Check if the character is ASCII.
80 | func is_ascii(b []byte, i int) bool {
81 | return b[i] <= 0x7F
82 | }
83 |
84 | // Check if the character at the start of the buffer can be printed unescaped.
85 | func is_printable(b []byte, i int) bool {
86 | return ((b[i] == 0x0A) || // . == #x0A
87 | (b[i] >= 0x20 && b[i] <= 0x7E) || // #x20 <= . <= #x7E
88 | (b[i] == 0xC2 && b[i+1] >= 0xA0) || // #0xA0 <= . <= #xD7FF
89 | (b[i] > 0xC2 && b[i] < 0xED) ||
90 | (b[i] == 0xED && b[i+1] < 0xA0) ||
91 | (b[i] == 0xEE) ||
92 | (b[i] == 0xEF && // #xE000 <= . <= #xFFFD
93 | !(b[i+1] == 0xBB && b[i+2] == 0xBF) && // && . != #xFEFF
94 | !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF))))
95 | }
96 |
97 | // Check if the character at the specified position is NUL.
98 | func is_z(b []byte, i int) bool {
99 | return b[i] == 0x00
100 | }
101 |
102 | // Check if the beginning of the buffer is a BOM.
103 | func is_bom(b []byte, i int) bool {
104 | return b[0] == 0xEF && b[1] == 0xBB && b[2] == 0xBF
105 | }
106 |
107 | // Check if the character at the specified position is space.
108 | func is_space(b []byte, i int) bool {
109 | return b[i] == ' '
110 | }
111 |
112 | // Check if the character at the specified position is tab.
113 | func is_tab(b []byte, i int) bool {
114 | return b[i] == '\t'
115 | }
116 |
117 | // Check if the character at the specified position is blank (space or tab).
118 | func is_blank(b []byte, i int) bool {
119 | //return is_space(b, i) || is_tab(b, i)
120 | return b[i] == ' ' || b[i] == '\t'
121 | }
122 |
123 | // Check if the character at the specified position is a line break.
124 | func is_break(b []byte, i int) bool {
125 | return (b[i] == '\r' || // CR (#xD)
126 | b[i] == '\n' || // LF (#xA)
127 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
128 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
129 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9) // PS (#x2029)
130 | }
131 |
132 | func is_crlf(b []byte, i int) bool {
133 | return b[i] == '\r' && b[i+1] == '\n'
134 | }
135 |
136 | // Check if the character is a line break or NUL.
137 | func is_breakz(b []byte, i int) bool {
138 | //return is_break(b, i) || is_z(b, i)
139 | return (
140 | // is_break:
141 | b[i] == '\r' || // CR (#xD)
142 | b[i] == '\n' || // LF (#xA)
143 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
144 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
145 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
146 | // is_z:
147 | b[i] == 0)
148 | }
149 |
150 | // Check if the character is a line break, space, or NUL.
151 | func is_spacez(b []byte, i int) bool {
152 | //return is_space(b, i) || is_breakz(b, i)
153 | return (
154 | // is_space:
155 | b[i] == ' ' ||
156 | // is_breakz:
157 | b[i] == '\r' || // CR (#xD)
158 | b[i] == '\n' || // LF (#xA)
159 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
160 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
161 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
162 | b[i] == 0)
163 | }
164 |
165 | // Check if the character is a line break, space, tab, or NUL.
166 | func is_blankz(b []byte, i int) bool {
167 | //return is_blank(b, i) || is_breakz(b, i)
168 | return (
169 | // is_blank:
170 | b[i] == ' ' || b[i] == '\t' ||
171 | // is_breakz:
172 | b[i] == '\r' || // CR (#xD)
173 | b[i] == '\n' || // LF (#xA)
174 | b[i] == 0xC2 && b[i+1] == 0x85 || // NEL (#x85)
175 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA8 || // LS (#x2028)
176 | b[i] == 0xE2 && b[i+1] == 0x80 && b[i+2] == 0xA9 || // PS (#x2029)
177 | b[i] == 0)
178 | }
179 |
180 | // Determine the width of the character.
181 | func width(b byte) int {
182 | // Don't replace these by a switch without first
183 | // confirming that it is being inlined.
184 | if b&0x80 == 0x00 {
185 | return 1
186 | }
187 | if b&0xE0 == 0xC0 {
188 | return 2
189 | }
190 | if b&0xF0 == 0xE0 {
191 | return 3
192 | }
193 | if b&0xF8 == 0xF0 {
194 | return 4
195 | }
196 | return 0
197 |
198 | }
199 |
--------------------------------------------------------------------------------
/vendor/modules.txt:
--------------------------------------------------------------------------------
1 | # github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964
2 | ## explicit
3 | github.com/danwakefield/fnmatch
4 | # github.com/go-jose/go-jose/v3 v3.0.4
5 | ## explicit; go 1.12
6 | github.com/go-jose/go-jose/v3
7 | github.com/go-jose/go-jose/v3/cipher
8 | github.com/go-jose/go-jose/v3/json
9 | # github.com/golang-jwt/jwt/v5 v5.2.2
10 | ## explicit; go 1.18
11 | github.com/golang-jwt/jwt/v5
12 | # github.com/mitchellh/mapstructure v1.5.0
13 | ## explicit; go 1.14
14 | github.com/mitchellh/mapstructure
15 | # golang.org/x/crypto v0.35.0
16 | ## explicit; go 1.23.0
17 | golang.org/x/crypto/pbkdf2
18 | # gopkg.in/yaml.v3 v3.0.1
19 | ## explicit
20 | gopkg.in/yaml.v3
21 |
--------------------------------------------------------------------------------