├── .go-version ├── .github ├── CODEOWNERS ├── workflows │ ├── action-test.yml │ └── main.yml └── dependabot.yml ├── vendor ├── github.com │ └── golang-jwt │ │ └── jwt │ │ └── v5 │ │ ├── .gitignore │ │ ├── staticcheck.conf │ │ ├── doc.go │ │ ├── token_option.go │ │ ├── claims.go │ │ ├── SECURITY.md │ │ ├── LICENSE │ │ ├── ed25519_utils.go │ │ ├── signing_method.go │ │ ├── none.go │ │ ├── ecdsa_utils.go │ │ ├── ed25519.go │ │ ├── registered_claims.go │ │ ├── rsa.go │ │ ├── errors.go │ │ ├── map_claims.go │ │ ├── rsa_utils.go │ │ ├── hmac.go │ │ ├── token.go │ │ ├── rsa_pss.go │ │ ├── ecdsa.go │ │ ├── types.go │ │ ├── parser_option.go │ │ ├── README.md │ │ ├── VERSION_HISTORY.md │ │ ├── MIGRATION_GUIDE.md │ │ ├── parser.go │ │ └── validator.go └── modules.txt ├── entrypoint.sh ├── go.mod ├── .dockerignore ├── go.sum ├── Dockerfile ├── .gitignore ├── action.yml ├── cmd └── oidc-debug.go ├── script └── release ├── LICENSE ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── README.md └── actionsoidc └── actions-oidc.go /.go-version: -------------------------------------------------------------------------------- 1 | 1.24.6 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @github/security-ops-reviewers 2 | -------------------------------------------------------------------------------- /vendor/github.com/golang-jwt/jwt/v5/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | bin 3 | .idea/ 4 | 5 | -------------------------------------------------------------------------------- /entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -l 2 | 3 | cd / 4 | 5 | go run cmd/oidc-debug.go -audience $1 6 | -------------------------------------------------------------------------------- /vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf: -------------------------------------------------------------------------------- 1 | checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"] 2 | -------------------------------------------------------------------------------- /vendor/modules.txt: -------------------------------------------------------------------------------- 1 | # github.com/golang-jwt/jwt/v5 v5.3.0 2 | ## explicit; go 1.21 3 | github.com/golang-jwt/jwt/v5 4 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/github/actions-oidc-debugger 2 | 3 | go 1.24 4 | 5 | require github.com/golang-jwt/jwt/v5 v5.3.0 6 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .devcontainer/ 2 | .github/ 3 | .git/ 4 | script/ 5 | action.yml 6 | Dockerfile 7 | LICENSE 8 | README.md 9 | tmp/ 10 | .vscode/ 11 | docs/ 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= 2 | github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= 3 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM alpine:3.22.1@sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1 2 | 3 | COPY .go-version .go-version 4 | 5 | RUN apk add --no-cache go=$(cat .go-version)-r0 6 | 7 | COPY . . 8 | 9 | ENTRYPOINT ["/entrypoint.sh"] 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ 16 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: 'OIDC Debugger' 2 | description: 'Print the GitHub Actions OIDC claims.' 3 | branding: 4 | icon: 'activity' 5 | color: 'red' 6 | inputs: 7 | audience: 8 | description: 'The audience to use when requesting the JWT. Your Github server URL and repository owner (e.g. https://github.com/github).' 9 | required: true 10 | runs: 11 | using: 'docker' 12 | image: 'Dockerfile' 13 | args: 14 | - ${{ inputs.audience }} 15 | -------------------------------------------------------------------------------- /.github/workflows/action-test.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Test Debugger Action 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | workflow_dispatch: 8 | 9 | jobs: 10 | oidc_debug_test: 11 | permissions: 12 | contents: read 13 | id-token: write 14 | runs-on: ubuntu-latest 15 | name: A test of the oidc debugger 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v5 19 | - name: Debug OIDC Claims 20 | uses: ./ 21 | with: 22 | audience: 'https://github.com/github' 23 | -------------------------------------------------------------------------------- /cmd/oidc-debug.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | "github.com/github/actions-oidc-debugger/actionsoidc" 8 | ) 9 | 10 | func main() { 11 | 12 | audience := flag.String("audience", "https://github.com/", "the audience for the requested jwt") 13 | flag.Parse() 14 | 15 | if *audience == "https://github.com/" { 16 | actionsoidc.QuitOnErr(fmt.Errorf("-audience cli argument must be specified")) 17 | } 18 | 19 | c := actionsoidc.DefaultOIDCClient(*audience) 20 | jwt, err := c.GetJWT() 21 | actionsoidc.QuitOnErr(err) 22 | 23 | jwt.Parse() 24 | fmt.Print(jwt.PrettyPrintClaims()) 25 | } 26 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: gomod 5 | directory: "/" 6 | schedule: 7 | interval: monthly 8 | groups: 9 | go-dependencies: 10 | patterns: 11 | - "*" 12 | 13 | - package-ecosystem: docker 14 | directory: "/" 15 | schedule: 16 | interval: monthly 17 | groups: 18 | docker-dependencies: 19 | patterns: 20 | - "*" 21 | 22 | - package-ecosystem: github-actions 23 | directory: "/" 24 | groups: 25 | github-actions: 26 | patterns: 27 | - "*" 28 | schedule: 29 | interval: monthly 30 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Test OIDC Debugger 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | workflow_dispatch: 8 | 9 | jobs: 10 | test: 11 | permissions: 12 | contents: read 13 | id-token: write 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: git checkout 17 | uses: actions/checkout@v5 18 | 19 | - name: setup go 20 | uses: actions/setup-go@v5 21 | with: 22 | go-version-file: 'go.mod' 23 | cache: true 24 | 25 | - name: run oidc-debug.go 26 | run: go run cmd/oidc-debug.go -audience "https://github.com/github" 27 | 28 | - name: docker build 29 | run: docker build -t actions-oidc-debugger . 30 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /script/release: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Usage: 4 | # script/release 5 | 6 | # COLORS 7 | OFF='\033[0m' 8 | RED='\033[0;31m' 9 | GREEN='\033[0;32m' 10 | BLUE='\033[0;34m' 11 | 12 | latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1)) 13 | echo -e "The latest release tag is: ${BLUE}${latest_tag}${OFF}" 14 | read -p 'New Release Tag (vX.X.X format): ' new_tag 15 | 16 | # Updated regex to allow one or more digits in each segment 17 | tag_regex='^v[0-9]+\.[0-9]+\.[0-9]+$' 18 | echo "$new_tag" | grep -E -q $tag_regex 19 | 20 | if [[ $? -ne 0 ]]; then 21 | echo -e "${RED}ERROR${OFF} - Tag: $new_tag is not valid. Please use vX.X.X format." 22 | exit 1 23 | fi 24 | 25 | git tag -a $new_tag -m "$new_tag Release" 26 | 27 | echo -e "${GREEN}OK${OFF} - Tagged: $new_tag" 28 | 29 | git push --tags 30 | 31 | echo -e "${GREEN}OK${OFF} - Tags pushed to remote!" 32 | echo -e "${GREEN}DONE${OFF}" 33 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 GitHub 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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.224.3/containers/go/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] Go version (use -bullseye variants on local arm64/Apple Silicon): 1, 1.16, 1.17, 1-bullseye, 1.16-bullseye, 1.17-bullseye, 1-buster, 1.16-buster, 1.17-buster 4 | ARG VARIANT="1.18-bullseye" 5 | FROM mcr.microsoft.com/vscode/devcontainers/go:0-${VARIANT} 6 | 7 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 8 | ARG NODE_VERSION="none" 9 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 10 | 11 | # [Optional] Uncomment this section to install additional OS packages. 12 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 13 | # && apt-get -y install --no-install-recommends 14 | 15 | # [Optional] Uncomment the next lines to use go get to install anything else you need 16 | # USER vscode 17 | # RUN go get -x 18 | 19 | # [Optional] Uncomment this line to install global node packages. 20 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 21 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.224.3/containers/go 3 | { 4 | "name": "Go", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | "args": { 8 | // Update the VARIANT arg to pick a version of Go: 1, 1.18, 1.17 9 | // Append -bullseye or -buster to pin to an OS version. 10 | // Use -bullseye variants on local arm64/Apple Silicon. 11 | "VARIANT": "1-bullseye", 12 | // Options 13 | "NODE_VERSION": "lts/*" 14 | } 15 | }, 16 | "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ], 17 | 18 | // Set *default* container specific settings.json values on container create. 19 | "settings": { 20 | "go.toolsManagement.checkForUpdates": "local", 21 | "go.useLanguageServer": true, 22 | "go.gopath": "/go" 23 | }, 24 | 25 | // Add the IDs of extensions you want installed when the container is created. 26 | "extensions": [ 27 | "golang.Go" 28 | ], 29 | 30 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 31 | // "forwardPorts": [], 32 | 33 | // Use 'postCreateCommand' to run commands after the container is created. 34 | // "postCreateCommand": "go version", 35 | 36 | // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 37 | "remoteUser": "vscode", 38 | "features": { 39 | "git": "os-provided", 40 | "github-cli": "latest" 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /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 any 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 any 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/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 any) error // Returns nil if signature is valid 16 | Sign(signingString string, key any) ([]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/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 any) (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 any) ([]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/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 any 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 any 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 any) 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 any) ([]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/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 any) 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 any) ([]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/errors.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "strings" 7 | ) 8 | 9 | var ( 10 | ErrInvalidKey = errors.New("key is invalid") 11 | ErrInvalidKeyType = errors.New("key is of invalid type") 12 | ErrHashUnavailable = errors.New("the requested hash function is unavailable") 13 | ErrTokenMalformed = errors.New("token is malformed") 14 | ErrTokenUnverifiable = errors.New("token is unverifiable") 15 | ErrTokenSignatureInvalid = errors.New("token signature is invalid") 16 | ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") 17 | ErrTokenInvalidAudience = errors.New("token has invalid audience") 18 | ErrTokenExpired = errors.New("token is expired") 19 | ErrTokenUsedBeforeIssued = errors.New("token used before issued") 20 | ErrTokenInvalidIssuer = errors.New("token has invalid issuer") 21 | ErrTokenInvalidSubject = errors.New("token has invalid subject") 22 | ErrTokenNotValidYet = errors.New("token is not valid yet") 23 | ErrTokenInvalidId = errors.New("token has invalid id") 24 | ErrTokenInvalidClaims = errors.New("token has invalid claims") 25 | ErrInvalidType = errors.New("invalid type for claim") 26 | ) 27 | 28 | // joinedError is an error type that works similar to what [errors.Join] 29 | // produces, with the exception that it has a nice error string; mainly its 30 | // error messages are concatenated using a comma, rather than a newline. 31 | type joinedError struct { 32 | errs []error 33 | } 34 | 35 | func (je joinedError) Error() string { 36 | msg := []string{} 37 | for _, err := range je.errs { 38 | msg = append(msg, err.Error()) 39 | } 40 | 41 | return strings.Join(msg, ", ") 42 | } 43 | 44 | // joinErrors joins together multiple errors. Useful for scenarios where 45 | // multiple errors next to each other occur, e.g., in claims validation. 46 | func joinErrors(errs ...error) error { 47 | return &joinedError{ 48 | errs: errs, 49 | } 50 | } 51 | 52 | // Unwrap implements the multiple error unwrapping for this error type, which is 53 | // possible in Go 1.20. 54 | func (je joinedError) Unwrap() []error { 55 | return je.errs 56 | } 57 | 58 | // newError creates a new error message with a detailed error message. The 59 | // message will be prefixed with the contents of the supplied error type. 60 | // Additionally, more errors, that provide more context can be supplied which 61 | // will be appended to the message. This makes use of Go 1.20's possibility to 62 | // include more than one %w formatting directive in [fmt.Errorf]. 63 | // 64 | // For example, 65 | // 66 | // newError("no keyfunc was provided", ErrTokenUnverifiable) 67 | // 68 | // will produce the error string 69 | // 70 | // "token is unverifiable: no keyfunc was provided" 71 | func newError(message string, err error, more ...error) error { 72 | var format string 73 | var args []any 74 | if message != "" { 75 | format = "%w: %s" 76 | args = []any{err, message} 77 | } else { 78 | format = "%w" 79 | args = []any{err} 80 | } 81 | 82 | for _, e := range more { 83 | format += ": %w" 84 | args = append(args, e) 85 | } 86 | 87 | err = fmt.Errorf(format, args...) 88 | return err 89 | } 90 | -------------------------------------------------------------------------------- /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]any for JSON 9 | // decoding. This is the default claims type if you don't supply one 10 | type MapClaims map[string]any 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 []any: 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 any 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/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 any 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 any 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 any 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⚠️ Archival notice 2 | 3 | Due to the lack of time we could allocate to this repo, we've decided to archive it. 4 | 5 | You can use [`steve-todorov`'s version](https://github.com/steve-todorov/oidc-debugger-action/blob/f9915fe9dc64133704c072eb59436373c23e9fdd/action.yml) instead. 6 | 7 | If you want just the code ([reference](https://github.com/github/actions-oidc-debugger/issues/30#issuecomment-3169059282), thanks again to `steve-todorov`): 8 | ```yaml 9 | - name: Show OIDC claims (right before assume) 10 | env: 11 | AUDIENCE: "sts.amazonaws.com" 12 | run: | 13 | TOKEN_JSON=$(curl -s -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=$AUDIENCE") 14 | ID_TOKEN=$(echo "$TOKEN_JSON" | jq -r .value) 15 | echo "$ID_TOKEN" | awk -F. '{print $2}' | base64 -d 2>/dev/null | jq -r 16 | ``` 17 | 18 | --- 19 | 20 | # actions-oidc-debugger 21 | 22 | This action requests a JWT and prints the claims included within the JWT received from GitHub Actions. 23 | 24 | ## How to use this Action 25 | 26 | Here's an example of how to use this action: 27 | 28 | ```yaml 29 | 30 | name: Test Debugger Action 31 | on: 32 | pull_request: 33 | workflow_dispatch: 34 | 35 | jobs: 36 | oidc_debug_test: 37 | permissions: 38 | contents: read 39 | id-token: write 40 | runs-on: ubuntu-latest 41 | name: A test of the oidc debugger 42 | steps: 43 | - name: Debug OIDC Claims 44 | uses: github/actions-oidc-debugger@main 45 | with: 46 | audience: '${{ github.server_url }}/${{ github.repository_owner }}' 47 | ``` 48 | 49 | The resulting output in your Actions log will look something like this: 50 | 51 | ```json 52 | { 53 | "actor": "GrantBirki", 54 | "actor_id": "23362539", 55 | "aud": "https://github.com/github", 56 | "base_ref": "main", 57 | "enterprise": "github", 58 | "enterprise_id": "11468", 59 | "event_name": "pull_request", 60 | "exp": 1751581975, 61 | "head_ref": "release-setup", 62 | "iat": 1751560375, 63 | "iss": "https://token.actions.githubusercontent.com", 64 | "job_workflow_ref": "github/actions-oidc-debugger/.github/workflows/action-test.yml@refs/pull/27/merge", 65 | "job_workflow_sha": "7f93a73b8273af5d35fcd70661704c1cadc57054", 66 | "jti": "4a576b35-ff09-41c5-af2c-ca62dd89b76a", 67 | "nbf": 1751560075, 68 | "ref": "refs/pull/27/merge", 69 | "ref_protected": "false", 70 | "ref_type": "branch", 71 | "repository": "github/actions-oidc-debugger", 72 | "repository_id": "487920697", 73 | "repository_owner": "github", 74 | "repository_owner_id": "9919", 75 | "repository_visibility": "public", 76 | "run_attempt": "1", 77 | "run_id": "16055869479", 78 | "run_number": "33", 79 | "runner_environment": "github-hosted", 80 | "sha": "7f93a73b8273af5d35fcd70661704c1cadc57054", 81 | "sub": "repo:github/actions-oidc-debugger:pull_request", 82 | "workflow": "Test Debugger Action", 83 | "workflow_ref": "github/actions-oidc-debugger/.github/workflows/action-test.yml@refs/pull/27/merge", 84 | "workflow_sha": "7f93a73b8273af5d35fcd70661704c1cadc57054" 85 | } 86 | ``` 87 | 88 | ## Maintainers 89 | 90 | Here is the general flow for developing this Action and releasing a new version: 91 | 92 | ### Bootstrapping 93 | 94 | This assumes you have `goenv` installed and the version listed in the `.go-version` file is installed as well. 95 | 96 | ```bash 97 | go mod vendor && go mod tidy && go mod verify 98 | ``` 99 | 100 | ### Releasing 101 | 102 | Please run `script/release` and publish a new release on GitHub from the resulting tag. 103 | -------------------------------------------------------------------------------- /actionsoidc/actions-oidc.go: -------------------------------------------------------------------------------- 1 | package actionsoidc 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "net/http" 9 | "net/url" 10 | "os" 11 | 12 | "github.com/golang-jwt/jwt/v5" 13 | ) 14 | 15 | type ActionsOIDCClient struct { 16 | // the url to fetch the jwt 17 | TokenRequestURL string 18 | // the audience for the jwt 19 | Audience string 20 | // the token used to retrieve the jwt, not the jwt 21 | RequestToken string 22 | } 23 | 24 | type ActionsJWT struct { 25 | Count int 26 | Value string 27 | ParsedToken *jwt.Token 28 | } 29 | 30 | func GetEnvironmentVariable(e string) (string, error) { 31 | value := os.Getenv(e) 32 | if value == "" { 33 | return "", fmt.Errorf("missing %s from envrionment", e) 34 | } 35 | return value, nil 36 | } 37 | 38 | func QuitOnErr(e error) { 39 | if e != nil { 40 | log.Fatal(e) 41 | } 42 | } 43 | 44 | // construct a new ActionsOIDCClient 45 | func NewActionsOIDCClient(tokenURL string, audience string, token string) (ActionsOIDCClient, error) { 46 | c := ActionsOIDCClient{ 47 | TokenRequestURL: tokenURL, 48 | Audience: audience, 49 | RequestToken: token, 50 | } 51 | err := c.BuildTokenURL() 52 | return c, err 53 | } 54 | 55 | func DefaultOIDCClient(audience string) ActionsOIDCClient { 56 | tokenURL, err := GetEnvironmentVariable("ACTIONS_ID_TOKEN_REQUEST_URL") 57 | QuitOnErr(err) 58 | token, err := GetEnvironmentVariable("ACTIONS_ID_TOKEN_REQUEST_TOKEN") 59 | QuitOnErr(err) 60 | 61 | c, err := NewActionsOIDCClient(tokenURL, audience, token) 62 | QuitOnErr(err) 63 | 64 | return c 65 | } 66 | 67 | // this function uses an ActionsOIDCClient to build the complete URL 68 | // to request a jwt 69 | func (c *ActionsOIDCClient) BuildTokenURL() error { 70 | parsed_url, err := url.Parse(c.TokenRequestURL) 71 | if err != nil { 72 | return fmt.Errorf("failed to parse URL: %w", err) 73 | } 74 | 75 | if c.Audience != "" { 76 | query := parsed_url.Query() 77 | query.Set("audience", c.Audience) 78 | parsed_url.RawQuery = query.Encode() 79 | c.TokenRequestURL = parsed_url.String() 80 | } 81 | return nil 82 | } 83 | 84 | // retrieve an actions oidc token 85 | func (c *ActionsOIDCClient) GetJWT() (*ActionsJWT, error) { 86 | request, err := http.NewRequest("GET", c.TokenRequestURL, nil) 87 | if err != nil { 88 | return nil, err 89 | } 90 | 91 | request.Header.Set("Authorization", "Bearer "+c.RequestToken) 92 | 93 | var httpClient http.Client 94 | response, err := httpClient.Do(request) 95 | if err != nil { 96 | return nil, err 97 | } 98 | defer response.Body.Close() 99 | 100 | if response.StatusCode != http.StatusOK { 101 | return nil, fmt.Errorf("received non-200 from jwt api: %s", http.StatusText((response.StatusCode))) 102 | } 103 | 104 | rawBody, err := ioutil.ReadAll(response.Body) 105 | if err != nil { 106 | return nil, err 107 | } 108 | 109 | var jwt ActionsJWT 110 | err = json.Unmarshal(rawBody, &jwt) 111 | 112 | return &jwt, err 113 | } 114 | 115 | func (j *ActionsJWT) Parse() { 116 | j.ParsedToken, _ = jwt.Parse(j.Value, func(token *jwt.Token) (interface{}, error) { 117 | // Don't forget to validate the alg is what you expect: 118 | if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { 119 | return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) 120 | } 121 | 122 | // we don't need a real check here 123 | return []byte{}, nil 124 | }) 125 | } 126 | 127 | func (j *ActionsJWT) PrettyPrintClaims() string { 128 | if claims, ok := j.ParsedToken.Claims.(jwt.MapClaims); ok { 129 | jsonClaims, err := json.MarshalIndent(claims, "", " ") 130 | if err != nil { 131 | fmt.Println(fmt.Errorf("%w", err)) 132 | } 133 | return string(jsonClaims) 134 | } 135 | return "" 136 | } 137 | -------------------------------------------------------------------------------- /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 any) 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 any) ([]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/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 any may be a single key or a VerificationKeySet containing 15 | // multiple keys. 16 | type Keyfunc func(*Token) (any, 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]any // 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]any{ 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 any) (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/rsa_pss.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | ) 8 | 9 | // SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods 10 | type SigningMethodRSAPSS struct { 11 | *SigningMethodRSA 12 | Options *rsa.PSSOptions 13 | // VerifyOptions is optional. If set overrides Options for rsa.VerifyPPS. 14 | // Used to accept tokens signed with rsa.PSSSaltLengthAuto, what doesn't follow 15 | // https://tools.ietf.org/html/rfc7518#section-3.5 but was used previously. 16 | // See https://github.com/dgrijalva/jwt-go/issues/285#issuecomment-437451244 for details. 17 | VerifyOptions *rsa.PSSOptions 18 | } 19 | 20 | // Specific instances for RS/PS and company. 21 | var ( 22 | SigningMethodPS256 *SigningMethodRSAPSS 23 | SigningMethodPS384 *SigningMethodRSAPSS 24 | SigningMethodPS512 *SigningMethodRSAPSS 25 | ) 26 | 27 | func init() { 28 | // PS256 29 | SigningMethodPS256 = &SigningMethodRSAPSS{ 30 | SigningMethodRSA: &SigningMethodRSA{ 31 | Name: "PS256", 32 | Hash: crypto.SHA256, 33 | }, 34 | Options: &rsa.PSSOptions{ 35 | SaltLength: rsa.PSSSaltLengthEqualsHash, 36 | }, 37 | VerifyOptions: &rsa.PSSOptions{ 38 | SaltLength: rsa.PSSSaltLengthAuto, 39 | }, 40 | } 41 | RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { 42 | return SigningMethodPS256 43 | }) 44 | 45 | // PS384 46 | SigningMethodPS384 = &SigningMethodRSAPSS{ 47 | SigningMethodRSA: &SigningMethodRSA{ 48 | Name: "PS384", 49 | Hash: crypto.SHA384, 50 | }, 51 | Options: &rsa.PSSOptions{ 52 | SaltLength: rsa.PSSSaltLengthEqualsHash, 53 | }, 54 | VerifyOptions: &rsa.PSSOptions{ 55 | SaltLength: rsa.PSSSaltLengthAuto, 56 | }, 57 | } 58 | RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { 59 | return SigningMethodPS384 60 | }) 61 | 62 | // PS512 63 | SigningMethodPS512 = &SigningMethodRSAPSS{ 64 | SigningMethodRSA: &SigningMethodRSA{ 65 | Name: "PS512", 66 | Hash: crypto.SHA512, 67 | }, 68 | Options: &rsa.PSSOptions{ 69 | SaltLength: rsa.PSSSaltLengthEqualsHash, 70 | }, 71 | VerifyOptions: &rsa.PSSOptions{ 72 | SaltLength: rsa.PSSSaltLengthAuto, 73 | }, 74 | } 75 | RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { 76 | return SigningMethodPS512 77 | }) 78 | } 79 | 80 | // Verify implements token verification for the SigningMethod. 81 | // For this verify method, key must be an rsa.PublicKey struct 82 | func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key any) error { 83 | var rsaKey *rsa.PublicKey 84 | switch k := key.(type) { 85 | case *rsa.PublicKey: 86 | rsaKey = k 87 | default: 88 | return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) 89 | } 90 | 91 | // Create hasher 92 | if !m.Hash.Available() { 93 | return ErrHashUnavailable 94 | } 95 | hasher := m.Hash.New() 96 | hasher.Write([]byte(signingString)) 97 | 98 | opts := m.Options 99 | if m.VerifyOptions != nil { 100 | opts = m.VerifyOptions 101 | } 102 | 103 | return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) 104 | } 105 | 106 | // Sign implements token signing for the SigningMethod. 107 | // For this signing method, key must be an rsa.PrivateKey struct 108 | func (m *SigningMethodRSAPSS) Sign(signingString string, key any) ([]byte, error) { 109 | var rsaKey *rsa.PrivateKey 110 | 111 | switch k := key.(type) { 112 | case *rsa.PrivateKey: 113 | rsaKey = k 114 | default: 115 | return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) 116 | } 117 | 118 | // Create the hasher 119 | if !m.Hash.Available() { 120 | return nil, ErrHashUnavailable 121 | } 122 | 123 | hasher := m.Hash.New() 124 | hasher.Write([]byte(signingString)) 125 | 126 | // Sign the string and return the encoded bytes 127 | if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { 128 | return sigBytes, nil 129 | } else { 130 | return nil, err 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /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 any) 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 any) ([]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/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 any 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 []any: 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/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 any of the specified 70 | // audiences in the `aud` claim. Validation will fail if the audience is not 71 | // listed in the 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 | // WithAllAudiences configures the validator to require all the specified 84 | // audiences in the `aud` claim. Validation will fail if the specified audiences 85 | // are not listed in the token or the `aud` claim is missing. Duplicates within 86 | // the list are de-duplicated since internally, we use a map to look up the 87 | // audiences. 88 | // 89 | // NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is 90 | // application-specific. Since this validation API is helping developers in 91 | // writing secure application, we decided to REQUIRE the existence of the claim, 92 | // if an audience is expected. 93 | func WithAllAudiences(aud ...string) ParserOption { 94 | return func(p *Parser) { 95 | p.validator.expectedAud = aud 96 | p.validator.expectAllAud = true 97 | } 98 | } 99 | 100 | // WithIssuer configures the validator to require the specified issuer in the 101 | // `iss` claim. Validation will fail if a different issuer is specified in the 102 | // token or the `iss` claim is missing. 103 | // 104 | // NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is 105 | // application-specific. Since this validation API is helping developers in 106 | // writing secure application, we decided to REQUIRE the existence of the claim, 107 | // if an issuer is expected. 108 | func WithIssuer(iss string) ParserOption { 109 | return func(p *Parser) { 110 | p.validator.expectedIss = iss 111 | } 112 | } 113 | 114 | // WithSubject configures the validator to require the specified subject in the 115 | // `sub` claim. Validation will fail if a different subject is specified in the 116 | // token or the `sub` claim is missing. 117 | // 118 | // NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is 119 | // application-specific. Since this validation API is helping developers in 120 | // writing secure application, we decided to REQUIRE the existence of the claim, 121 | // if a subject is expected. 122 | func WithSubject(sub string) ParserOption { 123 | return func(p *Parser) { 124 | p.validator.expectedSub = sub 125 | } 126 | } 127 | 128 | // WithPaddingAllowed will enable the codec used for decoding JWTs to allow 129 | // padding. Note that the JWS RFC7515 states that the tokens will utilize a 130 | // Base64url encoding with no padding. Unfortunately, some implementations of 131 | // JWT are producing non-standard tokens, and thus require support for decoding. 132 | func WithPaddingAllowed() ParserOption { 133 | return func(p *Parser) { 134 | p.decodePaddingAllowed = true 135 | } 136 | } 137 | 138 | // WithStrictDecoding will switch the codec used for decoding JWTs into strict 139 | // mode. In this mode, the decoder requires that trailing padding bits are zero, 140 | // as described in RFC 4648 section 3.5. 141 | func WithStrictDecoding() ParserOption { 142 | return func(p *Parser) { 143 | p.decodeStrict = true 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /vendor/github.com/golang-jwt/jwt/v5/README.md: -------------------------------------------------------------------------------- 1 | # jwt-go 2 | 3 | [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) 4 | [![Go 5 | Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) 6 | [![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](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/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/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]any // 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/parser.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "fmt" 8 | "strings" 9 | ) 10 | 11 | const tokenDelimiter = "." 12 | 13 | type Parser struct { 14 | // If populated, only these methods will be considered valid. 15 | validMethods []string 16 | 17 | // Use JSON Number format in JSON decoder. 18 | useJSONNumber bool 19 | 20 | // Skip claims validation during token parsing. 21 | skipClaimsValidation bool 22 | 23 | validator *Validator 24 | 25 | decodeStrict bool 26 | 27 | decodePaddingAllowed bool 28 | } 29 | 30 | // NewParser creates a new Parser with the specified options 31 | func NewParser(options ...ParserOption) *Parser { 32 | p := &Parser{ 33 | validator: &Validator{}, 34 | } 35 | 36 | // Loop through our parsing options and apply them 37 | for _, option := range options { 38 | option(p) 39 | } 40 | 41 | return p 42 | } 43 | 44 | // Parse parses, validates, verifies the signature and returns the parsed token. 45 | // keyFunc will receive the parsed token and should return the key for validating. 46 | func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { 47 | return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) 48 | } 49 | 50 | // ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims 51 | // interface. This provides default values which can be overridden and allows a caller to use their own type, rather 52 | // than the default MapClaims implementation of Claims. 53 | // 54 | // Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), 55 | // make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the 56 | // proper memory for it before passing in the overall claims, otherwise you might run into a panic. 57 | func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { 58 | token, parts, err := p.ParseUnverified(tokenString, claims) 59 | if err != nil { 60 | return token, err 61 | } 62 | 63 | // Verify signing method is in the required set 64 | if p.validMethods != nil { 65 | var signingMethodValid = false 66 | var alg = token.Method.Alg() 67 | for _, m := range p.validMethods { 68 | if m == alg { 69 | signingMethodValid = true 70 | break 71 | } 72 | } 73 | if !signingMethodValid { 74 | // signing method is not in the listed set 75 | return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) 76 | } 77 | } 78 | 79 | // Decode signature 80 | token.Signature, err = p.DecodeSegment(parts[2]) 81 | if err != nil { 82 | return token, newError("could not base64 decode signature", ErrTokenMalformed, err) 83 | } 84 | text := strings.Join(parts[0:2], ".") 85 | 86 | // Lookup key(s) 87 | if keyFunc == nil { 88 | // keyFunc was not provided. short circuiting validation 89 | return token, newError("no keyfunc was provided", ErrTokenUnverifiable) 90 | } 91 | 92 | got, err := keyFunc(token) 93 | if err != nil { 94 | return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) 95 | } 96 | 97 | switch have := got.(type) { 98 | case VerificationKeySet: 99 | if len(have.Keys) == 0 { 100 | return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) 101 | } 102 | // Iterate through keys and verify signature, skipping the rest when a match is found. 103 | // Return the last error if no match is found. 104 | for _, key := range have.Keys { 105 | if err = token.Method.Verify(text, token.Signature, key); err == nil { 106 | break 107 | } 108 | } 109 | default: 110 | err = token.Method.Verify(text, token.Signature, have) 111 | } 112 | if err != nil { 113 | return token, newError("", ErrTokenSignatureInvalid, err) 114 | } 115 | 116 | // Validate Claims 117 | if !p.skipClaimsValidation { 118 | // Make sure we have at least a default validator 119 | if p.validator == nil { 120 | p.validator = NewValidator() 121 | } 122 | 123 | if err := p.validator.Validate(claims); err != nil { 124 | return token, newError("", ErrTokenInvalidClaims, err) 125 | } 126 | } 127 | 128 | // No errors so far, token is valid. 129 | token.Valid = true 130 | 131 | return token, nil 132 | } 133 | 134 | // ParseUnverified parses the token but doesn't validate the signature. 135 | // 136 | // WARNING: Don't use this method unless you know what you're doing. 137 | // 138 | // It's only ever useful in cases where you know the signature is valid (since it has already 139 | // been or will be checked elsewhere in the stack) and you want to extract values from it. 140 | func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { 141 | var ok bool 142 | parts, ok = splitToken(tokenString) 143 | if !ok { 144 | return nil, nil, newError("token contains an invalid number of segments", ErrTokenMalformed) 145 | } 146 | 147 | token = &Token{Raw: tokenString} 148 | 149 | // parse Header 150 | var headerBytes []byte 151 | if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { 152 | return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) 153 | } 154 | if err = json.Unmarshal(headerBytes, &token.Header); err != nil { 155 | return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) 156 | } 157 | 158 | // parse Claims 159 | token.Claims = claims 160 | 161 | claimBytes, err := p.DecodeSegment(parts[1]) 162 | if err != nil { 163 | return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) 164 | } 165 | 166 | // If `useJSONNumber` is enabled then we must use *json.Decoder to decode 167 | // the claims. However, this comes with a performance penalty so only use 168 | // it if we must and, otherwise, simple use json.Unmarshal. 169 | if !p.useJSONNumber { 170 | // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. 171 | if c, ok := token.Claims.(MapClaims); ok { 172 | err = json.Unmarshal(claimBytes, &c) 173 | } else { 174 | err = json.Unmarshal(claimBytes, &claims) 175 | } 176 | } else { 177 | dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) 178 | dec.UseNumber() 179 | // JSON Decode. Special case for map type to avoid weird pointer behavior. 180 | if c, ok := token.Claims.(MapClaims); ok { 181 | err = dec.Decode(&c) 182 | } else { 183 | err = dec.Decode(&claims) 184 | } 185 | } 186 | if err != nil { 187 | return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) 188 | } 189 | 190 | // Lookup signature method 191 | if method, ok := token.Header["alg"].(string); ok { 192 | if token.Method = GetSigningMethod(method); token.Method == nil { 193 | return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) 194 | } 195 | } else { 196 | return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) 197 | } 198 | 199 | return token, parts, nil 200 | } 201 | 202 | // splitToken splits a token string into three parts: header, claims, and signature. It will only 203 | // return true if the token contains exactly two delimiters and three parts. In all other cases, it 204 | // will return nil parts and false. 205 | func splitToken(token string) ([]string, bool) { 206 | parts := make([]string, 3) 207 | header, remain, ok := strings.Cut(token, tokenDelimiter) 208 | if !ok { 209 | return nil, false 210 | } 211 | parts[0] = header 212 | claims, remain, ok := strings.Cut(remain, tokenDelimiter) 213 | if !ok { 214 | return nil, false 215 | } 216 | parts[1] = claims 217 | // One more cut to ensure the signature is the last part of the token and there are no more 218 | // delimiters. This avoids an issue where malicious input could contain additional delimiters 219 | // causing unecessary overhead parsing tokens. 220 | signature, _, unexpected := strings.Cut(remain, tokenDelimiter) 221 | if unexpected { 222 | return nil, false 223 | } 224 | parts[2] = signature 225 | 226 | return parts, true 227 | } 228 | 229 | // DecodeSegment decodes a JWT specific base64url encoding. This function will 230 | // take into account whether the [Parser] is configured with additional options, 231 | // such as [WithStrictDecoding] or [WithPaddingAllowed]. 232 | func (p *Parser) DecodeSegment(seg string) ([]byte, error) { 233 | encoding := base64.RawURLEncoding 234 | 235 | if p.decodePaddingAllowed { 236 | if l := len(seg) % 4; l > 0 { 237 | seg += strings.Repeat("=", 4-l) 238 | } 239 | encoding = base64.URLEncoding 240 | } 241 | 242 | if p.decodeStrict { 243 | encoding = encoding.Strict() 244 | } 245 | return encoding.DecodeString(seg) 246 | } 247 | 248 | // Parse parses, validates, verifies the signature and returns the parsed token. 249 | // keyFunc will receive the parsed token and should return the cryptographic key 250 | // for verifying the signature. The caller is strongly encouraged to set the 251 | // WithValidMethods option to validate the 'alg' claim in the token matches the 252 | // expected algorithm. For more details about the importance of validating the 253 | // 'alg' claim, see 254 | // https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ 255 | func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { 256 | return NewParser(options...).Parse(tokenString, keyFunc) 257 | } 258 | 259 | // ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). 260 | // 261 | // Note: If you provide a custom claim implementation that embeds one of the 262 | // standard claims (such as RegisteredClaims), make sure that a) you either 263 | // embed a non-pointer version of the claims or b) if you are using a pointer, 264 | // allocate the proper memory for it before passing in the overall claims, 265 | // otherwise you might run into a panic. 266 | func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { 267 | return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) 268 | } 269 | -------------------------------------------------------------------------------- /vendor/github.com/golang-jwt/jwt/v5/validator.go: -------------------------------------------------------------------------------- 1 | package jwt 2 | 3 | import ( 4 | "fmt" 5 | "slices" 6 | "time" 7 | ) 8 | 9 | // ClaimsValidator is an interface that can be implemented by custom claims who 10 | // wish to execute any additional claims validation based on 11 | // application-specific logic. The Validate function is then executed in 12 | // addition to the regular claims validation and any error returned is appended 13 | // to the final validation result. 14 | // 15 | // type MyCustomClaims struct { 16 | // Foo string `json:"foo"` 17 | // jwt.RegisteredClaims 18 | // } 19 | // 20 | // func (m MyCustomClaims) Validate() error { 21 | // if m.Foo != "bar" { 22 | // return errors.New("must be foobar") 23 | // } 24 | // return nil 25 | // } 26 | type ClaimsValidator interface { 27 | Claims 28 | Validate() error 29 | } 30 | 31 | // Validator is the core of the new Validation API. It is automatically used by 32 | // a [Parser] during parsing and can be modified with various parser options. 33 | // 34 | // The [NewValidator] function should be used to create an instance of this 35 | // struct. 36 | type Validator struct { 37 | // leeway is an optional leeway that can be provided to account for clock skew. 38 | leeway time.Duration 39 | 40 | // timeFunc is used to supply the current time that is needed for 41 | // validation. If unspecified, this defaults to time.Now. 42 | timeFunc func() time.Time 43 | 44 | // requireExp specifies whether the exp claim is required 45 | requireExp bool 46 | 47 | // verifyIat specifies whether the iat (Issued At) claim will be verified. 48 | // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this 49 | // only specifies the age of the token, but no validation check is 50 | // necessary. However, if wanted, it can be checked if the iat is 51 | // unrealistic, i.e., in the future. 52 | verifyIat bool 53 | 54 | // expectedAud contains the audience this token expects. Supplying an empty 55 | // slice will disable aud checking. 56 | expectedAud []string 57 | 58 | // expectAllAud specifies whether all expected audiences must be present in 59 | // the token. If false, only one of the expected audiences must be present. 60 | expectAllAud bool 61 | 62 | // expectedIss contains the issuer this token expects. Supplying an empty 63 | // string will disable iss checking. 64 | expectedIss string 65 | 66 | // expectedSub contains the subject this token expects. Supplying an empty 67 | // string will disable sub checking. 68 | expectedSub string 69 | } 70 | 71 | // NewValidator can be used to create a stand-alone validator with the supplied 72 | // options. This validator can then be used to validate already parsed claims. 73 | // 74 | // Note: Under normal circumstances, explicitly creating a validator is not 75 | // needed and can potentially be dangerous; instead functions of the [Parser] 76 | // class should be used. 77 | // 78 | // The [Validator] is only checking the *validity* of the claims, such as its 79 | // expiration time, but it does NOT perform *signature verification* of the 80 | // token. 81 | func NewValidator(opts ...ParserOption) *Validator { 82 | p := NewParser(opts...) 83 | return p.validator 84 | } 85 | 86 | // Validate validates the given claims. It will also perform any custom 87 | // validation if claims implements the [ClaimsValidator] interface. 88 | // 89 | // Note: It will NOT perform any *signature verification* on the token that 90 | // contains the claims and expects that the [Claim] was already successfully 91 | // verified. 92 | func (v *Validator) Validate(claims Claims) error { 93 | var ( 94 | now time.Time 95 | errs = make([]error, 0, 6) 96 | err error 97 | ) 98 | 99 | // Check, if we have a time func 100 | if v.timeFunc != nil { 101 | now = v.timeFunc() 102 | } else { 103 | now = time.Now() 104 | } 105 | 106 | // We always need to check the expiration time, but usage of the claim 107 | // itself is OPTIONAL by default. requireExp overrides this behavior 108 | // and makes the exp claim mandatory. 109 | if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { 110 | errs = append(errs, err) 111 | } 112 | 113 | // We always need to check not-before, but usage of the claim itself is 114 | // OPTIONAL. 115 | if err = v.verifyNotBefore(claims, now, false); err != nil { 116 | errs = append(errs, err) 117 | } 118 | 119 | // Check issued-at if the option is enabled 120 | if v.verifyIat { 121 | if err = v.verifyIssuedAt(claims, now, false); err != nil { 122 | errs = append(errs, err) 123 | } 124 | } 125 | 126 | // If we have an expected audience, we also require the audience claim 127 | if len(v.expectedAud) > 0 { 128 | if err = v.verifyAudience(claims, v.expectedAud, v.expectAllAud); err != nil { 129 | errs = append(errs, err) 130 | } 131 | } 132 | 133 | // If we have an expected issuer, we also require the issuer claim 134 | if v.expectedIss != "" { 135 | if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { 136 | errs = append(errs, err) 137 | } 138 | } 139 | 140 | // If we have an expected subject, we also require the subject claim 141 | if v.expectedSub != "" { 142 | if err = v.verifySubject(claims, v.expectedSub, true); err != nil { 143 | errs = append(errs, err) 144 | } 145 | } 146 | 147 | // Finally, we want to give the claim itself some possibility to do some 148 | // additional custom validation based on a custom Validate function. 149 | cvt, ok := claims.(ClaimsValidator) 150 | if ok { 151 | if err := cvt.Validate(); err != nil { 152 | errs = append(errs, err) 153 | } 154 | } 155 | 156 | if len(errs) == 0 { 157 | return nil 158 | } 159 | 160 | return joinErrors(errs...) 161 | } 162 | 163 | // verifyExpiresAt compares the exp claim in claims against cmp. This function 164 | // will succeed if cmp < exp. Additional leeway is taken into account. 165 | // 166 | // If exp is not set, it will succeed if the claim is not required, 167 | // otherwise ErrTokenRequiredClaimMissing will be returned. 168 | // 169 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 170 | // the wrong type, an ErrTokenUnverifiable error will be returned. 171 | func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { 172 | exp, err := claims.GetExpirationTime() 173 | if err != nil { 174 | return err 175 | } 176 | 177 | if exp == nil { 178 | return errorIfRequired(required, "exp") 179 | } 180 | 181 | return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) 182 | } 183 | 184 | // verifyIssuedAt compares the iat claim in claims against cmp. This function 185 | // will succeed if cmp >= iat. Additional leeway is taken into account. 186 | // 187 | // If iat is not set, it will succeed if the claim is not required, 188 | // otherwise ErrTokenRequiredClaimMissing will be returned. 189 | // 190 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 191 | // the wrong type, an ErrTokenUnverifiable error will be returned. 192 | func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { 193 | iat, err := claims.GetIssuedAt() 194 | if err != nil { 195 | return err 196 | } 197 | 198 | if iat == nil { 199 | return errorIfRequired(required, "iat") 200 | } 201 | 202 | return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) 203 | } 204 | 205 | // verifyNotBefore compares the nbf claim in claims against cmp. This function 206 | // will return true if cmp >= nbf. Additional leeway is taken into account. 207 | // 208 | // If nbf is not set, it will succeed if the claim is not required, 209 | // otherwise ErrTokenRequiredClaimMissing will be returned. 210 | // 211 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 212 | // the wrong type, an ErrTokenUnverifiable error will be returned. 213 | func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { 214 | nbf, err := claims.GetNotBefore() 215 | if err != nil { 216 | return err 217 | } 218 | 219 | if nbf == nil { 220 | return errorIfRequired(required, "nbf") 221 | } 222 | 223 | return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) 224 | } 225 | 226 | // verifyAudience compares the aud claim against cmp. 227 | // 228 | // If aud is not set or an empty list, it will succeed if the claim is not required, 229 | // otherwise ErrTokenRequiredClaimMissing will be returned. 230 | // 231 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 232 | // the wrong type, an ErrTokenUnverifiable error will be returned. 233 | func (v *Validator) verifyAudience(claims Claims, cmp []string, expectAllAud bool) error { 234 | aud, err := claims.GetAudience() 235 | if err != nil { 236 | return err 237 | } 238 | 239 | // Check that aud exists and is not empty. We only require the aud claim 240 | // if we expect at least one audience to be present. 241 | if len(aud) == 0 || len(aud) == 1 && aud[0] == "" { 242 | required := len(v.expectedAud) > 0 243 | return errorIfRequired(required, "aud") 244 | } 245 | 246 | if !expectAllAud { 247 | for _, a := range aud { 248 | // If we only expect one match, we can stop early if we find a match 249 | if slices.Contains(cmp, a) { 250 | return nil 251 | } 252 | } 253 | 254 | return ErrTokenInvalidAudience 255 | } 256 | 257 | // Note that we are looping cmp here to ensure that all expected audiences 258 | // are present in the aud claim. 259 | for _, a := range cmp { 260 | if !slices.Contains(aud, a) { 261 | return ErrTokenInvalidAudience 262 | } 263 | } 264 | 265 | return nil 266 | } 267 | 268 | // verifyIssuer compares the iss claim in claims against cmp. 269 | // 270 | // If iss is not set, it will succeed if the claim is not required, 271 | // otherwise ErrTokenRequiredClaimMissing will be returned. 272 | // 273 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 274 | // the wrong type, an ErrTokenUnverifiable error will be returned. 275 | func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { 276 | iss, err := claims.GetIssuer() 277 | if err != nil { 278 | return err 279 | } 280 | 281 | if iss == "" { 282 | return errorIfRequired(required, "iss") 283 | } 284 | 285 | return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) 286 | } 287 | 288 | // verifySubject compares the sub claim against cmp. 289 | // 290 | // If sub is not set, it will succeed if the claim is not required, 291 | // otherwise ErrTokenRequiredClaimMissing will be returned. 292 | // 293 | // Additionally, if any error occurs while retrieving the claim, e.g., when its 294 | // the wrong type, an ErrTokenUnverifiable error will be returned. 295 | func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { 296 | sub, err := claims.GetSubject() 297 | if err != nil { 298 | return err 299 | } 300 | 301 | if sub == "" { 302 | return errorIfRequired(required, "sub") 303 | } 304 | 305 | return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) 306 | } 307 | 308 | // errorIfFalse returns the error specified in err, if the value is true. 309 | // Otherwise, nil is returned. 310 | func errorIfFalse(value bool, err error) error { 311 | if value { 312 | return nil 313 | } else { 314 | return err 315 | } 316 | } 317 | 318 | // errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is 319 | // true. Otherwise, nil is returned. 320 | func errorIfRequired(required bool, claim string) error { 321 | if required { 322 | return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) 323 | } else { 324 | return nil 325 | } 326 | } 327 | --------------------------------------------------------------------------------