woodpecker/server/grpc/jwt_manager.go

88 lines
2.4 KiB
Go
Raw Normal View History

// Copyright 2023 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package grpc
import (
"errors"
"fmt"
"time"
fix(deps): update module github.com/golang-jwt/jwt/v4 to v5 (#2449) [![Mend Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com) This PR contains the following updates: | Package | Type | Update | Change | |---|---|---|---| | [github.com/golang-jwt/jwt/v4](https://togithub.com/golang-jwt/jwt) | require | major | `v4.5.0` -> `v5.0.0` | --- ### ⚠ Dependency Lookup Warnings ⚠ Warnings were logged while processing this repo. Please check the Dependency Dashboard for more information. --- ### Release Notes <details> <summary>golang-jwt/jwt (github.com/golang-jwt/jwt/v4)</summary> ### [`v5.0.0`](https://togithub.com/golang-jwt/jwt/releases/tag/v5.0.0) [Compare Source](https://togithub.com/golang-jwt/jwt/compare/v4.5.0...v5.0.0) ### 🚀 New Major Version `v5` 🚀 It's finally here, the release you have been waiting for! We don't take breaking changes lightly, but the changes outlined below were necessary to address some of the challenges of the previous API. A big thanks for [@&#8203;mfridman](https://togithub.com/mfridman) for all the reviews, all contributors for their commits and of course [@&#8203;dgrijalva](https://togithub.com/dgrijalva) for the original code. I hope we kept some of the spirit of your original `v4` branch alive in the approach we have taken here. \~[@&#8203;oxisto](https://togithub.com/oxisto), on behalf of [@&#8203;golang-jwt/maintainers](https://togithub.com/golang-jwt/maintainers) Version `v5` contains a major rework of core functionalities in the `jwt-go` library. This includes support for several validation options as well as a re-design of the `Claims` interface. Lastly, we reworked how errors work under the hood, which should provide a better overall developer experience. Starting from [v5.0.0](https://togithub.com/golang-jwt/jwt/releases/tag/v5.0.0), the import path will be: "github.com/golang-jwt/jwt/v5" For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of the public API, existing programs might need to be updated. The following sections describe significant changes and corresponding updates for existing programs. #### Parsing and Validation Options Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: - Added `WithLeeway` to support specifying the leeway that is allowed when validating time-based claims, such as `exp` or `nbf`. - Changed default behavior to not check the `iat` claim. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. - Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for expected `aud`, `sub` and `iss`. - Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow previously global settings to enable base64 strict encoding and the parsing of base64 strings with padding. The latter is strictly speaking against the standard, but unfortunately some of the major identity providers issue some of these incorrect tokens. Both options are disabled by default. #### Changes to the `Claims` interface ##### Complete Restructuring Previously, the claims interface was satisfied with an implementation of a `Valid() error` function. This had several issues: - The different claim types (struct claims, map claims, etc.) then contained similar (but not 100 % identical) code of how this validation was done. This lead to a lot of (almost) duplicate code and was hard to maintain - It was not really semantically close to what a "claim" (or a set of claims) really is; which is a list of defined key/value pairs with a certain semantic meaning. Since all the validation functionality is now extracted into the validator, all `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. Instead, the interface now represents a list of getters to retrieve values with a specific meaning. This allows us to completely decouple the validation logic with the underlying storage representation of the claim, which could be a struct, a map or even something stored in a database. ```go type Claims interface { GetExpirationTime() (*NumericDate, error) GetIssuedAt() (*NumericDate, error) GetNotBefore() (*NumericDate, error) GetIssuer() (string, error) GetSubject() (string, error) GetAudience() (ClaimStrings, error) } ``` ##### Supported Claim Types and Removal of `StandardClaims` The two standard claim types supported by this library, `MapClaims` and `RegisteredClaims` both implement the necessary functions of this interface. The old `StandardClaims` struct, which has already been deprecated in `v4` is now removed. Users using custom claims, in most cases, will not experience any changes in the behavior as long as they embedded `RegisteredClaims`. If they created a new claim type from scratch, they now need to implemented the proper getter functions. ##### Migrating Application Specific Logic of the old `Valid` Previously, users could override the `Valid` method in a custom claim, for example to extend the validation with application-specific claims. However, this was always very dangerous, since once could easily disable the standard validation and signature checking. In order to avoid that, while still supporting the use-case, a new `ClaimsValidator` interface has been introduced. This interface consists of the `Validate() error` function. If the validator sees, that a `Claims` struct implements this interface, the errors returned to the `Validate` function will be *appended* to the regular standard validation. It is not possible to disable the standard validation anymore (even only by accident). Usage examples can be found in [example_test.go](./example_test.go), to build claims structs like the following. ```go // MyCustomClaims includes all registered claims, plus Foo. type MyCustomClaims struct { Foo string `json:"foo"` jwt.RegisteredClaims } // Validate can be used to execute additional application-specific claims // validation. func (m MyCustomClaims) Validate() error { if m.Foo != "bar" { return errors.New("must be foobar") } return nil } ``` #### Changes to the `Token` and `Parser` struct The previously global functions `DecodeSegment` and `EncodeSegment` were moved to the `Parser` and `Token` struct respectively. This will allow us in the future to configure the behavior of these two based on options supplied on the parser or the token (creation). This also removes two previously global variables and moves them to parser options `WithStrictDecoding` and `WithPaddingAllowed`. In order to do that, we had to adjust the way signing methods work. Previously they were given a base64 encoded signature in `Verify` and were expected to return a base64 encoded version of the signature in `Sign`, both as a `string`. However, this made it necessary to have `DecodeSegment` and `EncodeSegment` global and was a less than perfect design because we were repeating encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` operate on a decoded signature as a `[]byte`, which feels more natural for a cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of the final encoding/decoding part. In addition to that, we also changed the `Signature` field on `Token` from a `string` to `[]byte` and this is also now populated with the decoded form. This is also more consistent, because the other parts of the JWT, mainly `Header` and `Claims` were already stored in decoded form in `Token`. Only the signature was stored in base64 encoded form, which was redundant with the information in the `Raw` field, which contains the complete token as base64. ```go type Token struct { Raw string // Raw contains the raw token Method SigningMethod // Method is the signing method used or to be used Header map[string]interface{} // Header is the first segment of the token in decoded form Claims Claims // Claims is the second segment of the token in decoded form Signature []byte // Signature is the third segment of the token in decoded form Valid bool // Valid specifies if the token is valid } ``` Most (if not all) of these changes should not impact the normal usage of this library. Only users directly accessing the `Signature` field as well as developers of custom signing methods should be affected. #### What's Changed - Added GitHub Actions Markdown by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/260](https://togithub.com/golang-jwt/jwt/pull/260) - Remove `StandardClaims` in favor of `RegisteredClaims` by [@&#8203;oxisto](https://togithub.com/oxisto) in [#&#8203;235](https://togithub.com/golang-jwt/jwt/issues/235) - Adding more coverage by [@&#8203;oxisto](https://togithub.com/oxisto) in [#&#8203;268](https://togithub.com/golang-jwt/jwt/issues/268) - More consistent way of handling validation errors by [@&#8203;oxisto](https://togithub.com/oxisto) in [#&#8203;274](https://togithub.com/golang-jwt/jwt/issues/274) - New Validation API by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/236](https://togithub.com/golang-jwt/jwt/pull/236) - `v5` Pre-Release by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/234](https://togithub.com/golang-jwt/jwt/pull/234) - no need for string slice and call to strings.join by [@&#8203;moneszarrugh](https://togithub.com/moneszarrugh) in [https://github.com/golang-jwt/jwt/pull/115](https://togithub.com/golang-jwt/jwt/pull/115) - Update MIGRATION_GUIDE.md by [@&#8203;liam-verta](https://togithub.com/liam-verta) in [https://github.com/golang-jwt/jwt/pull/289](https://togithub.com/golang-jwt/jwt/pull/289) - Moving `DecodeSegement` to `Parser` by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/278](https://togithub.com/golang-jwt/jwt/pull/278) - Adjusting the error checking example by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/270](https://togithub.com/golang-jwt/jwt/pull/270) - add documentation to hmac `Verify` & `Sign` to detail why string is not an advisable input for key by [@&#8203;dillonstreator](https://togithub.com/dillonstreator) in [https://github.com/golang-jwt/jwt/pull/249](https://togithub.com/golang-jwt/jwt/pull/249) - Add golangci-lint by [@&#8203;mfridman](https://togithub.com/mfridman) in [https://github.com/golang-jwt/jwt/pull/279](https://togithub.com/golang-jwt/jwt/pull/279) - Added dependabot updates for GitHub actions by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/298](https://togithub.com/golang-jwt/jwt/pull/298) - Bump actions/checkout from 2 to 3 by [@&#8203;dependabot](https://togithub.com/dependabot) in [https://github.com/golang-jwt/jwt/pull/299](https://togithub.com/golang-jwt/jwt/pull/299) - Bump actions/setup-go from 3 to 4 by [@&#8203;dependabot](https://togithub.com/dependabot) in [https://github.com/golang-jwt/jwt/pull/300](https://togithub.com/golang-jwt/jwt/pull/300) - Added coverage reporting by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/304](https://togithub.com/golang-jwt/jwt/pull/304) - Last Documentation cleanups for `v5` release by [@&#8203;oxisto](https://togithub.com/oxisto) in [https://github.com/golang-jwt/jwt/pull/291](https://togithub.com/golang-jwt/jwt/pull/291) - enable jwt.ParsePublicKeyFromPEM to parse PKCS1 Public Key by [@&#8203;twocs](https://togithub.com/twocs) in [https://github.com/golang-jwt/jwt/pull/120](https://togithub.com/golang-jwt/jwt/pull/120) #### New Contributors - [@&#8203;moneszarrugh](https://togithub.com/moneszarrugh) made their first contribution in [https://github.com/golang-jwt/jwt/pull/115](https://togithub.com/golang-jwt/jwt/pull/115) - [@&#8203;liam-verta](https://togithub.com/liam-verta) made their first contribution in [https://github.com/golang-jwt/jwt/pull/289](https://togithub.com/golang-jwt/jwt/pull/289) - [@&#8203;dillonstreator](https://togithub.com/dillonstreator) made their first contribution in [https://github.com/golang-jwt/jwt/pull/249](https://togithub.com/golang-jwt/jwt/pull/249) - [@&#8203;dependabot](https://togithub.com/dependabot) made their first contribution in [https://github.com/golang-jwt/jwt/pull/299](https://togithub.com/golang-jwt/jwt/pull/299) - [@&#8203;twocs](https://togithub.com/twocs) made their first contribution in [https://github.com/golang-jwt/jwt/pull/120](https://togithub.com/golang-jwt/jwt/pull/120) **Full Changelog**: https://github.com/golang-jwt/jwt/compare/v4.5.0...v5.0.0 </details> --- ### Configuration 📅 **Schedule**: Branch creation - At any time (no schedule defined), Automerge - At any time (no schedule defined). 🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied. ♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate](https://www.mend.io/free-developer-tools/renovate/). View repository job log [here](https://developer.mend.io/github/woodpecker-ci/woodpecker). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNi44My4wIiwidXBkYXRlZEluVmVyIjoiMzYuODMuMCIsInRhcmdldEJyYW5jaCI6Im1haW4ifQ==--> --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: qwerty287 <ndev@web.de>
2023-09-13 07:01:01 +00:00
"github.com/golang-jwt/jwt/v5"
)
// JWTManager is a JSON web token manager.
type JWTManager struct {
secretKey string
tokenDuration time.Duration
}
// UserClaims is a custom JWT claims that contains some user's information.
type AgentTokenClaims struct {
jwt.RegisteredClaims
AgentID int64 `json:"agent_id"`
}
const jwtTokenDuration = 1 * time.Hour
// NewJWTManager returns a new JWT manager.
func NewJWTManager(secretKey string) *JWTManager {
return &JWTManager{secretKey, jwtTokenDuration}
}
// Generate generates and signs a new token for a user.
func (manager *JWTManager) Generate(agentID int64) (string, error) {
claims := AgentTokenClaims{
RegisteredClaims: jwt.RegisteredClaims{
Issuer: "woodpecker",
Subject: fmt.Sprintf("%d", agentID),
Audience: jwt.ClaimStrings{},
NotBefore: jwt.NewNumericDate(time.Now()),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: fmt.Sprintf("%d", agentID),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(manager.tokenDuration)),
},
AgentID: agentID,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(manager.secretKey))
}
// Verify verifies the access token string and return a user claim if the token is valid.
func (manager *JWTManager) Verify(accessToken string) (*AgentTokenClaims, error) {
token, err := jwt.ParseWithClaims(
accessToken,
&AgentTokenClaims{},
func(token *jwt.Token) (any, error) {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, errors.New("unexpected token signing method")
}
return []byte(manager.secretKey), nil
},
)
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
claims, ok := token.Claims.(*AgentTokenClaims)
if !ok {
return nil, errors.New("invalid token claims")
}
return claims, nil
}