From 688a0f9b3e60e2c43fcd68e0b3e4565b4bccb92a Mon Sep 17 00:00:00 2001 From: Dean Sheather Date: Mon, 30 Nov 2026 21:23:42 +1100 Subject: [PATCH] refactor: use go-jose for all JWT handling (#31931) Closes ENG-1510. First-party code used two JWT libraries: `go-jose/v4` (workspace apps, jwtutils, tailnet resume, agent hooks, chats) and `golang-jwt/jwt/v4` (licenses, Azure OIDC PKI, test signers, and `jwt.MapClaims` in idpsync). This moves everything to go-jose and removes `golang-jwt/jwt/v4` from `go.mod`. - `enterprise/coderd/license`: verification uses `jwt.ParseSigned` with an EdDSA allowlist and `kid` lookup. Time claims are validated with zero leeway, matching golang-jwt's previous behavior instead of go-jose's 1 minute default. `ParseClaimsIgnoreNbf` still returns `ErrMultipleIssues` for any verification or time-claim failure other than `nbf`. `Claims` now embeds `jwtutils.RegisteredClaims`, so `ExpiresAt` becomes `Expiry` and `NumericDate` uses `.Time()`. - `coderd/oauthpki`: the Azure client assertion is signed with go-jose and keeps the `typ: JWT` and `x5t` headers that the existing test asserts. - Test helpers (`coderdtest`, `oidctest`, `coderdenttest`) sign with go-jose. - `jwt.MapClaims` is replaced with `map[string]any`. No callers used its methods. - A depguard rule (`single_jwt_library`) rejects new `github.com/golang-jwt/jwt` imports. `golang-jwt/jwt/v5` stays as an indirect dependency through `SherClockHolmes/webpush-go`.
Decision log - **Why go-jose over golang-jwt:** `coderd/jwtutils/jwe.go` needs JWE, which golang-jwt doesn't support, so only go-jose can be the single library. go-jose was already used for the more security-sensitive token paths, and `coreos/go-oidc` depends on it anyway. Its `ParseSigned` requires an explicit algorithm allowlist. Moving the golang-jwt usages, which were mostly `MapClaims`, was the smaller change. - **Expiry edge case:** golang-jwt treated a license as expired at `now >= exp`, and go-jose treats it as expired at `now > exp`. With whole-second timestamps the difference is at most one second. - **Not evaluated:** a comparison of CVE history or maintenance pace between the two libraries.
Validation: `make pre-commit`. Tests: `enterprise/coderd/license`, `enterprise/coderd` (license, trial, OIDC, and sync tests), `enterprise/trialer`, `enterprise/coderd/usage`, `enterprise/coderd/enidpsync`, `coderd/oauthpki`, `coderd/idpsync`, `coderd/coderdtest/oidctest`, `coderd` (OIDC, login, Google instance identity, and OAuth2 tests), `coderd/externalauth`, `coderd/provisionerdserver`, `cli`. I confirmed the depguard rule flags a `golang-jwt/jwt/v5` import. > Generated with Coder Agents on behalf of @deansheather. --- .golangci.yaml | 5 + cli/useroidcclaims_test.go | 11 +- coderd/coderdtest/coderdtest.go | 14 +- coderd/coderdtest/oidctest/helper.go | 7 +- coderd/coderdtest/oidctest/idp.go | 61 +++--- coderd/coderdtest/oidctest/idp_test.go | 5 +- coderd/externalauth/externalauth_test.go | 53 +++-- coderd/idpsync/group.go | 7 +- coderd/idpsync/group_test.go | 15 +- coderd/idpsync/idpsync.go | 7 +- coderd/idpsync/organization.go | 7 +- coderd/idpsync/organizations_test.go | 3 +- coderd/idpsync/role.go | 7 +- coderd/idpsync/role_test.go | 5 +- coderd/oauthpki/oidcpki.go | 18 +- coderd/oauthpki/okidcpki_test.go | 16 +- .../provisionerdserver_test.go | 5 +- coderd/userauth_test.go | 149 +++++++------ coderd/users_test.go | 3 +- .../coderd/coderdenttest/coderdenttest.go | 19 +- enterprise/coderd/enidpsync/groups.go | 4 +- enterprise/coderd/enidpsync/groups_test.go | 9 +- enterprise/coderd/enidpsync/organizations.go | 4 +- .../coderd/enidpsync/organizations_test.go | 17 +- enterprise/coderd/enidpsync/role.go | 3 +- enterprise/coderd/enidpsync/role_test.go | 13 +- enterprise/coderd/license/license.go | 197 +++++++++--------- enterprise/coderd/licenses.go | 9 +- enterprise/coderd/usage/publisher.go | 2 +- enterprise/coderd/userauth_test.go | 81 ++++--- go.mod | 1 - go.sum | 2 - scripts/testidp/main.go | 5 +- 33 files changed, 383 insertions(+), 381 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index d2a19a87c92..96b6b376df5 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -55,6 +55,11 @@ linters: deny: - pkg: log/slog desc: use cdr.dev/slog/v3 instead + single_jwt_library: + list-mode: lax + deny: + - pkg: github.com/golang-jwt/jwt + desc: use github.com/go-jose/go-jose/v4 so JWTs are handled by a single library dupl: threshold: 412 exhaustruct: diff --git a/cli/useroidcclaims_test.go b/cli/useroidcclaims_test.go index b5513e0b198..b87bfdc08e9 100644 --- a/cli/useroidcclaims_test.go +++ b/cli/useroidcclaims_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -40,7 +39,7 @@ func TestUserOIDCClaims(t *testing.T) { t.Parallel() fake, ownerClient := newOIDCTest(t) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -68,7 +67,7 @@ func TestUserOIDCClaims(t *testing.T) { t.Parallel() fake, ownerClient := newOIDCTest(t) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "bob@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -110,7 +109,7 @@ func TestUserOIDCClaims(t *testing.T) { t.Parallel() aliceFake, aliceOwnerClient := newOIDCTest(t) - aliceClaims := jwt.MapClaims{ + aliceClaims := map[string]any{ "email": "alice-isolation@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -119,7 +118,7 @@ func TestUserOIDCClaims(t *testing.T) { defer aliceLoginResp.Body.Close() bobFake, bobOwnerClient := newOIDCTest(t) - bobClaims := jwt.MapClaims{ + bobClaims := map[string]any{ "email": "bob-isolation@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -145,7 +144,7 @@ func TestUserOIDCClaims(t *testing.T) { fake, ownerClient := newOIDCTest(t) // Use minimal claims — just enough for OIDC login. - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "minimal@coder.com", "email_verified": true, "sub": uuid.NewString(), diff --git a/coderd/coderdtest/coderdtest.go b/coderd/coderdtest/coderdtest.go index 2fd22a7051b..efb6292b61b 100644 --- a/coderd/coderdtest/coderdtest.go +++ b/coderd/coderdtest/coderdtest.go @@ -34,7 +34,8 @@ import ( "cloud.google.com/go/compute/metadata" "github.com/go-chi/chi/v5" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "github.com/nats-io/nats-server/v2/server" "github.com/prometheus/client_golang/prometheus" @@ -1623,7 +1624,7 @@ func RequestExternalAuthCallback(t testing.TB, providerID string, client *coders func NewGoogleInstanceIdentity(t testing.TB, instanceID string, expired bool, audience string) (*idtoken.Validator, *metadata.Client) { keyID, err := cryptorand.String(12) require.NoError(t, err) - claims := jwt.MapClaims{ + claims := map[string]any{ "aud": audience, "google": map[string]interface{}{ "compute_engine": map[string]string{ @@ -1634,11 +1635,14 @@ func NewGoogleInstanceIdentity(t testing.TB, instanceID string, expired bool, au if !expired { claims["exp"] = time.Now().AddDate(1, 0, 0).Unix() } - token := jwt.NewWithClaims(jwt.SigningMethodRS256, claims) - token.Header["kid"] = keyID privateKey, err := rsa.GenerateKey(rand.Reader, 2048) require.NoError(t, err) - signedKey, err := token.SignedString(privateKey) + signer, err := jose.NewSigner(jose.SigningKey{ + Algorithm: jose.RS256, + Key: privateKey, + }, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", keyID)) + require.NoError(t, err) + signedKey, err := jwt.Signed(signer).Claims(claims).Serialize() require.NoError(t, err) // Taken from: https://github.com/googleapis/google-api-go-client/blob/4bb729045d611fa77bdbeb971f6a1204ba23161d/idtoken/validate.go#L57-L75 diff --git a/coderd/coderdtest/oidctest/helper.go b/coderd/coderdtest/oidctest/helper.go index 16b46ac662b..94e27ae6982 100644 --- a/coderd/coderdtest/oidctest/helper.go +++ b/coderd/coderdtest/oidctest/helper.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/require" "golang.org/x/xerrors" @@ -43,7 +42,7 @@ func NewLoginHelper(client *codersdk.Client, fake *FakeIDP) *LoginHelper { // Login just helps by making an unauthenticated client and logging in with // the given claims. All Logins should be unauthenticated, so this is a // convenience method. -func (h *LoginHelper) Login(t *testing.T, idTokenClaims jwt.MapClaims) (*codersdk.Client, *http.Response) { +func (h *LoginHelper) Login(t *testing.T, idTokenClaims map[string]any) (*codersdk.Client, *http.Response) { t.Helper() unauthenticatedClient := codersdk.New(h.client.URL) @@ -51,7 +50,7 @@ func (h *LoginHelper) Login(t *testing.T, idTokenClaims jwt.MapClaims) (*codersd } // AttemptLogin does not assert a successful login. -func (h *LoginHelper) AttemptLogin(t *testing.T, idTokenClaims jwt.MapClaims) (*codersdk.Client, *http.Response) { +func (h *LoginHelper) AttemptLogin(t *testing.T, idTokenClaims map[string]any) (*codersdk.Client, *http.Response) { t.Helper() unauthenticatedClient := codersdk.New(h.client.URL) @@ -100,7 +99,7 @@ func (*LoginHelper) ExpireOauthToken(t *testing.T, db database.Store, user *code // the API Key middleware to refresh the oauth token. // // A unit test assertion makes sure the refresh token is used. -func (h *LoginHelper) ForceRefresh(t *testing.T, db database.Store, user *codersdk.Client, idToken jwt.MapClaims) { +func (h *LoginHelper) ForceRefresh(t *testing.T, db database.Store, user *codersdk.Client, idToken map[string]any) { t.Helper() link := h.ExpireOauthToken(t, db, user) diff --git a/coderd/coderdtest/oidctest/idp.go b/coderd/coderdtest/oidctest/idp.go index 2329f6427f3..0dce24c9a88 100644 --- a/coderd/coderdtest/oidctest/idp.go +++ b/coderd/coderdtest/oidctest/idp.go @@ -27,7 +27,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/go-chi/chi/v5" "github.com/go-jose/go-jose/v4" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" @@ -190,8 +190,8 @@ type FakeIDP struct { // Refresh Token -> Email refreshTokensUsed *syncmap.Map[string, bool] refreshTokens *syncmap.Map[string, string] - stateToIDTokenClaims *syncmap.Map[string, jwt.MapClaims] - refreshIDTokenClaims *syncmap.Map[string, jwt.MapClaims] + stateToIDTokenClaims *syncmap.Map[string, map[string]any] + refreshIDTokenClaims *syncmap.Map[string, map[string]any] // Device flow deviceCode *syncmap.Map[string, deviceFlow] @@ -203,13 +203,13 @@ type FakeIDP struct { // IDP -> Application. Almost all IDPs have the concept of // "Authorized Redirect URLs". This can be used to emulate that. hookValidRedirectURL func(redirectURL string) error - hookUserInfo func(email string) (jwt.MapClaims, error) + hookUserInfo func(email string) (map[string]any, error) hookRevokeToken HookRevokeTokenFn revokeTokenGitHubFormat bool // GitHub doesn't follow token revocation RFC spec - hookAccessTokenJWT func(email string, exp time.Time) jwt.MapClaims + hookAccessTokenJWT func(email string, exp time.Time) map[string]any // defaultIDClaims is if a new client connects and we didn't preset // some claims. - defaultIDClaims jwt.MapClaims + defaultIDClaims map[string]any hookMutateToken func(token map[string]interface{}) hookOnRefresh func(email string) error // Custom authentication for the client. This is useful if you want @@ -256,7 +256,7 @@ func WithMiddlewares(mws ...func(http.Handler) http.Handler) func(*FakeIDP) { } } -func WithAccessTokenJWTHook(hook func(email string, exp time.Time) jwt.MapClaims) func(*FakeIDP) { +func WithAccessTokenJWTHook(hook func(email string, exp time.Time) map[string]any) func(*FakeIDP) { return func(f *FakeIDP) { f.hookAccessTokenJWT = hook } @@ -328,9 +328,9 @@ func WithLogger(logger slog.Logger) func(*FakeIDP) { // WithStaticUserInfo is optional, but will return the same user info for // every user on the /userinfo endpoint. -func WithStaticUserInfo(info jwt.MapClaims) func(*FakeIDP) { +func WithStaticUserInfo(info map[string]any) func(*FakeIDP) { return func(f *FakeIDP) { - f.hookUserInfo = func(_ string) (jwt.MapClaims, error) { + f.hookUserInfo = func(_ string) (map[string]any, error) { return info, nil } } @@ -349,13 +349,13 @@ func WithRevokeTokenGitHub(revokeFunc HookRevokeTokenFn) func(*FakeIDP) { } } -func WithDefaultIDClaims(claims jwt.MapClaims) func(*FakeIDP) { +func WithDefaultIDClaims(claims map[string]any) func(*FakeIDP) { return func(f *FakeIDP) { f.defaultIDClaims = claims } } -func WithDynamicUserInfo(userInfoFunc func(email string) (jwt.MapClaims, error)) func(*FakeIDP) { +func WithDynamicUserInfo(userInfoFunc func(email string) (map[string]any, error)) func(*FakeIDP) { return func(f *FakeIDP) { f.hookUserInfo = userInfoFunc } @@ -468,11 +468,11 @@ func NewFakeIDP(t testing.TB, opts ...FakeIDPOpt) *FakeIDP { accessTokens: syncmap.New[string, token](), refreshTokens: syncmap.New[string, string](), refreshTokensUsed: syncmap.New[string, bool](), - stateToIDTokenClaims: syncmap.New[string, jwt.MapClaims](), - refreshIDTokenClaims: syncmap.New[string, jwt.MapClaims](), + stateToIDTokenClaims: syncmap.New[string, map[string]any](), + refreshIDTokenClaims: syncmap.New[string, map[string]any](), deviceCode: syncmap.New[string, deviceFlow](), hookOnRefresh: func(_ string) error { return nil }, - hookUserInfo: func(_ string) (jwt.MapClaims, error) { return jwt.MapClaims{}, nil }, + hookUserInfo: func(_ string) (map[string]any, error) { return map[string]any{}, nil }, hookValidRedirectURL: func(_ string) error { return nil }, defaultExpire: time.Minute * 5, } @@ -569,7 +569,7 @@ func (f *FakeIDP) realServer(t testing.TB) *httptest.Server { // GenerateAuthenticatedToken skips all oauth2 flows, and just generates a // valid token for some given claims. -func (f *FakeIDP) GenerateAuthenticatedToken(claims jwt.MapClaims) (*oauth2.Token, error) { +func (f *FakeIDP) GenerateAuthenticatedToken(claims map[string]any) (*oauth2.Token, error) { state := uuid.NewString() f.stateToIDTokenClaims.Store(state, claims) @@ -589,7 +589,7 @@ func (f *FakeIDP) GenerateAuthenticatedToken(claims jwt.MapClaims) (*oauth2.Toke // // The client passed in is just to get the url of the Coder instance. // The actual client that is used is 100% unauthenticated and fresh. -func (f *FakeIDP) Login(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { +func (f *FakeIDP) Login(t testing.TB, client *codersdk.Client, idTokenClaims map[string]any, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { t.Helper() client, resp := f.AttemptLogin(t, client, idTokenClaims, opts...) @@ -603,7 +603,7 @@ func (f *FakeIDP) Login(t testing.TB, client *codersdk.Client, idTokenClaims jwt return client, resp } -func (f *FakeIDP) AttemptLogin(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { +func (f *FakeIDP) AttemptLogin(t testing.TB, client *codersdk.Client, idTokenClaims map[string]any, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { t.Helper() var err error @@ -625,7 +625,7 @@ func (f *FakeIDP) AttemptLogin(t testing.TB, client *codersdk.Client, idTokenCla // cookies will be used. This should be an unauthenticated client in most cases. // // This is a niche case, but it is needed for testing ConvertLoginType. -func (f *FakeIDP) LoginWithClient(t testing.TB, client *codersdk.Client, idTokenClaims jwt.MapClaims, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { +func (f *FakeIDP) LoginWithClient(t testing.TB, client *codersdk.Client, idTokenClaims map[string]any, opts ...func(r *http.Request)) (*codersdk.Client, *http.Response) { t.Helper() path := "/api/v2/users/oidc/callback" if f.callbackPath != "" { @@ -699,7 +699,7 @@ func (f *FakeIDP) ExternalLogin(t testing.TB, client *codersdk.Client, opts ...c // Store the idTokenClaims to the specific state request. This ties // the claims 1:1 with a given authentication flow. state := req.URL.Query().Get("state") - f.stateToIDTokenClaims.Store(state, jwt.MapClaims{}) + f.stateToIDTokenClaims.Store(state, map[string]any{}) return nil } @@ -756,7 +756,7 @@ func (*FakeIDP) DeviceLogin(t testing.TB, client *codersdk.Client, externalAuthI func (f *FakeIDP) CreateAuthCode(t testing.TB, state string) string { // We need to store some claims, because this is also an OIDC provider, and // it expects some claims to be present. - f.stateToIDTokenClaims.Store(state, jwt.MapClaims{}) + f.stateToIDTokenClaims.Store(state, map[string]any{}) code, err := OAuth2GetCode(f.locked.Config().AuthCodeURL(state), func(req *http.Request) (*http.Response, error) { rw := httptest.NewRecorder() @@ -773,7 +773,7 @@ func (f *FakeIDP) CreateAuthCode(t testing.TB, state string) string { // something. // Essentially this is used to fake the Coderd side of the exchange. // The flow starts at the user hitting the OIDC login page. -func (f *FakeIDP) OIDCCallback(t testing.TB, state string, idTokenClaims jwt.MapClaims) *http.Response { +func (f *FakeIDP) OIDCCallback(t testing.TB, state string, idTokenClaims map[string]any) *http.Response { t.Helper() if f.serve { panic("cannot use OIDCCallback with WithServing. This is only for the in memory usage") @@ -897,7 +897,7 @@ func (f *FakeIDP) authenticateOIDCClientRequest(t testing.TB, req *http.Request) } // encodeClaims is a helper func to convert claims to a valid JWT. -func (f *FakeIDP) encodeClaims(t testing.TB, claims jwt.MapClaims) string { +func (f *FakeIDP) encodeClaims(t testing.TB, claims map[string]any) string { t.Helper() if _, ok := claims["exp"]; !ok { @@ -923,7 +923,12 @@ func (f *FakeIDP) encodeClaims(t testing.TB, claims jwt.MapClaims) string { } } - signed, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).SignedString(f.locked.PrivateKey()) + signer, err := jose.NewSigner(jose.SigningKey{ + Algorithm: jose.RS256, + Key: f.locked.PrivateKey(), + }, (&jose.SignerOptions{}).WithType("JWT")) + require.NoError(t, err) + signed, err := jwt.Signed(signer).Claims(claims).Serialize() require.NoError(t, err) return signed @@ -1041,7 +1046,7 @@ func (f *FakeIDP) httpHandler(t testing.TB) http.Handler { httpError(rw, http.StatusBadRequest, err) return } - getEmail := func(claims jwt.MapClaims) string { + getEmail := func(claims map[string]any) string { email, ok := claims["email"] if !ok { return "unknown" @@ -1053,7 +1058,7 @@ func (f *FakeIDP) httpHandler(t testing.TB) http.Handler { return emailStr } - var claims jwt.MapClaims + var claims map[string]any switch values.Get("grant_type") { case "authorization_code": code := values.Get("code") @@ -1156,7 +1161,7 @@ func (f *FakeIDP) httpHandler(t testing.TB) http.Handler { } // Would be nice to get an actual email here. - claims = jwt.MapClaims{ + claims = map[string]any{ "email": "unknown-dev-auth", } default: @@ -1506,7 +1511,7 @@ func (f *FakeIDP) RefreshUsed(refreshToken string) bool { // UpdateRefreshClaims allows the caller to change what claims are returned // for a given refresh token. By default, all refreshes use the same claims as // the original IDToken issuance. -func (f *FakeIDP) UpdateRefreshClaims(refreshToken string, claims jwt.MapClaims) { +func (f *FakeIDP) UpdateRefreshClaims(refreshToken string, claims map[string]any) { // no mutex because it's a sync.Map f.refreshIDTokenClaims.Store(refreshToken, claims) } @@ -1737,7 +1742,7 @@ func (f *FakeIDP) internalOIDCConfig(ctx context.Context, t testing.TB, scopes [ return cfg } -func (f *FakeIDP) getClaims(m *syncmap.Map[string, jwt.MapClaims], key string) (jwt.MapClaims, bool) { +func (f *FakeIDP) getClaims(m *syncmap.Map[string, map[string]any], key string) (map[string]any, bool) { v, ok := m.Load(key) if !ok || v == nil { if f.defaultIDClaims != nil { diff --git a/coderd/coderdtest/oidctest/idp_test.go b/coderd/coderdtest/oidctest/idp_test.go index 622dd7b0137..8ac3e9d34f8 100644 --- a/coderd/coderdtest/oidctest/idp_test.go +++ b/coderd/coderdtest/oidctest/idp_test.go @@ -8,7 +8,6 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" @@ -51,7 +50,7 @@ func TestFakeIDPBasicFlow(t *testing.T) { }) //nolint:bodyclose - resp := fake.OIDCCallback(t, expectedState, jwt.MapClaims{}) + resp := fake.OIDCCallback(t, expectedState, map[string]any{}) require.Equal(t, http.StatusOK, resp.StatusCode) // Test the user info @@ -81,7 +80,7 @@ func TestIDPIssuerMismatch(t *testing.T) { fake := oidctest.NewFakeIDP(t, oidctest.WithIssuer(proxyURL), - oidctest.WithDefaultIDClaims(jwt.MapClaims{ + oidctest.WithDefaultIDClaims(map[string]any{ "iss": primaryURL, }), oidctest.WithHookWellKnown(func(r *http.Request, j *oidctest.ProviderJSON) error { diff --git a/coderd/externalauth/externalauth_test.go b/coderd/externalauth/externalauth_test.go index 1001668dce3..dc63eb3658e 100644 --- a/coderd/externalauth/externalauth_test.go +++ b/coderd/externalauth/externalauth_test.go @@ -18,7 +18,6 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/lib/pq" "github.com/prometheus/client_golang/prometheus" @@ -129,7 +128,7 @@ func TestRefreshToken(t *testing.T) { }), // The IDP should not be contacted since the token is expired. An expired // token with 'NoRefresh' should early abort. - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { t.Error("token was validated, but it was expired and this should never have happened.") return nil, xerrors.New("should not be called") }), @@ -166,9 +165,9 @@ func TestRefreshToken(t *testing.T) { t.Error("refresh on the IDP was called, but NoRefresh was set") return xerrors.New("should not be called") }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validated = true - return jwt.MapClaims{}, nil + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -222,9 +221,9 @@ func TestRefreshToken(t *testing.T) { validated := false fake, config, link := setupOauth2Test(t, testConfig{ FakeIDPOpts: []oidctest.FakeIDPOpt{ - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validated = true - return jwt.MapClaims{}, xerrors.New(staticError) + return map[string]any{}, xerrors.New(staticError) }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -269,7 +268,7 @@ func TestRefreshToken(t *testing.T) { }), // The IDP should not be contacted since the token is expired and // refresh attempts will fail. - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { t.Error("token was validated, but it was expired and this should never have happened.") return nil, xerrors.New("should not be called") }), @@ -612,8 +611,8 @@ func TestRefreshToken(t *testing.T) { } return xerrors.New("should not reach this") }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { - return jwt.MapClaims{}, nil + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -761,9 +760,9 @@ func TestRefreshToken(t *testing.T) { validated := false fake, config, link := setupOauth2Test(t, testConfig{ FakeIDPOpts: []oidctest.FakeIDPOpt{ - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validated = true - return jwt.MapClaims{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError)) + return map[string]any{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError)) }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -794,13 +793,13 @@ func TestRefreshToken(t *testing.T) { t.Error("refresh on the IDP was called, but the token is not expired") return xerrors.New("should not be called") }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validateCalls++ // Make the first call return a 401, subsequent calls should return a 200. if validateCalls > 1 { - return jwt.MapClaims{}, nil + return map[string]any{}, nil } - return jwt.MapClaims{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError)) + return map[string]any{}, oidctest.StatusError(http.StatusUnauthorized, xerrors.New(staticError)) }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -832,9 +831,9 @@ func TestRefreshToken(t *testing.T) { t.Error("refresh on the IDP was called, but the token is not expired") return xerrors.New("should not be called") }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validateCalls++ - return jwt.MapClaims{}, nil + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -865,9 +864,9 @@ func TestRefreshToken(t *testing.T) { refreshCalls++ return nil }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { validateCalls++ - return jwt.MapClaims{}, nil + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -951,11 +950,11 @@ func TestRefreshToken(t *testing.T) { refreshCalls.Add(1) return nil }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { if simulateRateLimit.Load() { - return jwt.MapClaims{}, oidctest.StatusError(http.StatusForbidden, xerrors.New("rate limit exceeded")) + return map[string]any{}, oidctest.StatusError(http.StatusForbidden, xerrors.New("rate limit exceeded")) } - return jwt.MapClaims{}, nil + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -1025,8 +1024,8 @@ func TestRefreshToken(t *testing.T) { cancel() return nil }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { - return jwt.MapClaims{}, nil + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -1402,8 +1401,8 @@ func TestRefreshToken(t *testing.T) { <-wait return nil }), - oidctest.WithDynamicUserInfo(func(_ string) (jwt.MapClaims, error) { - return jwt.MapClaims{}, nil + oidctest.WithDynamicUserInfo(func(_ string) (map[string]any, error) { + return map[string]any{}, nil }), }, ExternalAuthOpt: func(cfg *externalauth.Config) { @@ -2288,7 +2287,7 @@ func TestConstantQueryParams(t *testing.T) { // Actually run an auth request. Although it says OIDC, the flow is the same // for oauth2. //nolint:bodyclose - resp := fake.OIDCCallback(t, state, jwt.MapClaims{}) + resp := fake.OIDCCallback(t, state, map[string]any{}) require.True(t, callbackCalled) require.Equal(t, http.StatusOK, resp.StatusCode) } @@ -2337,7 +2336,7 @@ func setupOauth2Test(t *testing.T, settings testConfig) (*oidctest.FakeIDP, *ext } settings.ExternalAuthOpt(config) - oauthToken, err := fake.GenerateAuthenticatedToken(jwt.MapClaims{ + oauthToken, err := fake.GenerateAuthenticatedToken(map[string]any{ "email": "test@coder.com", }) require.NoError(t, err) diff --git a/coderd/idpsync/group.go b/coderd/idpsync/group.go index b9ec9fe2d4a..e844d5dd61d 100644 --- a/coderd/idpsync/group.go +++ b/coderd/idpsync/group.go @@ -6,7 +6,6 @@ import ( "fmt" "net/http" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -21,7 +20,7 @@ import ( type GroupParams struct { // SyncEntitled if false will skip syncing the user's groups SyncEntitled bool - MergedClaims jwt.MapClaims + MergedClaims map[string]any } func (AGPLIDPSync) GroupSyncEntitled() bool { @@ -70,7 +69,7 @@ func (s AGPLIDPSync) GroupSyncSettings(ctx context.Context, orgID uuid.UUID, db return settings, nil } -func (s AGPLIDPSync) ParseGroupClaims(_ context.Context, mergedClaims jwt.MapClaims) (GroupParams, *HTTPError) { +func (s AGPLIDPSync) ParseGroupClaims(_ context.Context, mergedClaims map[string]any) (GroupParams, *HTTPError) { if s.GroupField != "" && len(s.GroupAllowList) > 0 { groupsRaw, ok := mergedClaims[s.GroupField] if !ok { @@ -391,7 +390,7 @@ func (a ExpectedGroup) Equal(b ExpectedGroup) bool { // the group "UUID 1234" is renamed, we want to maintain the mapping. // We have to keep names because group sync supports syncing groups by name if // the external IDP group name matches the Coder one. -func (s GroupSyncSettings) ParseClaims(orgID uuid.UUID, mergedClaims jwt.MapClaims) ([]ExpectedGroup, error) { +func (s GroupSyncSettings) ParseClaims(orgID uuid.UUID, mergedClaims map[string]any) ([]ExpectedGroup, error) { groupsRaw, ok := mergedClaims[s.Field] if !ok { return []ExpectedGroup{}, nil diff --git a/coderd/idpsync/group_test.go b/coderd/idpsync/group_test.go index f17f2dfb3b7..a51922ef78e 100644 --- a/coderd/idpsync/group_test.go +++ b/coderd/idpsync/group_test.go @@ -7,7 +7,6 @@ import ( "slices" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/require" "golang.org/x/xerrors" @@ -37,7 +36,7 @@ func TestParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) - params, err := s.ParseGroupClaims(ctx, jwt.MapClaims{}) + params, err := s.ParseGroupClaims(ctx, map[string]any{}) require.Nil(t, err) require.False(t, params.SyncEntitled) @@ -58,14 +57,14 @@ func TestParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) // Invalid group - _, err := s.ParseGroupClaims(ctx, jwt.MapClaims{ + _, err := s.ParseGroupClaims(ctx, map[string]any{ "groups": []string{"bar"}, }) require.NotNil(t, err) require.Equal(t, 403, err.Code) // No groups - _, err = s.ParseGroupClaims(ctx, jwt.MapClaims{}) + _, err = s.ParseGroupClaims(ctx, map[string]any{}) require.NotNil(t, err) require.Equal(t, 403, err.Code) }) @@ -84,7 +83,7 @@ func TestParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) - claims := jwt.MapClaims{ + claims := map[string]any{ "groups": []string{"foo", "bar"}, } params, err := s.ParseGroupClaims(ctx, claims) @@ -97,7 +96,7 @@ func TestParseGroupClaims(t *testing.T) { func TestGroupSyncTable(t *testing.T) { t.Parallel() - userClaims := jwt.MapClaims{ + userClaims := map[string]any{ "groups": []string{ "foo", "bar", "baz", "create-bar", "create-baz", @@ -438,7 +437,7 @@ func TestSyncDisabled(t *testing.T) { // Do the group sync! err := s.SyncGroups(ctx, db, user, idpsync.GroupParams{ SyncEntitled: false, - MergedClaims: jwt.MapClaims{ + MergedClaims: map[string]any{ "groups": []string{"baz", "bop"}, }, }) @@ -600,7 +599,7 @@ func TestSyncGroupsOutsideOrganization(t *testing.T) { err := s.SyncGroups(ctx, db, user, idpsync.GroupParams{ SyncEntitled: true, - MergedClaims: jwt.MapClaims{"groups": []string{"x"}}, + MergedClaims: map[string]any{"groups": []string{"x"}}, }) require.NoError(t, err) diff --git a/coderd/idpsync/idpsync.go b/coderd/idpsync/idpsync.go index 8153bf80aac..891b6e4dfc4 100644 --- a/coderd/idpsync/idpsync.go +++ b/coderd/idpsync/idpsync.go @@ -6,7 +6,6 @@ import ( "regexp" "strings" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -32,7 +31,7 @@ type IDPSync interface { OrganizationSyncEnabled(ctx context.Context, db database.Store) bool // ParseOrganizationClaims takes claims from an OIDC provider, and returns the // organization sync params for assigning users into organizations. - ParseOrganizationClaims(ctx context.Context, mergedClaims jwt.MapClaims) (OrganizationParams, *HTTPError) + ParseOrganizationClaims(ctx context.Context, mergedClaims map[string]any) (OrganizationParams, *HTTPError) // SyncOrganizations assigns and removed users from organizations based on the // provided params. SyncOrganizations(ctx context.Context, tx database.Store, user database.User, params OrganizationParams) error @@ -40,7 +39,7 @@ type IDPSync interface { GroupSyncEntitled() bool // ParseGroupClaims takes claims from an OIDC provider, and returns the params // for group syncing. Most of the logic happens in SyncGroups. - ParseGroupClaims(ctx context.Context, mergedClaims jwt.MapClaims) (GroupParams, *HTTPError) + ParseGroupClaims(ctx context.Context, mergedClaims map[string]any) (GroupParams, *HTTPError) // SyncGroups assigns and removes users from groups based on the provided params. SyncGroups(ctx context.Context, db database.Store, user database.User, params GroupParams) error // GroupSyncSettings is exposed for the API to implement CRUD operations @@ -63,7 +62,7 @@ type IDPSync interface { UpdateRoleSyncSettings(ctx context.Context, orgID uuid.UUID, db database.Store, settings RoleSyncSettings) error // ParseRoleClaims takes claims from an OIDC provider, and returns the params // for role syncing. Most of the logic happens in SyncRoles. - ParseRoleClaims(ctx context.Context, mergedClaims jwt.MapClaims) (RoleParams, *HTTPError) + ParseRoleClaims(ctx context.Context, mergedClaims map[string]any) (RoleParams, *HTTPError) // SyncRoles assigns and removes users from roles based on the provided params. // Site & org roles are handled in this method. SyncRoles(ctx context.Context, db database.Store, user database.User, params RoleParams) error diff --git a/coderd/idpsync/organization.go b/coderd/idpsync/organization.go index 7684e812a75..63014400bc9 100644 --- a/coderd/idpsync/organization.go +++ b/coderd/idpsync/organization.go @@ -5,7 +5,6 @@ import ( "database/sql" "encoding/json" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -21,7 +20,7 @@ type OrganizationParams struct { // SyncEntitled if false will skip syncing the user's organizations. SyncEntitled bool // MergedClaims are passed to the organization level for syncing - MergedClaims jwt.MapClaims + MergedClaims map[string]any } func (AGPLIDPSync) OrganizationSyncEntitled() bool { @@ -63,7 +62,7 @@ func (s AGPLIDPSync) OrganizationSyncSettings(ctx context.Context, db database.S return orgSettings, nil } -func (s AGPLIDPSync) ParseOrganizationClaims(_ context.Context, claims jwt.MapClaims) (OrganizationParams, *HTTPError) { +func (s AGPLIDPSync) ParseOrganizationClaims(_ context.Context, claims map[string]any) (OrganizationParams, *HTTPError) { // For AGPL we only sync the default organization. return OrganizationParams{ SyncEntitled: s.OrganizationSyncEntitled(), @@ -246,7 +245,7 @@ func (s *OrganizationSyncSettings) MarshalJSON() ([]byte, error) { // ParseClaims will parse the claims and return the list of organizations the user // should sync to. -func (s *OrganizationSyncSettings) ParseClaims(ctx context.Context, db database.Store, mergedClaims jwt.MapClaims) ([]uuid.UUID, error) { +func (s *OrganizationSyncSettings) ParseClaims(ctx context.Context, db database.Store, mergedClaims map[string]any) ([]uuid.UUID, error) { userOrganizations := make([]uuid.UUID, 0) if s.AssignDefault { diff --git a/coderd/idpsync/organizations_test.go b/coderd/idpsync/organizations_test.go index 5054dc988fa..00373b87b67 100644 --- a/coderd/idpsync/organizations_test.go +++ b/coderd/idpsync/organizations_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/require" @@ -106,7 +105,7 @@ func TestParseOrganizationClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) - params, err := s.ParseOrganizationClaims(ctx, jwt.MapClaims{}) + params, err := s.ParseOrganizationClaims(ctx, map[string]any{}) require.Nil(t, err) require.False(t, params.SyncEntitled) diff --git a/coderd/idpsync/role.go b/coderd/idpsync/role.go index 67de32812ac..077d0c1e7ab 100644 --- a/coderd/idpsync/role.go +++ b/coderd/idpsync/role.go @@ -5,7 +5,6 @@ import ( "encoding/json" "slices" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -26,7 +25,7 @@ type RoleParams struct { SyncSiteWide bool SiteWideRoles []string // MergedClaims are passed to the organization level for syncing - MergedClaims jwt.MapClaims + MergedClaims map[string]any } func (AGPLIDPSync) RoleSyncEntitled() bool { @@ -64,7 +63,7 @@ func (s AGPLIDPSync) RoleSyncSettings(ctx context.Context, orgID uuid.UUID, db d return settings, nil } -func (s AGPLIDPSync) ParseRoleClaims(_ context.Context, _ jwt.MapClaims) (RoleParams, *HTTPError) { +func (s AGPLIDPSync) ParseRoleClaims(_ context.Context, _ map[string]any) (RoleParams, *HTTPError) { return RoleParams{ SyncEntitled: s.RoleSyncEntitled(), SyncSiteWide: s.SiteRoleSyncEnabled(), @@ -274,7 +273,7 @@ func (s AGPLIDPSync) syncSiteWideRoles(ctx context.Context, tx database.Store, u return nil } -func (AGPLIDPSync) RolesFromClaim(field string, claims jwt.MapClaims) ([]string, error) { +func (AGPLIDPSync) RolesFromClaim(field string, claims map[string]any) ([]string, error) { rolesRow, ok := claims[field] if !ok { // If no claim is provided than we can assume the user is just diff --git a/coderd/idpsync/role_test.go b/coderd/idpsync/role_test.go index e961bd8328a..796b6146755 100644 --- a/coderd/idpsync/role_test.go +++ b/coderd/idpsync/role_test.go @@ -6,7 +6,6 @@ import ( "slices" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" @@ -26,7 +25,7 @@ import ( func TestRoleSyncTable(t *testing.T) { t.Parallel() - userClaims := jwt.MapClaims{ + userClaims := map[string]any{ "roles": []string{ "foo", "bar", "baz", "create-bar", "create-baz", @@ -395,7 +394,7 @@ func TestNoopNoDiff(t *testing.T) { SyncEntitled: true, SyncSiteWide: true, SiteWideRoles: siteRoles, - MergedClaims: jwt.MapClaims{ + MergedClaims: map[string]any{ "roles": orgRoles, }, }) diff --git a/coderd/oauthpki/oidcpki.go b/coderd/oauthpki/oidcpki.go index 76f8d59c88c..3d6ae8dabf5 100644 --- a/coderd/oauthpki/oidcpki.go +++ b/coderd/oauthpki/oidcpki.go @@ -14,7 +14,8 @@ import ( "strings" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "golang.org/x/oauth2" "golang.org/x/oauth2/jws" @@ -135,7 +136,15 @@ func (ja *Config) Exchange(ctx context.Context, code string, opts ...oauth2.Auth func (ja *Config) jwtToken() (string, error) { now := time.Now() - token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + signer, err := jose.NewSigner(jose.SigningKey{ + Algorithm: jose.RS256, + Key: ja.clientKey, + }, (&jose.SignerOptions{}).WithType("JWT").WithHeader("x5t", ja.x5t)) + if err != nil { + return "", xerrors.Errorf("new jwt assertion signer: %w", err) + } + + signed, err := jwt.Signed(signer).Claims(map[string]any{ "iss": ja.clientID, "sub": ja.clientID, "aud": ja.tokenURL, @@ -145,10 +154,7 @@ func (ja *Config) jwtToken() (string, error) { "jti": uuid.New().String(), "nbf": now.Unix(), "iat": now.Unix(), - }) - token.Header["x5t"] = ja.x5t - - signed, err := token.SignedString(ja.clientKey) + }).Serialize() if err != nil { return "", xerrors.Errorf("sign jwt assertion: %w", err) } diff --git a/coderd/oauthpki/okidcpki_test.go b/coderd/oauthpki/okidcpki_test.go index 7f7dda17bcb..da122052a07 100644 --- a/coderd/oauthpki/okidcpki_test.go +++ b/coderd/oauthpki/okidcpki_test.go @@ -12,7 +12,8 @@ import ( "time" "github.com/coreos/go-oidc/v3/oidc" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -169,7 +170,7 @@ func TestAzureAKPKIWithCoderd(t *testing.T) { // Create a user and login const email = "alice@coder.com" - claims := jwt.MapClaims{ + claims := map[string]any{ "email": email, "sub": uuid.NewString(), } @@ -341,15 +342,16 @@ func assertJWTAuth(t testing.TB, r *http.Request) url.Values { assert.Equal(t, "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", vals.Get("client_assertion_type")) jwtToken := vals.Get("client_assertion") // No need to actually verify the jwt is signed right. - parsedToken, _, err := (&jwt.Parser{}).ParseUnverified(jwtToken, jwt.MapClaims{}) - if !assert.NoError(t, err, "failed to parse jwt token") { + parsedToken, err := jwt.ParseSigned(jwtToken, []jose.SignatureAlgorithm{jose.RS256}) + if !assert.NoError(t, err, "failed to parse jwt token") || !assert.Len(t, parsedToken.Headers, 1) { return nil } + header := parsedToken.Headers[0] // Azure requirements - assert.NotEmpty(t, parsedToken.Header["x5t"], "hashed cert missing") - assert.Equal(t, "RS256", parsedToken.Header["alg"], "azure only accepts RS256") - assert.Equal(t, "JWT", parsedToken.Header["typ"], "azure only accepts JWT") + assert.NotEmpty(t, header.ExtraHeaders["x5t"], "hashed cert missing") + assert.Equal(t, string(jose.RS256), header.Algorithm, "azure only accepts RS256") + assert.Equal(t, "JWT", header.ExtraHeaders[jose.HeaderType], "azure only accepts JWT") return vals } diff --git a/coderd/provisionerdserver/provisionerdserver_test.go b/coderd/provisionerdserver/provisionerdserver_test.go index 5ecaef690b5..f283af0cfdb 100644 --- a/coderd/provisionerdserver/provisionerdserver_test.go +++ b/coderd/provisionerdserver/provisionerdserver_test.go @@ -17,7 +17,6 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" @@ -100,7 +99,7 @@ func TestTokenIsRefreshedEarly(t *testing.T) { template := coderdtest.CreateTemplate(t, owner, first.OrganizationID, version.ID) // Setup an OIDC user. - client, _ := fake.Login(t, owner, jwt.MapClaims{ + client, _ := fake.Login(t, owner, map[string]any{ "email": "user@unauthorized.com", "email_verified": true, "sub": uuid.NewString(), @@ -129,7 +128,7 @@ func TestTokenIsRefreshedEarlyWithoutCoderd(t *testing.T) { cfg := fake.OIDCConfig(t, nil) // Fetch a valid token from the fake OIDC provider - token, err := fake.GenerateAuthenticatedToken(jwt.MapClaims{ + token, err := fake.GenerateAuthenticatedToken(map[string]any{ "email": "user@unauthorized.com", "email_verified": true, "sub": uuid.NewString(), diff --git a/coderd/userauth_test.go b/coderd/userauth_test.go index f101b7792e6..4d6bfae9bdb 100644 --- a/coderd/userauth_test.go +++ b/coderd/userauth_test.go @@ -18,7 +18,6 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/go-jose/go-jose/v4" - "github.com/golang-jwt/jwt/v4" "github.com/google/go-github/v43/github" "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" @@ -82,7 +81,7 @@ func TestOIDCOauthLoginWithExisting(t *testing.T) { }) const username = "alice" - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "email_verified": true, "preferred_username": username, @@ -1041,7 +1040,7 @@ func TestUserOAuth2Github(t *testing.T) { // This causes the email change to fail. client := codersdk.New(owner.URL) - client, _ = fake.Login(t, client, jwt.MapClaims{}) + client, _ = fake.Login(t, client, map[string]any{}) deleted, err := client.User(ctx, "me") require.NoError(t, err) @@ -1065,7 +1064,7 @@ func TestUserOAuth2Github(t *testing.T) { require.ErrorContains(t, err, "Cannot create user_link for deleted user") // Create the user again. - client, _ = fake.Login(t, client, jwt.MapClaims{}) + client, _ = fake.Login(t, client, map[string]any{}) user, err := client.User(ctx, "me") require.NoError(t, err) userID := user.ID @@ -1075,7 +1074,7 @@ func TestUserOAuth2Github(t *testing.T) { coderEmail.Primary = github.Bool(false) gmailEmail.Primary = github.Bool(true) - client, _ = fake.Login(t, client, jwt.MapClaims{}) + client, _ = fake.Login(t, client, map[string]any{}) user, err = client.User(ctx, "me") require.NoError(t, err) @@ -1091,7 +1090,7 @@ func TestUserOAuth2Github(t *testing.T) { Verified: github.Bool(true), }, } - client, _ = fake.Login(t, client, jwt.MapClaims{}) + client, _ = fake.Login(t, client, map[string]any{}) user, err = client.User(ctx, "me") require.NoError(t, err) @@ -1196,9 +1195,9 @@ func TestUserOIDC(t *testing.T) { for _, tc := range []struct { Name string - IDTokenClaims jwt.MapClaims - UserInfoClaims jwt.MapClaims - AccessTokenClaims jwt.MapClaims + IDTokenClaims map[string]any + UserInfoClaims map[string]any + AccessTokenClaims map[string]any AllowSignups bool EmailDomain []string AssertUser func(t testing.TB, u codersdk.User) @@ -1211,7 +1210,7 @@ func TestUserOIDC(t *testing.T) { }{ { Name: "NoSub", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", }, AllowSignups: true, @@ -1219,10 +1218,10 @@ func TestUserOIDC(t *testing.T) { }, { Name: "AccessTokenMerge", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "sub": uuid.NewString(), }, - AccessTokenClaims: jwt.MapClaims{ + AccessTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, }, @@ -1236,7 +1235,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "AccessTokenMergeNotJWT", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "sub": uuid.NewString(), }, IgnoreUserInfo: true, @@ -1246,7 +1245,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailOnly", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1259,7 +1258,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailVerifiedAsStringTrue", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": "true", "sub": uuid.NewString(), @@ -1272,7 +1271,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailVerifiedAsStringFalse", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": "false", "sub": uuid.NewString(), @@ -1282,7 +1281,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailNotVerified", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": false, "sub": uuid.NewString(), @@ -1303,7 +1302,7 @@ func TestUserOIDC(t *testing.T) { }, }, { - Name: "EmailNotAString", IDTokenClaims: jwt.MapClaims{ + Name: "EmailNotAString", IDTokenClaims: map[string]any{ "email": 3.14159, "email_verified": false, "sub": uuid.NewString(), @@ -1313,7 +1312,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailNotVerifiedIgnored", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": false, "sub": uuid.NewString(), @@ -1327,7 +1326,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "NotInRequiredEmailDomain", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1352,7 +1351,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailDomainWithLeadingAt", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "cian@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -1365,7 +1364,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailDomainForbiddenWithLeadingAt", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1390,7 +1389,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailDomainCaseInsensitive", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@KWC.io", "email_verified": true, "sub": uuid.NewString(), @@ -1406,7 +1405,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmailDomainSubset", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "colin@gmail.com", "email_verified": true, "sub": uuid.NewString(), @@ -1419,13 +1418,13 @@ func TestUserOIDC(t *testing.T) { }, { Name: "EmptyClaims", - IDTokenClaims: jwt.MapClaims{}, + IDTokenClaims: map[string]any{}, AllowSignups: true, StatusCode: http.StatusBadRequest, }, { Name: "NoSignups", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1435,7 +1434,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "FirstSignup", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1444,7 +1443,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "UsernameFromEmail", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), @@ -1457,7 +1456,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "UsernameFromClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "preferred_username": "hotdog", @@ -1471,7 +1470,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "FullNameFromClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "name": "Hot Dog", @@ -1485,7 +1484,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "InvalidFullNameFromClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, // Full names must be less or equal to than 128 characters in length. @@ -1502,7 +1501,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "FullNameWhitespace", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, // Full names must not have leading or trailing whitespace, but this is a @@ -1520,7 +1519,7 @@ func TestUserOIDC(t *testing.T) { // Services like Okta return the email as the username: // https://developer.okta.com/docs/reference/api/oidc/#base-claims-always-present Name: "UsernameAsEmail", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "name": "Kylium Carbonate", @@ -1536,7 +1535,7 @@ func TestUserOIDC(t *testing.T) { { // See: https://github.com/coder/coder/issues/4472 Name: "UsernameIsEmail", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email_verified": true, "preferred_username": "kyle@kwc.io", "sub": uuid.NewString(), @@ -1550,7 +1549,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "WithPicture", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "preferred_username": "kyle", @@ -1566,12 +1565,12 @@ func TestUserOIDC(t *testing.T) { }, { Name: "WithUserInfoClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "kyle@kwc.io", "email_verified": true, "sub": uuid.NewString(), }, - UserInfoClaims: jwt.MapClaims{ + UserInfoClaims: map[string]any{ "preferred_username": "potato", "picture": "/example.png", "name": "Kylium Carbonate", @@ -1586,7 +1585,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "GroupsDoesNothing", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "coolin@coder.com", "email_verified": true, "groups": []string{"pingpong"}, @@ -1597,12 +1596,12 @@ func TestUserOIDC(t *testing.T) { }, { Name: "UserInfoOverridesIDTokenClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "internaluser@internal.domain", "email_verified": false, "sub": uuid.NewString(), }, - UserInfoClaims: jwt.MapClaims{ + UserInfoClaims: map[string]any{ "email": "externaluser@external.domain", "email_verified": true, "preferred_username": "user", @@ -1616,12 +1615,12 @@ func TestUserOIDC(t *testing.T) { }, { Name: "InvalidUserInfo", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "internaluser@internal.domain", "email_verified": false, "sub": uuid.NewString(), }, - UserInfoClaims: jwt.MapClaims{ + UserInfoClaims: map[string]any{ "email": 1, }, AllowSignups: true, @@ -1630,14 +1629,14 @@ func TestUserOIDC(t *testing.T) { }, { Name: "IgnoreUserInfo", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "user@internal.domain", "email_verified": true, "name": "User McName", "preferred_username": "user", "sub": uuid.NewString(), }, - UserInfoClaims: jwt.MapClaims{ + UserInfoClaims: map[string]any{ "email": "user.mcname@external.domain", "name": "Mr. User McName", "preferred_username": "Mr. User McName", @@ -1652,7 +1651,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "HugeIDToken", - IDTokenClaims: inflateClaims(t, jwt.MapClaims{ + IDTokenClaims: inflateClaims(t, map[string]any{ "email": "user@domain.tld", "email_verified": true, "sub": uuid.NewString(), @@ -1665,12 +1664,12 @@ func TestUserOIDC(t *testing.T) { }, { Name: "HugeClaims", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "email": "user@domain.tld", "email_verified": true, "sub": uuid.NewString(), }, - UserInfoClaims: inflateClaims(t, jwt.MapClaims{}, 65536), + UserInfoClaims: inflateClaims(t, map[string]any{}, 65536), AssertUser: func(t testing.TB, u codersdk.User) { assert.Equal(t, "user", u.Username) }, @@ -1679,7 +1678,7 @@ func TestUserOIDC(t *testing.T) { }, { Name: "IssuerMismatch", - IDTokenClaims: jwt.MapClaims{ + IDTokenClaims: map[string]any{ "iss": "https://mismatch.com", "email": "user@domain.tld", "email_verified": true, @@ -1705,7 +1704,7 @@ func TestUserOIDC(t *testing.T) { } if len(tc.AccessTokenClaims) > 0 { - opts = append(opts, oidctest.WithAccessTokenJWTHook(func(email string, exp time.Time) jwt.MapClaims { + opts = append(opts, oidctest.WithAccessTokenJWTHook(func(email string, exp time.Time) map[string]any { return tc.AccessTokenClaims })) } @@ -1781,7 +1780,7 @@ func TestUserOIDC(t *testing.T) { client := coderdtest.New(t, &coderdtest.Options{ OIDCConfig: cfg, }) - _, resp := fake.AttemptLogin(t, client, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, client, map[string]any{ "email": "kyle@kwc.io", "sub": uuid.NewString(), }) @@ -1798,7 +1797,7 @@ func TestUserOIDC(t *testing.T) { SetupToken: "0123456789abcdefghijklmnopqrstuv", OIDCConfig: cfg, }) - _, resp := fake.AttemptLogin(t, client, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, client, map[string]any{ "email": "stranger@coder.com", "sub": uuid.NewString(), }) @@ -1825,7 +1824,7 @@ func TestUserOIDC(t *testing.T) { client := coderdtest.New(t, &coderdtest.Options{ OIDCConfig: cfg, }) - userClient, _ := fake.Login(t, client, jwt.MapClaims{ + userClient, _ := fake.Login(t, client, map[string]any{ "email": "kyle@kwc.io", "sub": uuid.NewString(), }) @@ -1862,7 +1861,7 @@ func TestUserOIDC(t *testing.T) { }) auditor.ResetLogs() - client, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + client, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "email_verified": true, "sub": uuid.NewString(), @@ -1929,7 +1928,7 @@ func TestUserOIDC(t *testing.T) { // Attacker tries to login with a different subject but the // same email. The email fallback is blocked because the victim // already has a user_link with a different linked_id. - _, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": victim.Email, "sub": "attacker-subject", }) @@ -1978,7 +1977,7 @@ func TestUserOIDC(t *testing.T) { // Login with a new OIDC subject and matching email. // This should succeed because no user_link exists. sub := uuid.NewString() - client, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + client, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": sub, }) @@ -2035,7 +2034,7 @@ func TestUserOIDC(t *testing.T) { }) sub := uuid.NewString() - client, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + client, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": sub, }) @@ -2099,7 +2098,7 @@ func TestUserOIDC(t *testing.T) { // Login presents the same subject but the current issuer, so the // computed linked_id differs from the stored one and is blocked. - _, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": sub, }) @@ -2157,7 +2156,7 @@ func TestUserOIDC(t *testing.T) { // for the same user) but the same email. With EmailFallback // enabled the email match resolves the login despite the linked_id // mismatch. - client, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + client, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": "second-connection-sub", }) @@ -2219,7 +2218,7 @@ func TestUserOIDC(t *testing.T) { }) // Fallback login with a different subject. - _, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": "second-connection-sub", }) @@ -2227,7 +2226,7 @@ func TestUserOIDC(t *testing.T) { // Subsequent login with the original subject must hit the primary // linked_id match and succeed. - client, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + client, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": originalSub, }) @@ -2279,7 +2278,7 @@ func TestUserOIDC(t *testing.T) { // New email, no existing user. Signups are disabled, so the // fallback flag must not let the login through. - _, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": "stranger@example.com", "sub": "stranger-subject", }) @@ -2312,7 +2311,7 @@ func TestUserOIDC(t *testing.T) { Status: database.UserStatusSuspended, }) - _, resp := fake.AttemptLogin(t, owner, jwt.MapClaims{ + _, resp := fake.AttemptLogin(t, owner, map[string]any{ "email": user.Email, "sub": uuid.NewString(), }) @@ -2357,7 +2356,7 @@ func TestUserOIDC(t *testing.T) { user, userData := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) require.Equal(t, codersdk.LoginTypePassword, userData.LoginType) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": userData.Email, "email_verified": true, "sub": uuid.NewString(), @@ -2429,7 +2428,7 @@ func TestUserOIDC(t *testing.T) { owner := coderdtest.CreateFirstUser(t, client) user, userData := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": userData.Email, "email_verified": true, "sub": uuid.NewString(), @@ -2501,7 +2500,7 @@ func TestUserOIDC(t *testing.T) { }) numLogs := len(auditor.AuditLogs()) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "jon@coder.com", "email_verified": true, "sub": uuid.NewString(), @@ -2517,7 +2516,7 @@ func TestUserOIDC(t *testing.T) { // Pass a different subject field so that we prompt creating a // new user - userClient, _ = fake.Login(t, client, jwt.MapClaims{ + userClient, _ = fake.Login(t, client, map[string]any{ "email": "jon@example2.com", "email_verified": true, "sub": "diff", @@ -2563,7 +2562,7 @@ func TestUserOIDC(t *testing.T) { OIDCConfig: cfg, }) - _, resp := fake.AttemptLogin(t, client, jwt.MapClaims{}) + _, resp := fake.AttemptLogin(t, client, map[string]any{}) require.Equal(t, http.StatusBadRequest, resp.StatusCode) }) @@ -2590,7 +2589,7 @@ func TestUserOIDC(t *testing.T) { OIDCConfig: cfg, }) - _, resp := fake.AttemptLogin(t, client, jwt.MapClaims{}) + _, resp := fake.AttemptLogin(t, client, map[string]any{}) require.Equal(t, http.StatusBadRequest, resp.StatusCode) }) @@ -2622,7 +2621,7 @@ func TestUserOIDC(t *testing.T) { return http.ErrUseLastResponse } - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "user@example.com", "email_verified": true, "sub": uuid.NewString(), @@ -2796,7 +2795,7 @@ func TestOIDCDomainErrorMessage(t *testing.T) { fake, client := setup() // Prepare claims with email from unauthorized domain - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "user@unauthorized.com", "email_verified": true, "sub": uuid.NewString(), @@ -2831,7 +2830,7 @@ func TestOIDCDomainErrorMessage(t *testing.T) { fake, client := setup() // Prepare claims with an invalid email format (no @ symbol) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "invalid-email-without-domain", "email_verified": true, "sub": uuid.NewString(), @@ -2867,7 +2866,7 @@ func TestOIDCSkipIssuer(t *testing.T) { fake := oidctest.NewFakeIDP(t, oidctest.WithServing(), - oidctest.WithDefaultIDClaims(jwt.MapClaims{}), + oidctest.WithDefaultIDClaims(map[string]any{}), oidctest.WithHookWellKnown(func(r *http.Request, j *oidctest.ProviderJSON) error { assert.NotEqual(t, r.URL.Host, primaryURL.Host, "request went to wrong host") j.Issuer = primaryURLString @@ -2884,7 +2883,7 @@ func TestOIDCSkipIssuer(t *testing.T) { // User can login and use their token. ctx := testutil.Context(t, testutil.WaitShort) //nolint:bodyclose - userClient, _ := fake.Login(t, owner, jwt.MapClaims{ + userClient, _ := fake.Login(t, owner, map[string]any{ "iss": secondaryURLString, "email": "alice@coder.com", "email_verified": true, @@ -3266,9 +3265,9 @@ func authCookieValue(cookies []*http.Cookie) string { return "" } -// inflateClaims 'inflates' a jwt.MapClaims from a seed by +// inflateClaims 'inflates' a map[string]any from a seed by // adding a ridiculously large key-value pair of length size. -func inflateClaims(t testing.TB, seed jwt.MapClaims, size int) jwt.MapClaims { +func inflateClaims(t testing.TB, seed map[string]any, size int) map[string]any { t.Helper() junk, err := cryptorand.String(size) require.NoError(t, err) diff --git a/coderd/users_test.go b/coderd/users_test.go index 4448384d001..678ffd39175 100644 --- a/coderd/users_test.go +++ b/coderd/users_test.go @@ -11,7 +11,6 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -1097,7 +1096,7 @@ func TestPostUsers(t *testing.T) { require.NoError(t, err) // Try to log in with OIDC. - userClient, _ := fake.Login(t, client, jwt.MapClaims{ + userClient, _ := fake.Login(t, client, map[string]any{ "email": email, "email_verified": true, "sub": uuid.NewString(), diff --git a/enterprise/coderd/coderdenttest/coderdenttest.go b/enterprise/coderd/coderdenttest/coderdenttest.go index a9e441faebb..bb3b3eb9e0e 100644 --- a/enterprise/coderd/coderdenttest/coderdenttest.go +++ b/enterprise/coderd/coderdenttest/coderdenttest.go @@ -13,7 +13,8 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -22,6 +23,7 @@ import ( "github.com/coder/coder/v2/coderd/coderdtest" "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/pubsub" + "github.com/coder/coder/v2/coderd/jwtutils" "github.com/coder/coder/v2/coderd/prebuilds" "github.com/coder/coder/v2/coderd/util/namesgenerator" "github.com/coder/coder/v2/codersdk" @@ -294,10 +296,10 @@ func GenerateLicense(t *testing.T, options LicenseOptions) string { } c := &license.Claims{ - RegisteredClaims: jwt.RegisteredClaims{ + RegisteredClaims: jwtutils.RegisteredClaims{ ID: uuid.NewString(), Issuer: "test@testing.test", - ExpiresAt: jwt.NewNumericDate(options.ExpiresAt), + Expiry: jwt.NewNumericDate(options.ExpiresAt), NotBefore: jwt.NewNumericDate(options.NotBefore), IssuedAt: jwt.NewNumericDate(issuedAt), }, @@ -316,11 +318,14 @@ func GenerateLicense(t *testing.T, options LicenseOptions) string { return GenerateLicenseRaw(t, c) } -func GenerateLicenseRaw(t *testing.T, claims jwt.Claims) string { +func GenerateLicenseRaw(t *testing.T, claims any) string { t.Helper() - tok := jwt.NewWithClaims(jwt.SigningMethodEdDSA, claims) - tok.Header[license.HeaderKeyID] = testKeyID - signedTok, err := tok.SignedString(testPrivateKey) + signer, err := jose.NewSigner(jose.SigningKey{ + Algorithm: jose.EdDSA, + Key: testPrivateKey, + }, (&jose.SignerOptions{}).WithType("JWT").WithHeader(license.HeaderKeyID, testKeyID)) + require.NoError(t, err) + signedTok, err := jwt.Signed(signer).Claims(claims).Serialize() require.NoError(t, err) return signedTok } diff --git a/enterprise/coderd/enidpsync/groups.go b/enterprise/coderd/enidpsync/groups.go index c67d8d53f05..b85c834276f 100644 --- a/enterprise/coderd/enidpsync/groups.go +++ b/enterprise/coderd/enidpsync/groups.go @@ -3,8 +3,6 @@ package enidpsync import ( "context" - "github.com/golang-jwt/jwt/v4" - "github.com/coder/coder/v2/coderd/idpsync" "github.com/coder/coder/v2/codersdk" ) @@ -18,7 +16,7 @@ func (e EnterpriseIDPSync) GroupSyncEntitled() bool { // group sync settings. // GroupAllowList is implemented here to prevent login by unauthorized users. // TODO: GroupAllowList overlaps with the default organization group sync settings. -func (e EnterpriseIDPSync) ParseGroupClaims(ctx context.Context, mergedClaims jwt.MapClaims) (idpsync.GroupParams, *idpsync.HTTPError) { +func (e EnterpriseIDPSync) ParseGroupClaims(ctx context.Context, mergedClaims map[string]any) (idpsync.GroupParams, *idpsync.HTTPError) { resp, err := e.AGPLIDPSync.ParseGroupClaims(ctx, mergedClaims) if err != nil { return idpsync.GroupParams{}, err diff --git a/enterprise/coderd/enidpsync/groups_test.go b/enterprise/coderd/enidpsync/groups_test.go index 2ba33647a17..d8eea0c4666 100644 --- a/enterprise/coderd/enidpsync/groups_test.go +++ b/enterprise/coderd/enidpsync/groups_test.go @@ -3,7 +3,6 @@ package enidpsync_test import ( "testing" - "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/require" "cdr.dev/slog/v3/sloggers/slogtest" @@ -36,7 +35,7 @@ func TestEnterpriseParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) - params, err := s.ParseGroupClaims(ctx, jwt.MapClaims{}) + params, err := s.ParseGroupClaims(ctx, map[string]any{}) require.Nil(t, err) require.False(t, params.SyncEntitled) @@ -58,14 +57,14 @@ func TestEnterpriseParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) // Try with incorrect group - _, err := s.ParseGroupClaims(ctx, jwt.MapClaims{ + _, err := s.ParseGroupClaims(ctx, map[string]any{ "groups": []string{"bar"}, }) require.NotNil(t, err) require.Equal(t, 403, err.Code) // Try with no groups - _, err = s.ParseGroupClaims(ctx, jwt.MapClaims{}) + _, err = s.ParseGroupClaims(ctx, map[string]any{}) require.NotNil(t, err) require.Equal(t, 403, err.Code) }) @@ -85,7 +84,7 @@ func TestEnterpriseParseGroupClaims(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) - claims := jwt.MapClaims{ + claims := map[string]any{ "groups": []string{"foo", "bar"}, } params, err := s.ParseGroupClaims(ctx, claims) diff --git a/enterprise/coderd/enidpsync/organizations.go b/enterprise/coderd/enidpsync/organizations.go index 826144afc14..5a741024d9f 100644 --- a/enterprise/coderd/enidpsync/organizations.go +++ b/enterprise/coderd/enidpsync/organizations.go @@ -3,8 +3,6 @@ package enidpsync import ( "context" - "github.com/golang-jwt/jwt/v4" - "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/idpsync" "github.com/coder/coder/v2/codersdk" @@ -28,7 +26,7 @@ func (e EnterpriseIDPSync) OrganizationSyncEnabled(ctx context.Context, db datab return false } -func (e EnterpriseIDPSync) ParseOrganizationClaims(ctx context.Context, mergedClaims jwt.MapClaims) (idpsync.OrganizationParams, *idpsync.HTTPError) { +func (e EnterpriseIDPSync) ParseOrganizationClaims(ctx context.Context, mergedClaims map[string]any) (idpsync.OrganizationParams, *idpsync.HTTPError) { if !e.OrganizationSyncEntitled() { // Default to agpl if multi-org is not enabled return e.AGPLIDPSync.ParseOrganizationClaims(ctx, mergedClaims) diff --git a/enterprise/coderd/enidpsync/organizations_test.go b/enterprise/coderd/enidpsync/organizations_test.go index be951e69269..f59951f5b1a 100644 --- a/enterprise/coderd/enidpsync/organizations_test.go +++ b/enterprise/coderd/enidpsync/organizations_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" @@ -33,7 +32,7 @@ type ExpectedUser struct { type Expectations struct { Name string - Claims jwt.MapClaims + Claims map[string]any // Parse ParseError func(t *testing.T, httpErr *idpsync.HTTPError) ExpectedParams idpsync.OrganizationParams @@ -97,7 +96,7 @@ func TestOrganizationSync(t *testing.T) { Exps: []Expectations{ { Name: "NoOrganizations", - Claims: jwt.MapClaims{}, + Claims: map[string]any{}, ExpectedParams: idpsync.OrganizationParams{ SyncEntitled: true, }, @@ -108,7 +107,7 @@ func TestOrganizationSync(t *testing.T) { }, { Name: "AlreadyInOrgs", - Claims: jwt.MapClaims{}, + Claims: map[string]any{}, ExpectedParams: idpsync.OrganizationParams{ SyncEntitled: true, }, @@ -162,7 +161,7 @@ func TestOrganizationSync(t *testing.T) { Exps: []Expectations{ { Name: "NoOrganizations", - Claims: jwt.MapClaims{}, + Claims: map[string]any{}, ExpectedParams: idpsync.OrganizationParams{ SyncEntitled: true, }, @@ -173,7 +172,7 @@ func TestOrganizationSync(t *testing.T) { }, { Name: "AlreadyInOrgs", - Claims: jwt.MapClaims{ + Claims: map[string]any{ "organizations": []string{"second", "extra", "deleted"}, }, ExpectedParams: idpsync.OrganizationParams{ @@ -196,7 +195,7 @@ func TestOrganizationSync(t *testing.T) { }, { Name: "ManyClaims", - Claims: jwt.MapClaims{ + Claims: map[string]any{ // Add some repeats "organizations": []string{"second", "extra", "first", "third", "second", "second", "deleted"}, }, @@ -251,7 +250,7 @@ func TestOrganizationSync(t *testing.T) { Exps: []Expectations{ { Name: "NoOrganizations", - Claims: jwt.MapClaims{}, + Claims: map[string]any{}, ExpectedParams: idpsync.OrganizationParams{ SyncEntitled: true, }, @@ -262,7 +261,7 @@ func TestOrganizationSync(t *testing.T) { }, { Name: "AlreadyInOrgs", - Claims: jwt.MapClaims{ + Claims: map[string]any{ "organizations": []string{"second", "extra"}, "dynamic": []string{"third"}, }, diff --git a/enterprise/coderd/enidpsync/role.go b/enterprise/coderd/enidpsync/role.go index 092134d25ea..97c410d8182 100644 --- a/enterprise/coderd/enidpsync/role.go +++ b/enterprise/coderd/enidpsync/role.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -42,7 +41,7 @@ func (e EnterpriseIDPSync) SiteRoleSyncEnabled() bool { return e.SiteRoleField != "" } -func (e EnterpriseIDPSync) ParseRoleClaims(ctx context.Context, mergedClaims jwt.MapClaims) (idpsync.RoleParams, *idpsync.HTTPError) { +func (e EnterpriseIDPSync) ParseRoleClaims(ctx context.Context, mergedClaims map[string]any) (idpsync.RoleParams, *idpsync.HTTPError) { if !e.RoleSyncEntitled() { return e.AGPLIDPSync.ParseRoleClaims(ctx, mergedClaims) } diff --git a/enterprise/coderd/enidpsync/role_test.go b/enterprise/coderd/enidpsync/role_test.go index 555ab7ac7a1..2e089c6663d 100644 --- a/enterprise/coderd/enidpsync/role_test.go +++ b/enterprise/coderd/enidpsync/role_test.go @@ -4,7 +4,6 @@ import ( "context" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/stretchr/testify/require" "github.com/coder/coder/v2/coderd/entitlements" @@ -33,7 +32,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { mgr := runtimeconfig.NewManager() s := enidpsync.NewSync(testutil.Logger(t), mgr, entitlements.New(), idpsync.DeploymentSyncSettings{}) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{}) + params, err := s.ParseRoleClaims(context.Background(), map[string]any{}) require.Nil(t, err) require.False(t, params.SyncEntitled) require.False(t, params.SyncSiteWide) @@ -48,7 +47,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { SiteRoleField: "roles", }) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{}) + params, err := s.ParseRoleClaims(context.Background(), map[string]any{}) require.Nil(t, err) require.False(t, params.SyncEntitled) require.False(t, params.SyncSiteWide) @@ -60,7 +59,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { mgr := runtimeconfig.NewManager() s := enidpsync.NewSync(testutil.Logger(t), mgr, entitled, idpsync.DeploymentSyncSettings{}) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{}) + params, err := s.ParseRoleClaims(context.Background(), map[string]any{}) require.Nil(t, err) require.True(t, params.SyncEntitled) require.False(t, params.SyncSiteWide) @@ -76,7 +75,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { SiteDefaultRoles: []string{rbac.RoleTemplateAdmin().Name}, }) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{ + params, err := s.ParseRoleClaims(context.Background(), map[string]any{ "roles": []string{rbac.RoleAuditor().Name}, }) require.Nil(t, err) @@ -101,7 +100,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { SiteDefaultRoles: []string{rbac.RoleTemplateAdmin().Name}, }) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{ + params, err := s.ParseRoleClaims(context.Background(), map[string]any{ "roles": []string{"foo", "bar", "random"}, }) require.Nil(t, err) @@ -130,7 +129,7 @@ func TestEnterpriseParseRoleClaims(t *testing.T) { SiteDefaultRoles: []string{rbac.RoleAuditor().Name}, }) - params, err := s.ParseRoleClaims(context.Background(), jwt.MapClaims{ + params, err := s.ParseRoleClaims(context.Background(), map[string]any{ "roles": []string{"foo", "bar", rbac.RoleAuditor().Name, rbac.RoleOwner().Name}, }) require.Nil(t, err) diff --git a/enterprise/coderd/license/license.go b/enterprise/coderd/license/license.go index d26e990f5d8..476fb878cc6 100644 --- a/enterprise/coderd/license/license.go +++ b/enterprise/coderd/license/license.go @@ -10,12 +10,14 @@ import ( "sort" "time" - "github.com/golang-jwt/jwt/v4" + "github.com/go-jose/go-jose/v4" + "github.com/go-jose/go-jose/v4/jwt" "golang.org/x/xerrors" "cdr.dev/slog/v3" "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/dbauthz" + "github.com/coder/coder/v2/coderd/jwtutils" "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/codersdk" ) @@ -387,8 +389,7 @@ func LicensesEntitlements( // 'Entitlements' group as a whole. for _, license := range licenses { claims, err := ParseClaims(license.JWT, keys) - var vErr *jwt.ValidationError - if xerrors.As(err, &vErr) && vErr.Is(jwt.ErrTokenNotValidYet) { + if xerrors.Is(err, jwt.ErrNotValidYet) { // The license isn't valid yet. We don't consider any entitlements contained in it, but // it's also not an error. Just skip it silently. This can happen if an administrator // uploads a license for a new term that hasn't started yet. @@ -415,8 +416,8 @@ func LicensesEntitlements( // validity period. nextLicenseValidityPeriod.ApplyClaims(claims) - usagePeriodStart := claims.NotBefore.Time // checked not-nil when validating claims - usagePeriodEnd := claims.ExpiresAt.Time // checked not-nil when validating claims + usagePeriodStart := claims.NotBefore.Time() // checked not-nil when validating claims + usagePeriodEnd := claims.Expiry.Time() // checked not-nil when validating claims if usagePeriodStart.After(usagePeriodEnd) { // This shouldn't be possible to be hit. You'd need to have a // license with `nbf` after `exp`. Because `nbf` must be in the past @@ -437,7 +438,7 @@ func LicensesEntitlements( // If any license is a trial license, this should be set to true. // The user should delete the trial license to remove this. entitlements.Trial = claims.Trial - if now.After(claims.LicenseExpires.Time) { + if now.After(claims.LicenseExpires.Time()) { // if the grace period were over, the validation fails, so if we are after // LicenseExpires we must be in grace period. entitlement = codersdk.EntitlementGracePeriod @@ -570,7 +571,7 @@ func LicensesEntitlements( Entitlement: entitlement, Limit: &featureValue, UsagePeriod: &codersdk.UsagePeriod{ - IssuedAt: claims.IssuedAt.Time, + IssuedAt: claims.IssuedAt.Time(), Start: usagePeriodStart, End: usagePeriodEnd, }, @@ -609,7 +610,7 @@ func LicensesEntitlements( } runtimeFeature, granted, ignoredClaims := decodeAgentRuntimeHours(claims.Features, entitlement, codersdk.UsagePeriod{ - IssuedAt: claims.IssuedAt.Time, + IssuedAt: claims.IssuedAt.Time(), Start: usagePeriodStart, End: usagePeriodEnd, }) @@ -1031,7 +1032,7 @@ const ( const AgentRuntimeHoursUnlimitedAllocation int64 = -1 var ( - ValidMethods = []string{"EdDSA"} + ValidMethods = []jose.SignatureAlgorithm{jose.EdDSA} ErrInvalidVersion = xerrors.New("license must be version 3") ErrMissingKeyID = xerrors.Errorf("JOSE header must contain %s", HeaderKeyID) @@ -1146,9 +1147,9 @@ func decodeAgentRuntimeHours(features Features, entitlement codersdk.Entitlement // Claims is the full set of claims in a license. type Claims struct { - jwt.RegisteredClaims + jwtutils.RegisteredClaims // LicenseExpires is the end of the legit license term, and the start of the grace period, if - // there is one. The standard JWT claim "exp" (ExpiresAt in jwt.RegisteredClaims, above) is + // there is one. The standard JWT claim "exp" (Expiry in RegisteredClaims, above) is // the end of the grace period (identical to LicenseExpires if there is no grace period). // The reason we use the standard claim for the end of the grace period is that we want JWT // processing libraries to consider the token "valid" until then. @@ -1169,116 +1170,118 @@ type Claims struct { PublishUsageData bool `json:"publish_usage_data,omitempty"` } -var _ jwt.Claims = &Claims{} - // ParseRaw consumes a license and returns the claims. -func ParseRaw(l string, keys map[string]ed25519.PublicKey) (jwt.MapClaims, error) { - tok, err := jwt.Parse( - l, - keyFunc(keys), - jwt.WithValidMethods(ValidMethods), +func ParseRaw(l string, keys map[string]ed25519.PublicKey) (map[string]any, error) { + var ( + registered jwt.Claims + claims map[string]any ) - if err != nil { + if err := verify(l, keys, ®istered, &claims); err != nil { return nil, err } - if claims, ok := tok.Claims.(jwt.MapClaims); ok && tok.Valid { - version, ok := claims[VersionClaim].(float64) - if !ok { - return nil, ErrInvalidVersion - } - if int64(version) != CurrentVersion { - return nil, ErrInvalidVersion - } - return claims, nil + if err := validateTimes(registered, time.Now()); err != nil { + return nil, err } - return nil, xerrors.New("unable to parse Claims") + version, ok := claims[VersionClaim].(float64) + if !ok { + return nil, ErrInvalidVersion + } + if int64(version) != CurrentVersion { + return nil, ErrInvalidVersion + } + return claims, nil } // ParseClaims validates a raw JWT, and if valid, returns the claims. If // unparsable or invalid, it returns an error func ParseClaims(rawJWT string, keys map[string]ed25519.PublicKey) (*Claims, error) { - tok, err := jwt.ParseWithClaims( - rawJWT, - &Claims{}, - keyFunc(keys), - jwt.WithValidMethods(ValidMethods), - ) - if err != nil { + claims := &Claims{} + if err := verify(rawJWT, keys, claims); err != nil { return nil, err } - return validateClaims(tok) + if err := validateTimes(jwt.Claims(claims.RegisteredClaims), time.Now()); err != nil { + return nil, err + } + return validateClaims(claims) } -func validateClaims(tok *jwt.Token) (*Claims, error) { - if claims, ok := tok.Claims.(*Claims); ok { - if claims.Version != uint64(CurrentVersion) { - return nil, ErrInvalidVersion - } - if claims.IssuedAt == nil { - return nil, ErrMissingIssuedAt - } - if claims.NotBefore == nil { - return nil, ErrMissingNotBefore - } - - yearsHardLimit := time.Now().Add(5 /* years */ * 365 * 24 * time.Hour) - if claims.LicenseExpires == nil || claims.LicenseExpires.After(yearsHardLimit) { - return nil, ErrMissingLicenseExpires - } - if claims.ExpiresAt == nil { - return nil, ErrMissingExp - } - if claims.AccountType == "" { - return nil, ErrMissingAccountType - } - if claims.AccountID == "" { - return nil, ErrMissingAccountID - } - return claims, nil +func validateClaims(claims *Claims) (*Claims, error) { + if claims.Version != uint64(CurrentVersion) { + return nil, ErrInvalidVersion } - return nil, xerrors.New("unable to parse Claims") + if claims.IssuedAt == nil { + return nil, ErrMissingIssuedAt + } + if claims.NotBefore == nil { + return nil, ErrMissingNotBefore + } + + yearsHardLimit := time.Now().Add(5 /* years */ * 365 * 24 * time.Hour) + if claims.LicenseExpires == nil || claims.LicenseExpires.Time().After(yearsHardLimit) { + return nil, ErrMissingLicenseExpires + } + if claims.Expiry == nil { + return nil, ErrMissingExp + } + if claims.AccountType == "" { + return nil, ErrMissingAccountType + } + if claims.AccountID == "" { + return nil, ErrMissingAccountID + } + return claims, nil } // ParseClaimsIgnoreNbf validates a raw JWT, but ignores `nbf` claim. If otherwise valid, it returns // the claims. If unparsable or invalid, it returns an error. Ignoring the `nbf` (not before) is // useful to determine if a JWT _will_ become valid at any point now or in the future. func ParseClaimsIgnoreNbf(rawJWT string, keys map[string]ed25519.PublicKey) (*Claims, error) { - tok, err := jwt.ParseWithClaims( - rawJWT, - &Claims{}, - keyFunc(keys), - jwt.WithValidMethods(ValidMethods), - ) - var vErr *jwt.ValidationError - if xerrors.As(err, &vErr) { - // zero out the NotValidYet error to check if there were other problems - vErr.Errors &= (^jwt.ValidationErrorNotValidYet) - if vErr.Errors != 0 { - // There are other errors besides not being valid yet. We _could_ go - // through all the jwt.ValidationError bits and try to work out the - // correct error, but if we get here something very strange is - // going on so let's just return a generic error that says to get in - // touch with our support team. - return nil, ErrMultipleIssues - } - } else if err != nil { - return nil, err + claims := &Claims{} + if err := verify(rawJWT, keys, claims); err != nil { + // Signature and parsing problems are not worth explaining in detail + // here, so ask the user to get in touch with our support team. + return nil, ErrMultipleIssues } - return validateClaims(tok) + registered := jwt.Claims(claims.RegisteredClaims) + registered.NotBefore = nil + if err := validateTimes(registered, time.Now()); err != nil { + return nil, ErrMultipleIssues + } + return validateClaims(claims) } -func keyFunc(keys map[string]ed25519.PublicKey) func(*jwt.Token) (interface{}, error) { - return func(j *jwt.Token) (interface{}, error) { - keyID, ok := j.Header[HeaderKeyID].(string) - if !ok { - return nil, ErrMissingKeyID - } - k, ok := keys[keyID] - if !ok { - return nil, xerrors.Errorf("no key with ID %s", keyID) - } - return k, nil +// verify checks the signature of a raw license JWT against the key named by +// its kid header and decodes the payload into each of dest. +func verify(rawJWT string, keys map[string]ed25519.PublicKey, dest ...any) error { + tok, err := jwt.ParseSigned(rawJWT, ValidMethods) + if err != nil { + return xerrors.Errorf("parse license jwt: %w", err) } + // Compact serialization always has exactly one signature. + if len(tok.Headers) != 1 { + return xerrors.New("license jwt must have exactly one signature") + } + keyID := tok.Headers[0].KeyID + if keyID == "" { + return ErrMissingKeyID + } + key, ok := keys[keyID] + if !ok { + return xerrors.Errorf("no key with ID %s", keyID) + } + if err := tok.Claims(key, dest...); err != nil { + return xerrors.Errorf("verify license jwt: %w", err) + } + return nil +} + +// validateTimes checks the registered time claims (exp, nbf, iat) that are +// present, without any clock skew leeway. +func validateTimes(claims jwt.Claims, now time.Time) error { + if err := claims.ValidateWithLeeway(jwt.Expected{Time: now}, 0); err != nil { + return xerrors.Errorf("validate license claims: %w", err) + } + return nil } // licenseValidityPeriod keeps track of all license validity periods, and @@ -1299,7 +1302,7 @@ func (p *licenseValidityPeriod) ApplyClaims(claims *Claims) { // Bad data return } - p.Apply(claims.NotBefore.Time, claims.LicenseExpires.Time) + p.Apply(claims.NotBefore.Time(), claims.LicenseExpires.Time()) } // Apply adds a license validity period. diff --git a/enterprise/coderd/licenses.go b/enterprise/coderd/licenses.go index bbe93931674..66cc15714be 100644 --- a/enterprise/coderd/licenses.go +++ b/enterprise/coderd/licenses.go @@ -17,7 +17,6 @@ import ( "time" "github.com/go-chi/chi/v5" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "golang.org/x/xerrors" @@ -265,7 +264,7 @@ func (api *API) installLicense( dl, err := api.Database.InsertLicense(ctx, database.InsertLicenseParams{ UploadedAt: dbtime.Now(), JWT: rawLicense, - Exp: claims.ExpiresAt.Time, + Exp: claims.Expiry.Time(), UUID: id, }) if err != nil { @@ -479,7 +478,7 @@ func (api *API) deleteLicense(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(http.StatusOK) } -func convertLicense(dl database.License, c jwt.MapClaims) codersdk.License { +func convertLicense(dl database.License, c map[string]any) codersdk.License { return codersdk.License{ ID: dl.ID, UUID: dl.UUID, @@ -506,7 +505,7 @@ func convertLicenses(licenses []database.License) ([]codersdk.License, error) { // // Also, we do not return the whole JWT itself because a signed JWT is a bearer token and we // want to limit the chance of it being accidentally leaked. -func decodeClaims(l database.License) (jwt.MapClaims, error) { +func decodeClaims(l database.License) (map[string]any, error) { parts := strings.Split(l.JWT, ".") if len(parts) != 3 { return nil, xerrors.Errorf("Unable to parse license %d as JWT", l.ID) @@ -515,7 +514,7 @@ func decodeClaims(l database.License) (jwt.MapClaims, error) { if err != nil { return nil, xerrors.Errorf("Unable to decode license %d claims: %w", l.ID, err) } - c := make(jwt.MapClaims) + c := make(map[string]any) d := json.NewDecoder(bytes.NewBuffer(cb)) d.UseNumber() err = d.Decode(&c) diff --git a/enterprise/coderd/usage/publisher.go b/enterprise/coderd/usage/publisher.go index c88a8775e55..dccc0b1d433 100644 --- a/enterprise/coderd/usage/publisher.go +++ b/enterprise/coderd/usage/publisher.go @@ -476,7 +476,7 @@ func (p *tallymanPublisher) getBestLicenseJWT(ctx context.Context) (string, erro // Otherwise, if it's issued more recently, it's the best license. // IssuedAt is verified to be non-nil in license.ParseClaims. - if bestLicense.Claims == nil || claims.IssuedAt.After(bestLicense.Claims.IssuedAt.Time) { + if bestLicense.Claims == nil || claims.IssuedAt.Time().After(bestLicense.Claims.IssuedAt.Time()) { bestLicense = licenseJWTWithClaims{ Claims: claims, Raw: dbLicense.JWT, diff --git a/enterprise/coderd/userauth_test.go b/enterprise/coderd/userauth_test.go index 5a0986788ac..9072a86a9a0 100644 --- a/enterprise/coderd/userauth_test.go +++ b/enterprise/coderd/userauth_test.go @@ -6,7 +6,6 @@ import ( "regexp" "testing" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/require" "golang.org/x/xerrors" @@ -47,7 +46,7 @@ func TestUserOIDC(t *testing.T) { }, }) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "sub": uuid.NewString(), } @@ -80,7 +79,7 @@ func TestUserOIDC(t *testing.T) { }) require.NoError(t, err) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "sub": uuid.NewString(), } @@ -154,7 +153,7 @@ func TestUserOIDC(t *testing.T) { require.Equal(t, expectedSettings.Field, settings.Field) sub := uuid.NewString() - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "organization": []string{"first", "second"}, "sub": sub, @@ -204,7 +203,7 @@ func TestUserOIDC(t *testing.T) { // Then: Log in again will resync the orgs to their updated // claims. - runner.Login(t, jwt.MapClaims{ + runner.Login(t, map[string]any{ "email": "alice@coder.com", "organization": []string{"second"}, "sub": sub, @@ -244,7 +243,7 @@ func TestUserOIDC(t *testing.T) { sub := uuid.NewString() ctx := testutil.Context(t, testutil.WaitMedium) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "organization": []string{"second", "third"}, "sub": sub, @@ -268,7 +267,7 @@ func TestUserOIDC(t *testing.T) { // Then: Log in again will resync the orgs to their updated // claims. - runner.Login(t, jwt.MapClaims{ + runner.Login(t, map[string]any{ "email": "alice@coder.com", "organization": []string{"third"}, "sub": sub, @@ -294,7 +293,7 @@ func TestUserOIDC(t *testing.T) { }, }) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "sub": uuid.NewString(), } @@ -331,7 +330,7 @@ func TestUserOIDC(t *testing.T) { }) // User starts with the owner role - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", // This is sent as a **string** intentionally instead // of an array. @@ -353,7 +352,7 @@ func TestUserOIDC(t *testing.T) { const oidcRoleName = "TemplateAuthor" runner := setupOIDCTest(t, oidcTestConfig{ - Userinfo: jwt.MapClaims{oidcRoleName: []string{rbac.RoleTemplateAdmin().String(), rbac.RoleUserAdmin().String()}}, + Userinfo: map[string]any{oidcRoleName: []string{rbac.RoleTemplateAdmin().String(), rbac.RoleUserAdmin().String()}}, Config: func(cfg *coderd.OIDCConfig) { cfg.AllowSignups = true }, @@ -368,7 +367,7 @@ func TestUserOIDC(t *testing.T) { }) // User starts with the owner role - client, resp := runner.Login(t, jwt.MapClaims{ + client, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", "roles": []string{"random", oidcRoleName, rbac.RoleOwner().String()}, }) @@ -377,7 +376,7 @@ func TestUserOIDC(t *testing.T) { // Now refresh the oauth, and check the roles are removed. // Force a refresh, and assert nothing has changes - runner.ForceRefresh(t, client, jwt.MapClaims{ + runner.ForceRefresh(t, client, map[string]any{ "email": "alice@coder.com", "roles": []string{"random"}, }) @@ -392,7 +391,7 @@ func TestUserOIDC(t *testing.T) { const oidcRoleName = "TemplateAuthor" runner := setupOIDCTest(t, oidcTestConfig{ - Userinfo: jwt.MapClaims{oidcRoleName: []string{rbac.RoleTemplateAdmin().String(), rbac.RoleUserAdmin().String()}}, + Userinfo: map[string]any{oidcRoleName: []string{rbac.RoleTemplateAdmin().String(), rbac.RoleUserAdmin().String()}}, Config: func(cfg *coderd.OIDCConfig) { cfg.AllowSignups = true }, @@ -408,7 +407,7 @@ func TestUserOIDC(t *testing.T) { // User starts with the owner role sub := uuid.NewString() - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", "roles": []string{"random", oidcRoleName, rbac.RoleOwner().String()}, "sub": sub, @@ -417,7 +416,7 @@ func TestUserOIDC(t *testing.T) { runner.AssertRoles(t, "alice", []string{rbac.RoleTemplateAdmin().String(), rbac.RoleUserAdmin().String(), rbac.RoleOwner().String()}) // Now login with oauth again, and check the roles are removed. - _, resp = runner.Login(t, jwt.MapClaims{ + _, resp = runner.Login(t, map[string]any{ "email": "alice@coder.com", "roles": []string{"random"}, "sub": sub, @@ -442,7 +441,7 @@ func TestUserOIDC(t *testing.T) { }) sub := uuid.NewString() - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", "roles": []string{}, "sub": sub, @@ -487,7 +486,7 @@ func TestUserOIDC(t *testing.T) { require.NoError(t, err) require.Len(t, group.Members, 0) - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{groupName}, "sub": uuid.New(), @@ -522,7 +521,7 @@ func TestUserOIDC(t *testing.T) { require.NoError(t, err) require.Len(t, group.Members, 0) - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{oidcGroupName}, "sub": uuid.New(), @@ -559,7 +558,7 @@ func TestUserOIDC(t *testing.T) { require.NoError(t, err) require.Len(t, group.Members, 0) - client, resp := runner.Login(t, jwt.MapClaims{ + client, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{groupName}, "sub": uuid.New(), @@ -568,7 +567,7 @@ func TestUserOIDC(t *testing.T) { runner.AssertGroups(t, "alice", []string{groupName}) // Refresh without the group claim - runner.ForceRefresh(t, client, jwt.MapClaims{ + runner.ForceRefresh(t, client, map[string]any{ "email": "alice@coder.com", }) runner.AssertGroups(t, "alice", []string{}) @@ -597,7 +596,7 @@ func TestUserOIDC(t *testing.T) { require.Len(t, group.Members, 0) sub := uuid.NewString() - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{groupName}, "sub": sub, @@ -606,7 +605,7 @@ func TestUserOIDC(t *testing.T) { runner.AssertGroups(t, "alice", []string{groupName}) // Refresh without the group claim - _, resp = runner.Login(t, jwt.MapClaims{ + _, resp = runner.Login(t, map[string]any{ "email": "alice@coder.com", "sub": sub, }) @@ -629,7 +628,7 @@ func TestUserOIDC(t *testing.T) { }, }) - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{"not-exists"}, "sub": uuid.New(), @@ -655,7 +654,7 @@ func TestUserOIDC(t *testing.T) { }, }) - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{groupName}, "sub": uuid.New(), @@ -682,7 +681,7 @@ func TestUserOIDC(t *testing.T) { }) // User starts with the owner role - _, resp := runner.Login(t, jwt.MapClaims{ + _, resp := runner.Login(t, map[string]any{ "email": "alice@coder.com", // This is sent as a **string** intentionally instead // of an array. @@ -710,7 +709,7 @@ func TestUserOIDC(t *testing.T) { // Test forbidden sub := uuid.NewString() - _, resp := runner.AttemptLogin(t, jwt.MapClaims{ + _, resp := runner.AttemptLogin(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{"not-allowed"}, "sub": sub, @@ -718,7 +717,7 @@ func TestUserOIDC(t *testing.T) { require.Equal(t, http.StatusForbidden, resp.StatusCode) // Test allowed - client, _ := runner.Login(t, jwt.MapClaims{ + client, _ := runner.Login(t, map[string]any{ "email": "alice@coder.com", groupClaim: []string{allowedGroup}, "sub": sub, @@ -743,7 +742,7 @@ func TestUserOIDC(t *testing.T) { }, }) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "sub": uuid.NewString(), } @@ -772,7 +771,7 @@ func TestUserOIDC(t *testing.T) { }, }) - claims := jwt.MapClaims{ + claims := map[string]any{ "email": "alice@coder.com", "sub": uuid.NewString(), } @@ -810,7 +809,7 @@ func TestGroupSync(t *testing.T) { expectedUserGroups []string // expectedOrgGroups is expected all groups on the system expectedOrgGroups []string - claims jwt.MapClaims + claims map[string]any }{ { name: "NoGroups", @@ -819,7 +818,7 @@ func TestGroupSync(t *testing.T) { initialOrgGroups: []string{}, expectedUserGroups: []string{}, expectedOrgGroups: []string{}, - claims: jwt.MapClaims{}, + claims: map[string]any{}, }, { name: "GroupSyncDisabled", @@ -832,7 +831,7 @@ func TestGroupSync(t *testing.T) { initialUserGroups: []string{"b", "c", "d"}, expectedUserGroups: []string{"b", "c", "d"}, expectedOrgGroups: []string{"a", "b", "c", "d"}, - claims: jwt.MapClaims{}, + claims: map[string]any{}, }, { // From a,c,b -> b,c,d @@ -844,7 +843,7 @@ func TestGroupSync(t *testing.T) { initialUserGroups: []string{"a", "b", "c"}, expectedUserGroups: []string{"b", "c", "d"}, expectedOrgGroups: []string{"a", "b", "c", "d"}, - claims: jwt.MapClaims{ + claims: map[string]any{ // D -> d mapped "groups": []string{"b", "c", "D"}, }, @@ -859,7 +858,7 @@ func TestGroupSync(t *testing.T) { initialUserGroups: []string{"a", "b", "c"}, expectedUserGroups: []string{}, expectedOrgGroups: []string{"a", "b", "c", "d"}, - claims: jwt.MapClaims{ + claims: map[string]any{ // No claim == no groups }, }, @@ -873,7 +872,7 @@ func TestGroupSync(t *testing.T) { initialUserGroups: []string{"a", "b", "c"}, expectedUserGroups: []string{"b", "c", "d", "e", "f"}, expectedOrgGroups: []string{"a", "b", "c", "d", "e", "f"}, - claims: jwt.MapClaims{ + claims: map[string]any{ "groups": []string{"b", "c", "d", "e", "f"}, }, }, @@ -890,7 +889,7 @@ func TestGroupSync(t *testing.T) { initialUserGroups: []string{"a", "b", "c"}, expectedUserGroups: []string{"b", "c", "d", "e", "f", "z"}, expectedOrgGroups: []string{"a", "b", "c", "d", "e", "f", "z"}, - claims: jwt.MapClaims{ + claims: map[string]any{ "groups": []string{ "b", "c", "d", "e", "f", // These groups are ignored @@ -1093,17 +1092,17 @@ type oidcTestRunner struct { // Login will call the OIDC flow with an unauthenticated client. // The IDP will return the idToken claims. - Login func(t *testing.T, idToken jwt.MapClaims) (*codersdk.Client, *http.Response) - AttemptLogin func(t *testing.T, idToken jwt.MapClaims) (*codersdk.Client, *http.Response) + Login func(t *testing.T, idToken map[string]any) (*codersdk.Client, *http.Response) + AttemptLogin func(t *testing.T, idToken map[string]any) (*codersdk.Client, *http.Response) // ForceRefresh will use an authenticated codersdk.Client, and force their // OIDC token to be expired and require a refresh. The refresh will use the claims provided. // It just calls the /users/me endpoint to trigger the refresh. - ForceRefresh func(t *testing.T, client *codersdk.Client, idToken jwt.MapClaims) + ForceRefresh func(t *testing.T, client *codersdk.Client, idToken map[string]any) ExpireOauthToken func(t *testing.T, client *codersdk.Client) } type oidcTestConfig struct { - Userinfo jwt.MapClaims + Userinfo map[string]any // Config allows modifying the Coderd OIDC configuration. Config func(cfg *coderd.OIDCConfig) @@ -1218,7 +1217,7 @@ func setupOIDCTest(t *testing.T, settings oidcTestConfig) *oidcTestRunner { API: api, Login: helper.Login, AttemptLogin: helper.AttemptLogin, - ForceRefresh: func(t *testing.T, client *codersdk.Client, idToken jwt.MapClaims) { + ForceRefresh: func(t *testing.T, client *codersdk.Client, idToken map[string]any) { helper.ForceRefresh(t, api.Database, client, idToken) }, ExpireOauthToken: func(t *testing.T, client *codersdk.Client) { diff --git a/go.mod b/go.mod index 31b033c1ff1..3486a32efe8 100644 --- a/go.mod +++ b/go.mod @@ -223,7 +223,6 @@ require ( github.com/go-playground/validator/v10 v10.30.0 github.com/gofrs/flock v0.13.0 github.com/gohugoio/hugo v0.163.3 - github.com/golang-jwt/jwt/v4 v4.5.2 github.com/golang-migrate/migrate/v4 v4.20.1 github.com/gomarkdown/markdown v0.0.0-20260724235538-61af6e1e6971 github.com/google/go-cmp v0.7.0 diff --git a/go.sum b/go.sum index 017cb0cc6d4..b798fc970fc 100644 --- a/go.sum +++ b/go.sum @@ -617,8 +617,6 @@ github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0 h1:I/n6v7VImJ3aISLnn7 github.com/gohugoio/hugo-goldmark-extensions/extras v0.7.0/go.mod h1:9LJNfKWFmhEJ7HW0in5znezMwH+FYMBIhNZ3VWtRcRs= github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.5.0 h1:p13Q0DBCrBRpJGtbtlgkYNCs4TnIlZJh8vHgnAiofrI= github.com/gohugoio/hugo-goldmark-extensions/passthrough v0.5.0/go.mod h1:ob9PCHy/ocsQhTz68uxhyInaYCbbVNpOOrJkIoSeD+8= -github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI= -github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= diff --git a/scripts/testidp/main.go b/scripts/testidp/main.go index 7496c680ed7..39665e20d1f 100644 --- a/scripts/testidp/main.go +++ b/scripts/testidp/main.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "github.com/stretchr/testify/require" @@ -85,7 +84,7 @@ func RunIDP() func(t *testing.T) { return func(t *testing.T) { idp := oidctest.NewFakeIDP(t, oidctest.WithServing(), - oidctest.WithStaticUserInfo(jwt.MapClaims{ + oidctest.WithStaticUserInfo(map[string]any{ // This is a static set of auth fields. Might be beneficial to make flags // to allow different values here. This is only required for using the // testIDP as primary auth. External auth does not ever fetch these fields. @@ -96,7 +95,7 @@ func RunIDP() func(t *testing.T) { "groups": []string{"testidp", "qa", "engineering"}, "roles": []string{"testidp", "admin", "higher_power"}, }), - oidctest.WithDefaultIDClaims(jwt.MapClaims{ + oidctest.WithDefaultIDClaims(map[string]any{ "sub": uuid.MustParse("26c6a19c-b9b8-493b-a991-88a4c3310314"), }), oidctest.WithDefaultExpire(*expiry),