From 8d9e55c33c1e041eadf519ee9c2bc1c56649a923 Mon Sep 17 00:00:00 2001 From: Dmitry Verkhoturov Date: Thu, 18 Jan 2024 10:23:47 +0100 Subject: [PATCH 1/5] update github.com/golang-jwt/jwt to v5 --- backend/app/cmd/server.go | 21 ++++++++----- backend/app/cmd/server_test.go | 37 ++++++----------------- backend/app/rest/api/admin.go | 13 ++++++-- backend/app/rest/api/admin_test.go | 22 +++++++------- backend/app/rest/api/rest_private.go | 18 +++++------ backend/app/rest/api/rest_private_test.go | 10 +++--- 6 files changed, 57 insertions(+), 64 deletions(-) diff --git a/backend/app/cmd/server.go b/backend/app/cmd/server.go index 3810c5ca0c..990d359e6f 100644 --- a/backend/app/cmd/server.go +++ b/backend/app/cmd/server.go @@ -19,7 +19,7 @@ import ( "github.com/go-pkgz/lcw/v2/eventbus" log "github.com/go-pkgz/lgr" ntf "github.com/go-pkgz/notify" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "github.com/kyokomi/emoji/v2" bolt "go.etcd.io/bbolt" @@ -1109,10 +1109,10 @@ func (s *ServerCommand) makeNotifyDestinations(authenticator *auth.Service) ([]n TokenGenFn: func(userID, email, site string) (string, error) { claims := token.Claims{ Handshake: &token.Handshake{ID: userID + "::" + email}, - StandardClaims: jwt.StandardClaims{ - Audience: site, - ExpiresAt: time.Now().Add(100 * 365 * 24 * time.Hour).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{site}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(100 * 365 * 24 * time.Hour)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), Issuer: "remark42", }, } @@ -1215,10 +1215,15 @@ func (s *ServerCommand) getAuthenticator(ds *service.DataStore, avas avatar.Stor if c.User == nil { return c } - c.User.SetAdmin(ds.IsAdmin(c.Audience, c.User.ID)) - c.User.SetBoolAttr("blocked", ds.IsBlocked(c.Audience, c.User.ID)) + if len(c.Audience) != 1 { + return c + } + audience := c.Audience[0] + + c.User.SetAdmin(ds.IsAdmin(audience, c.User.ID)) + c.User.SetBoolAttr("blocked", ds.IsBlocked(audience, c.User.ID)) var err error - c.User.Email, err = ds.GetUserEmail(c.Audience, c.User.ID) + c.User.Email, err = ds.GetUserEmail(audience, c.User.ID) if err != nil { log.Printf("[WARN] can't read email for %s, %v", c.User.ID, err) } diff --git a/backend/app/cmd/server_test.go b/backend/app/cmd/server_test.go index 66ecc06872..251189ff80 100644 --- a/backend/app/cmd/server_test.go +++ b/backend/app/cmd/server_test.go @@ -16,7 +16,7 @@ import ( "time" "github.com/go-pkgz/auth/token" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "github.com/jessevdk/go-flags" "go.uber.org/goleak" @@ -609,11 +609,11 @@ func TestServerAuthHooks(t *testing.T) { tkService.TokenDuration = time.Second claims := token.Claims{ - StandardClaims: jwt.StandardClaims{ - Audience: "remark", + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{"remark"}, Issuer: "remark", - ExpiresAt: time.Now().Add(time.Second).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Second)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, User: &token.User{ ID: "github_dev", @@ -637,10 +637,10 @@ func TestServerAuthHooks(t *testing.T) { require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusCreated, resp.StatusCode, "non-blocked user able to post") - // try to add comment with no-aud claim - badClaimsNoAud := claims - badClaimsNoAud.Audience = "" - tkNoAud, err := tkService.Token(badClaimsNoAud) + // add comment with no-aud claim + claimsNoAud := claims + claimsNoAud.Audience = jwt.ClaimStrings{""} + tkNoAud, err := tkService.Token(claimsNoAud) require.NoError(t, err) t.Logf("no-aud claims: %s", tkNoAud) req, err = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/api/v1/comment", port), @@ -655,25 +655,6 @@ func TestServerAuthHooks(t *testing.T) { require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user without aud claim rejected, \n"+tkNoAud+"\n"+string(body)) - // try to add comment without user set - badClaimsNoUser := claims - badClaimsNoUser.Audience = "remark" - badClaimsNoUser.User = nil - tkNoUser, err := tkService.Token(badClaimsNoUser) - require.NoError(t, err) - t.Logf("no user claims: %s", tkNoUser) - req, err = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/api/v1/comment", port), - strings.NewReader(`{"text": "test 123", "locator":{"url": "https://radio-t.com/p/2018/12/29/podcast-631/", - "site": "remark"}}`)) - require.NoError(t, err) - req.Header.Set("X-JWT", tkNoUser) - resp, err = client.Do(req) - require.NoError(t, err) - body, err = io.ReadAll(resp.Body) - require.NoError(t, err) - require.NoError(t, resp.Body.Close()) - assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user without user information rejected, \n"+tkNoUser+"\n"+string(body)) - // block user github_dev as admin req, err = http.NewRequest(http.MethodPut, fmt.Sprintf("http://localhost:%d/api/v1/admin/user/github_dev?site=remark&block=1&ttl=10d", port), http.NoBody) diff --git a/backend/app/rest/api/admin.go b/backend/app/rest/api/admin.go index d6e1f94b88..49b3bd8a5c 100644 --- a/backend/app/rest/api/admin.go +++ b/backend/app/rest/api/admin.go @@ -107,13 +107,20 @@ func (a *admin) deleteMeRequestCtrl(w http.ResponseWriter, r *http.Request) { return } - if err = a.dataService.DeleteUserDetail(claims.Audience, claims.User.ID, engine.AllUserDetails); err != nil { + if len(claims.Audience) != 1 { + rest.SendErrorJSON(w, r, http.StatusBadRequest, fmt.Errorf("bad request"), "can't process token, aud is not a single element", rest.ErrActionRejected) + return + } + + audience := claims.Audience[0] + + if err = a.dataService.DeleteUserDetail(audience, claims.User.ID, engine.AllUserDetails); err != nil { code := parseError(err, rest.ErrInternal) rest.SendErrorJSON(w, r, http.StatusBadRequest, err, "can't delete user details for user", code) return } - if err = a.dataService.DeleteUser(claims.Audience, claims.User.ID, store.HardDelete); err != nil { + if err = a.dataService.DeleteUser(audience, claims.User.ID, store.HardDelete); err != nil { rest.SendErrorJSON(w, r, http.StatusBadRequest, err, "can't delete user", rest.ErrNoAccess) return } @@ -126,7 +133,7 @@ func (a *admin) deleteMeRequestCtrl(w http.ResponseWriter, r *http.Request) { } } - a.cache.Flush(cache.Flusher(claims.Audience).Scopes(claims.Audience, claims.User.ID, lastCommentsScope)) + a.cache.Flush(cache.Flusher(audience).Scopes(audience, claims.User.ID, lastCommentsScope)) render.Status(r, http.StatusOK) render.JSON(w, r, R.JSON{"user_id": claims.User.ID, "site_id": claims.Audience}) } diff --git a/backend/app/rest/api/admin_test.go b/backend/app/rest/api/admin_test.go index 644a8ce510..577c9bb11e 100644 --- a/backend/app/rest/api/admin_test.go +++ b/backend/app/rest/api/admin_test.go @@ -16,7 +16,7 @@ import ( "github.com/go-pkgz/auth/token" cache "github.com/go-pkgz/lcw/v2" R "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -708,12 +708,12 @@ func TestAdmin_DeleteMeRequest(t *testing.T) { claims := token.Claims{ SessionOnly: true, - StandardClaims: jwt.StandardClaims{ - Audience: "remark42", - Id: "1234567", + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{"remark42"}, + ID: "1234567", Issuer: "remark42", - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), }, User: &token.User{ ID: "user1", @@ -777,12 +777,12 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) { // try with bad auth claims := token.Claims{ SessionOnly: true, - StandardClaims: jwt.StandardClaims{ - Audience: "remark42", - Id: "provider1_1234567", + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{"remark42"}, + ID: "provider1_1234567", Issuer: "remark42", - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), }, User: &token.User{ ID: "provider1_user1", diff --git a/backend/app/rest/api/rest_private.go b/backend/app/rest/api/rest_private.go index d723a1a2aa..41e4b2ce12 100644 --- a/backend/app/rest/api/rest_private.go +++ b/backend/app/rest/api/rest_private.go @@ -21,7 +21,7 @@ import ( cache "github.com/go-pkgz/lcw/v2" log "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "github.com/hashicorp/go-multierror" "github.com/umputun/remark42/backend/app/notify" @@ -362,10 +362,10 @@ func (s *private) sendEmailConfirmationCtrl(w http.ResponseWriter, r *http.Reque claims := token.Claims{ Handshake: &token.Handshake{ID: user.ID + "::" + subscribe.Address}, - StandardClaims: jwt.StandardClaims{ - Audience: r.URL.Query().Get("site"), - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{r.URL.Query().Get("site")}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), Issuer: "remark42", }, } @@ -704,11 +704,11 @@ func (s *private) deleteMeCtrl(w http.ResponseWriter, r *http.Request) { siteID := r.URL.Query().Get("site") claims := token.Claims{ - StandardClaims: jwt.StandardClaims{ - Audience: siteID, + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{siteID}, Issuer: "remark42", - ExpiresAt: time.Now().AddDate(0, 3, 0).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + ExpiresAt: jwt.NewNumericDate(time.Now().AddDate(0, 3, 0)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, User: &token.User{ ID: user.ID, diff --git a/backend/app/rest/api/rest_private_test.go b/backend/app/rest/api/rest_private_test.go index cea721fbd9..6d0d4c8814 100644 --- a/backend/app/rest/api/rest_private_test.go +++ b/backend/app/rest/api/rest_private_test.go @@ -20,7 +20,7 @@ import ( "github.com/go-pkgz/auth/token" "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -861,10 +861,10 @@ func TestRest_EmailAndTelegram(t *testing.T) { // issue good token claims := token.Claims{ Handshake: &token.Handshake{ID: "provider1_dev::good@example.com"}, - StandardClaims: jwt.StandardClaims{ - Audience: "remark42", - ExpiresAt: time.Now().Add(10 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + Audience: jwt.ClaimStrings{"remark42"}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(10 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), Issuer: "remark42", }, } From e3ad01b555294a4f844c4f0a8201223ec064fa57 Mon Sep 17 00:00:00 2001 From: Dmitry Verkhoturov Date: Thu, 11 Apr 2024 00:11:34 +0200 Subject: [PATCH 2/5] migrate to go-pkgz/auth/v2 --- backend/app/cmd/avatar.go | 2 +- backend/app/cmd/avatar_test.go | 2 +- backend/app/cmd/server.go | 18 +++++++++--------- backend/app/cmd/server_test.go | 2 +- backend/app/rest/api/admin.go | 2 +- backend/app/rest/api/admin_test.go | 2 +- backend/app/rest/api/rest.go | 2 +- backend/app/rest/api/rest_private.go | 4 ++-- backend/app/rest/api/rest_private_test.go | 2 +- backend/app/rest/api/rest_test.go | 8 ++++---- backend/app/rest/user.go | 2 +- 11 files changed, 23 insertions(+), 23 deletions(-) diff --git a/backend/app/cmd/avatar.go b/backend/app/cmd/avatar.go index 3baa418553..d5a91427ca 100644 --- a/backend/app/cmd/avatar.go +++ b/backend/app/cmd/avatar.go @@ -7,7 +7,7 @@ import ( log "github.com/go-pkgz/lgr" bolt "go.etcd.io/bbolt" - "github.com/go-pkgz/auth/avatar" + "github.com/go-pkgz/auth/v2/avatar" ) // AvatarCommand set of flags and command for avatar migration diff --git a/backend/app/cmd/avatar_test.go b/backend/app/cmd/avatar_test.go index 551ed6d77c..a2bc7673a4 100644 --- a/backend/app/cmd/avatar_test.go +++ b/backend/app/cmd/avatar_test.go @@ -5,7 +5,7 @@ import ( "os" "testing" - "github.com/go-pkgz/auth/avatar" + "github.com/go-pkgz/auth/v2/avatar" "github.com/jessevdk/go-flags" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/backend/app/cmd/server.go b/backend/app/cmd/server.go index 990d359e6f..42c9b3f38b 100644 --- a/backend/app/cmd/server.go +++ b/backend/app/cmd/server.go @@ -23,11 +23,11 @@ import ( "github.com/kyokomi/emoji/v2" bolt "go.etcd.io/bbolt" - "github.com/go-pkgz/auth" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/provider" - "github.com/go-pkgz/auth/provider/sender" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/provider" + "github.com/go-pkgz/auth/v2/provider/sender" + "github.com/go-pkgz/auth/v2/token" cache "github.com/go-pkgz/lcw/v2" "github.com/umputun/remark42/backend/app/migrator" @@ -1355,11 +1355,11 @@ func newAuthRefreshCache() *authRefreshCache { } // Get implements cache getter with key converted to string -func (c *authRefreshCache) Get(key interface{}) (interface{}, bool) { - return c.LoadingCache.Peek(key.(string)) +func (c *authRefreshCache) Get(key string) (token.Claims, bool) { + return c.LoadingCache.Peek(key) } // Set implements cache setter with key converted to string -func (c *authRefreshCache) Set(key, value interface{}) { - _, _ = c.LoadingCache.Get(key.(string), func() (token.Claims, error) { return value.(token.Claims), nil }) +func (c *authRefreshCache) Set(key string, value token.Claims) { + _, _ = c.LoadingCache.Get(key, func() (token.Claims, error) { return value, nil }) } diff --git a/backend/app/cmd/server_test.go b/backend/app/cmd/server_test.go index 251189ff80..bc13ba9e83 100644 --- a/backend/app/cmd/server_test.go +++ b/backend/app/cmd/server_test.go @@ -15,7 +15,7 @@ import ( "testing" "time" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" "github.com/golang-jwt/jwt/v5" "github.com/jessevdk/go-flags" "go.uber.org/goleak" diff --git a/backend/app/rest/api/admin.go b/backend/app/rest/api/admin.go index 49b3bd8a5c..34ab993395 100644 --- a/backend/app/rest/api/admin.go +++ b/backend/app/rest/api/admin.go @@ -8,7 +8,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/render" - "github.com/go-pkgz/auth" + "github.com/go-pkgz/auth/v2" cache "github.com/go-pkgz/lcw/v2" log "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" diff --git a/backend/app/rest/api/admin_test.go b/backend/app/rest/api/admin_test.go index 577c9bb11e..ecbe33dd94 100644 --- a/backend/app/rest/api/admin_test.go +++ b/backend/app/rest/api/admin_test.go @@ -13,7 +13,7 @@ import ( "testing" "time" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" cache "github.com/go-pkgz/lcw/v2" R "github.com/go-pkgz/rest" "github.com/golang-jwt/jwt/v5" diff --git a/backend/app/rest/api/rest.go b/backend/app/rest/api/rest.go index 293e793daa..5922fc3045 100644 --- a/backend/app/rest/api/rest.go +++ b/backend/app/rest/api/rest.go @@ -21,7 +21,7 @@ import ( "github.com/go-chi/chi/v5/middleware" "github.com/go-chi/cors" "github.com/go-chi/render" - "github.com/go-pkgz/auth" + "github.com/go-pkgz/auth/v2" "github.com/go-pkgz/lcw/v2" log "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" diff --git a/backend/app/rest/api/rest_private.go b/backend/app/rest/api/rest_private.go index 41e4b2ce12..cbe957929e 100644 --- a/backend/app/rest/api/rest_private.go +++ b/backend/app/rest/api/rest_private.go @@ -16,8 +16,8 @@ import ( "github.com/go-chi/chi/v5" "github.com/go-chi/render" - "github.com/go-pkgz/auth" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2" + "github.com/go-pkgz/auth/v2/token" cache "github.com/go-pkgz/lcw/v2" log "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" diff --git a/backend/app/rest/api/rest_private_test.go b/backend/app/rest/api/rest_private_test.go index 6d0d4c8814..8bdb440d16 100644 --- a/backend/app/rest/api/rest_private_test.go +++ b/backend/app/rest/api/rest_private_test.go @@ -17,7 +17,7 @@ import ( "time" "github.com/go-chi/render" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" "github.com/go-pkgz/lgr" R "github.com/go-pkgz/rest" "github.com/golang-jwt/jwt/v5" diff --git a/backend/app/rest/api/rest_test.go b/backend/app/rest/api/rest_test.go index 804e2c210d..f5085c1036 100644 --- a/backend/app/rest/api/rest_test.go +++ b/backend/app/rest/api/rest_test.go @@ -16,10 +16,10 @@ import ( "testing" "time" - "github.com/go-pkgz/auth" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/provider" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/provider" + "github.com/go-pkgz/auth/v2/token" cache "github.com/go-pkgz/lcw/v2" R "github.com/go-pkgz/rest" "github.com/stretchr/testify/assert" diff --git a/backend/app/rest/user.go b/backend/app/rest/user.go index f908bea93f..44963333ab 100644 --- a/backend/app/rest/user.go +++ b/backend/app/rest/user.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" "github.com/umputun/remark42/backend/app/store" ) From c2d386230cef9cd56838abe373779708b521fff8 Mon Sep 17 00:00:00 2001 From: Dmitry Verkhoturov Date: Thu, 11 Apr 2024 00:11:50 +0200 Subject: [PATCH 3/5] vendor new modules --- backend/go.mod | 4 +- backend/go.sum | 6 +- .../vendor/github.com/go-pkgz/auth/.gitignore | 15 - .../github.com/go-pkgz/auth/.golangci.yml | 89 --- .../vendor/github.com/go-pkgz/auth/README.md | 638 ------------------ .../github.com/go-pkgz/auth/{ => v2}/LICENSE | 0 .../github.com/go-pkgz/auth/{ => v2}/auth.go | 47 +- .../go-pkgz/auth/{ => v2}/avatar/avatar.go | 4 +- .../go-pkgz/auth/{ => v2}/avatar/bolt.go | 0 .../go-pkgz/auth/{ => v2}/avatar/gridfs.go | 0 .../go-pkgz/auth/{ => v2}/avatar/localfs.go | 0 .../go-pkgz/auth/{ => v2}/avatar/noop.go | 0 .../go-pkgz/auth/{ => v2}/avatar/store.go | 2 +- .../go-pkgz/auth/{ => v2}/logger/interface.go | 0 .../go-pkgz/auth/{ => v2}/middleware/auth.go | 14 +- .../auth/{ => v2}/middleware/user_updater.go | 2 +- .../go-pkgz/auth/{ => v2}/provider/apple.go | 32 +- .../auth/{ => v2}/provider/apple_pubkeys.go | 2 +- .../auth/{ => v2}/provider/custom_server.go | 6 +- .../auth/{ => v2}/provider/dev_provider.go | 6 +- .../go-pkgz/auth/{ => v2}/provider/direct.go | 12 +- .../go-pkgz/auth/{ => v2}/provider/oauth1.go | 20 +- .../go-pkgz/auth/{ => v2}/provider/oauth2.go | 20 +- .../auth/{ => v2}/provider/providers.go | 2 +- .../auth/{ => v2}/provider/sender/email.go | 2 +- .../go-pkgz/auth/{ => v2}/provider/service.go | 2 +- .../auth/{ => v2}/provider/telegram.go | 16 +- .../go-pkgz/auth/{ => v2}/provider/verify.go | 20 +- .../go-pkgz/auth/{ => v2}/token/jwt.go | 77 ++- .../go-pkgz/auth/{ => v2}/token/user.go | 0 .../golang-jwt/jwt/MIGRATION_GUIDE.md | 22 - .../github.com/golang-jwt/jwt/README.md | 113 ---- .../github.com/golang-jwt/jwt/claims.go | 146 ---- .../github.com/golang-jwt/jwt/errors.go | 59 -- .../github.com/golang-jwt/jwt/map_claims.go | 120 ---- .../github.com/golang-jwt/jwt/parser.go | 148 ---- .../golang-jwt/jwt/signing_method.go | 35 - .../vendor/github.com/golang-jwt/jwt/token.go | 104 --- .../golang-jwt/jwt/{ => v5}/.gitignore | 0 .../golang-jwt/jwt/{ => v5}/LICENSE | 0 .../golang-jwt/jwt/v5/MIGRATION_GUIDE.md | 195 ++++++ .../github.com/golang-jwt/jwt/v5/README.md | 167 +++++ .../github.com/golang-jwt/jwt/v5/SECURITY.md | 19 + .../jwt/{ => v5}/VERSION_HISTORY.md | 18 +- .../github.com/golang-jwt/jwt/v5/claims.go | 16 + .../github.com/golang-jwt/jwt/{ => v5}/doc.go | 0 .../golang-jwt/jwt/{ => v5}/ecdsa.go | 30 +- .../golang-jwt/jwt/{ => v5}/ecdsa_utils.go | 8 +- .../golang-jwt/jwt/{ => v5}/ed25519.go | 48 +- .../golang-jwt/jwt/{ => v5}/ed25519_utils.go | 8 +- .../github.com/golang-jwt/jwt/v5/errors.go | 49 ++ .../golang-jwt/jwt/v5/errors_go1_20.go | 47 ++ .../golang-jwt/jwt/v5/errors_go_other.go | 78 +++ .../golang-jwt/jwt/{ => v5}/hmac.go | 41 +- .../golang-jwt/jwt/v5/map_claims.go | 109 +++ .../golang-jwt/jwt/{ => v5}/none.go | 20 +- .../github.com/golang-jwt/jwt/v5/parser.go | 238 +++++++ .../golang-jwt/jwt/v5/parser_option.go | 128 ++++ .../golang-jwt/jwt/v5/registered_claims.go | 63 ++ .../github.com/golang-jwt/jwt/{ => v5}/rsa.go | 28 +- .../golang-jwt/jwt/{ => v5}/rsa_pss.go | 29 +- .../golang-jwt/jwt/{ => v5}/rsa_utils.go | 20 +- .../golang-jwt/jwt/v5/signing_method.go | 49 ++ .../golang-jwt/jwt/v5/staticcheck.conf | 1 + .../github.com/golang-jwt/jwt/v5/token.go | 100 +++ .../golang-jwt/jwt/v5/token_option.go | 5 + .../github.com/golang-jwt/jwt/v5/types.go | 149 ++++ .../github.com/golang-jwt/jwt/v5/validator.go | 316 +++++++++ backend/vendor/modules.txt | 22 +- 69 files changed, 2026 insertions(+), 1760 deletions(-) delete mode 100644 backend/vendor/github.com/go-pkgz/auth/.gitignore delete mode 100644 backend/vendor/github.com/go-pkgz/auth/.golangci.yml delete mode 100644 backend/vendor/github.com/go-pkgz/auth/README.md rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/LICENSE (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/auth.go (92%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/avatar.go (99%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/bolt.go (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/gridfs.go (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/localfs.go (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/noop.go (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/avatar/store.go (99%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/logger/interface.go (100%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/middleware/auth.go (96%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/middleware/user_updater.go (96%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/apple.go (96%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/apple_pubkeys.go (99%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/custom_server.go (98%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/dev_provider.go (98%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/direct.go (96%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/oauth1.go (93%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/oauth2.go (94%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/providers.go (99%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/sender/email.go (98%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/service.go (98%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/telegram.go (97%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/provider/verify.go (93%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/token/jwt.go (86%) rename backend/vendor/github.com/go-pkgz/auth/{ => v2}/token/user.go (100%) delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/README.md delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/claims.go delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/errors.go delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/map_claims.go delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/parser.go delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/signing_method.go delete mode 100644 backend/vendor/github.com/golang-jwt/jwt/token.go rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/.gitignore (100%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/LICENSE (100%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/README.md create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/VERSION_HISTORY.md (94%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/claims.go rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/doc.go (100%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/ecdsa.go (83%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/ecdsa_utils.go (81%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/ed25519.go (52%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/ed25519_utils.go (80%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/errors.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/hmac.go (53%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/map_claims.go rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/none.go (68%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/parser.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/parser_option.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/rsa.go (77%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/rsa_pss.go (83%) rename backend/vendor/github.com/golang-jwt/jwt/{ => v5}/rsa_utils.go (69%) create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/signing_method.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/token.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/token_option.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/types.go create mode 100644 backend/vendor/github.com/golang-jwt/jwt/v5/validator.go diff --git a/backend/go.mod b/backend/go.mod index 7445428642..f13512e113 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -13,7 +13,7 @@ require ( github.com/go-chi/chi/v5 v5.1.0 github.com/go-chi/cors v1.2.1 github.com/go-chi/render v1.0.3 - github.com/go-pkgz/auth v1.24.3-0.20241007090635-78537e6f812d + github.com/go-pkgz/auth/v2 v2.0.0-20241208183119-88b3a842be9f github.com/go-pkgz/jrpc v0.3.0 github.com/go-pkgz/lcw/v2 v2.0.0 github.com/go-pkgz/lgr v0.11.1 @@ -21,7 +21,7 @@ require ( github.com/go-pkgz/repeater v1.2.0 github.com/go-pkgz/rest v1.19.0 github.com/go-pkgz/syncs v1.3.2 - github.com/golang-jwt/jwt v3.2.2+incompatible + github.com/golang-jwt/jwt/v5 v5.2.1 github.com/google/uuid v1.6.0 github.com/gorilla/feeds v1.2.0 github.com/hashicorp/go-multierror v1.1.1 diff --git a/backend/go.sum b/backend/go.sum index 3b229e6cb8..ea26e7b547 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -60,8 +60,8 @@ github.com/go-chi/render v1.0.3 h1:AsXqd2a1/INaIfUSKq3G5uA8weYx20FOsM7uSoCyyt4= github.com/go-chi/render v1.0.3/go.mod h1:/gr3hVkmYR0YlEy3LxCuVRFzEu9Ruok+gFqbIofjao0= github.com/go-oauth2/oauth2/v4 v4.5.2 h1:CuZhD3lhGuI6aNLyUbRHXsgG2RwGRBOuCBfd4WQKqBQ= github.com/go-oauth2/oauth2/v4 v4.5.2/go.mod h1:wk/2uLImWIa9VVQDgxz99H2GDbhmfi/9/Xr+GvkSUSQ= -github.com/go-pkgz/auth v1.24.3-0.20241007090635-78537e6f812d h1:6iwosbIwyRm7k0lprEv5mFWpGg1qQKLWJNHL088+Bcs= -github.com/go-pkgz/auth v1.24.3-0.20241007090635-78537e6f812d/go.mod h1:xmnzq6g8mhemW1nHnkuByXkBXsHrNf9/qkiVwJugWIs= +github.com/go-pkgz/auth/v2 v2.0.0-20241208183119-88b3a842be9f h1:CDG4Xwk8oq5jFzBtm81vAoB38PgXeUndiSQN/G2vnPA= +github.com/go-pkgz/auth/v2 v2.0.0-20241208183119-88b3a842be9f/go.mod h1:aepr8uqw5PKidS+h2sJDvTWbqzyveHDyKNEAznDb3L8= github.com/go-pkgz/email v0.5.0 h1:fdtMDGJ8NwyBACLR0LYHaCIK/OeUwZHMhH7Q0+oty9U= github.com/go-pkgz/email v0.5.0/go.mod h1:BdxglsQnymzhfdbnncEE72a6DrucZHy6I+42LK2jLEc= github.com/go-pkgz/expirable-cache v0.1.0/go.mod h1:GTrEl0X+q0mPNqN6dtcQXksACnzCBQ5k/k1SwXJsZKs= @@ -88,6 +88,8 @@ github.com/go-test/deep v1.0.4/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3a github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY= github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= +github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= diff --git a/backend/vendor/github.com/go-pkgz/auth/.gitignore b/backend/vendor/github.com/go-pkgz/auth/.gitignore deleted file mode 100644 index 2c09a37228..0000000000 --- a/backend/vendor/github.com/go-pkgz/auth/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# Binaries for programs and plugins -*.exe -*.exe~ -*.dll -*.so -*.dylib - -# Test binary, build with `go test -c` -*.test - -# Output of the go coverage tool, specifically when used with LiteIDE -*.out -.vscode -*.cov -Dockerfile \ No newline at end of file diff --git a/backend/vendor/github.com/go-pkgz/auth/.golangci.yml b/backend/vendor/github.com/go-pkgz/auth/.golangci.yml deleted file mode 100644 index eab781a1a3..0000000000 --- a/backend/vendor/github.com/go-pkgz/auth/.golangci.yml +++ /dev/null @@ -1,89 +0,0 @@ -linters-settings: - govet: - check-shadowing: true - golint: - min-confidence: 0.6 - gocyclo: - min-complexity: 15 - maligned: - suggest-new: true - dupl: - threshold: 100 - goconst: - min-len: 2 - min-occurrences: 2 - misspell: - locale: US - lll: - line-length: 140 - gocritic: - enabled-tags: - - performance - - style - - experimental - disabled-checks: - - wrapperFunc - - hugeParam - - rangeValCopy - -linters: - disable-all: true - enable: - - megacheck - - revive - - govet - - unconvert - - gas - - misspell - - unused - - typecheck - - ineffassign - - stylecheck - - gochecknoinits - - exportloopref - - nakedret - - gosimple - - prealloc - - fast: false - - -run: - # modules-download-mode: vendor - skip-dirs: - - vendor - concurrency: 4 - -issues: - exclude-rules: - - text: "should have a package comment, unless it's in another file for this package" - linters: - - golint - - text: "exitAfterDefer:" - linters: - - gocritic - - text: "whyNoLint: include an explanation for nolint directive" - linters: - - gocritic - - text: "go.mongodb.org/mongo-driver/bson/primitive.E" - linters: - - govet - - text: "weak cryptographic primitive" - linters: - - gosec - - text: "at least one file in a package should have a package comment" - linters: - - stylecheck - - text: "should have a package comment" - linters: - - revive - - text: 'Deferring unsafe method "Close" on type "io.ReadCloser"' - linters: - - gosec - - linters: - - unparam - - unused - - revive - path: _test\.go$ - text: "unused-parameter" - exclude-use-default: false diff --git a/backend/vendor/github.com/go-pkgz/auth/README.md b/backend/vendor/github.com/go-pkgz/auth/README.md deleted file mode 100644 index 9e48ae4ca8..0000000000 --- a/backend/vendor/github.com/go-pkgz/auth/README.md +++ /dev/null @@ -1,638 +0,0 @@ -# auth - authentication via oauth2, direct and email -[![Build Status](https://github.com/go-pkgz/auth/workflows/build/badge.svg)](https://github.com/go-pkgz/auth/actions) [![Coverage Status](https://coveralls.io/repos/github/go-pkgz/auth/badge.svg?branch=master)](https://coveralls.io/github/go-pkgz/auth?branch=master) [![godoc](https://godoc.org/github.com/go-pkgz/auth?status.svg)](https://pkg.go.dev/github.com/go-pkgz/auth?tab=doc) - -This library provides "social login" with Github, Google, Facebook, Microsoft, Twitter, Yandex, Battle.net, Apple, Patreon, Discord and Telegram as well as custom auth providers and email verification. - -- Multiple oauth2 providers can be used at the same time -- Special `dev` provider allows local testing and development -- JWT stored in a secure cookie with XSRF protection. Cookies can be session-only -- Minimal scopes with user name, id and picture (avatar) only -- Direct authentication with user's provided credential checker -- Verified authentication with user's provided sender (email, im, etc) -- Custom oauth2 server and ability to use any third party provider -- Integrated avatar proxy with an FS, boltdb and gridfs storage -- Support of user-defined storage for avatars -- Identicon for default avatars -- Black list with user-defined validator -- Multiple aud (audience) supported -- Secure key with customizable `SecretReader` -- Ability to store an extra information to token and retrieve on login -- Pre-auth and post-auth hooks to handle custom use cases. -- Middleware for easy integration into http routers -- Wrappers to extract user info from the request -- Role based access control - -## Install - -`go get -u github.com/go-pkgz/auth` - -## Usage - -Example with chi router: - -```go - -func main() { - // define options - options := auth.Opts{ - SecretReader: token.SecretFunc(func(id string) (string, error) { // secret key for JWT - return "secret", nil - }), - TokenDuration: time.Minute * 5, // token expires in 5 minutes - CookieDuration: time.Hour * 24, // cookie expires in 1 day and will enforce re-login - Issuer: "my-test-app", - URL: "http://127.0.0.1:8080", - AvatarStore: avatar.NewLocalFS("/tmp"), - Validator: token.ValidatorFunc(func(_ string, claims token.Claims) bool { - // allow only dev_* names - return claims.User != nil && strings.HasPrefix(claims.User.Name, "dev_") - }), - } - - // create auth service with providers - service := auth.NewService(options) - service.AddProvider("github", "", "") // add github provider - service.AddProvider("facebook", "", "") // add facebook provider - - // retrieve auth middleware - m := service.Middleware() - - // setup http server - router := chi.NewRouter() - router.Get("/open", openRouteHandler) // open api - router.With(m.Auth).Get("/private", protectedRouteHandler) // protected api - - // setup auth routes - authRoutes, avaRoutes := service.Handlers() - router.Mount("/auth", authRoutes) // add auth handlers - router.Mount("/avatar", avaRoutes) // add avatar handler - - log.Fatal(http.ListenAndServe(":8080", router)) -} -``` - -## Middleware - -`github.com/go-pkgz/auth/middleware` provides ready-to-use middleware. - -- `middleware.Auth` - requires authenticated user -- `middleware.Admin` - requires authenticated admin user -- `middleware.Trace` - doesn't require authenticated user, but adds user info to request -- `middleware.RBAC` - requires authenticated user with passed role(s) - -Also, there is a special middleware `middleware.UpdateUser` for population and modifying UserInfo in every request. See "Customization" for more details. - -## Details - -Generally, adding support of `auth` includes a few relatively simple steps: - -1. Setup `auth.Opts` structure with all parameters. Each of them [documented](https://github.com/go-pkgz/auth/blob/master/auth.go#L29) and most of parameters are optional and have sane defaults. -2. [Create](https://github.com/go-pkgz/auth/blob/master/auth.go#L56) the new `auth.Service` with provided options. -3. [Add all](https://github.com/go-pkgz/auth/blob/master/auth.go#L149) desirable authentication providers. -4. Retrieve [middleware](https://github.com/go-pkgz/auth/blob/master/auth.go#L144) and [http handlers](https://github.com/go-pkgz/auth/blob/master/auth.go#L105) from `auth.Service` -5. Wire auth and avatar handlers into http router as sub–routes. - -### API - -For the example above authentication handlers wired as `/auth` and provides: - -- `/auth//login?site=&from=` - site_id used as `aud` claim for the token and can be processed by `SecretReader` to load/retrieve/define different secrets. redirect_url is the url to redirect after successful login. -- `/avatar/` - returns the avatar (image). Links to those pictures added into user info automatically, for details see "Avatar proxy" -- `/auth//logout` and `/auth/logout` - invalidate "session" by removing JWT cookie -- `/auth/list` - gives a json list of active providers -- `/auth/user` - returns `token.User` (json) -- `/auth/status` - returns status of logged in user (json) - -### User info - -Middleware populates `token.User` to request's context. It can be loaded with `token.GetUserInfo(r *http.Request) (user User, err error)` or `token.MustGetUserInfo(r *http.Request) User` functions. - -`token.User` object includes all fields retrieved from oauth2 provider: -- `Name` - user name -- `ID` - hash of user id -- `Picture` - full link to proxied avatar (see "Avatar proxy") - -It also has placeholders for fields application can populate with custom `token.ClaimsUpdater` (see "Customization") - -- `IP` - hash of user's IP address -- `Email` - user's email -- `Attributes` - map of string:any-value. To simplify management of this map some setters and getters provided, for example `users.StrAttr`, `user.SetBoolAttr` and so on. See [user.go](https://github.com/go-pkgz/auth/blob/master/token/user.go) for more details. - -### Avatar proxy - -Direct links to avatars won't survive any real-life usage if they linked from a public page. For example, page [like this](https://remark42.com/demo/) may have hundreds of avatars and, most likely, will trigger throttling on provider's side. To eliminate such restriction `auth` library provides an automatic proxy - -- On each login the proxy will retrieve user's picture and save it to `AvatarStore` -- Local (proxied) link to avatar included in user's info (jwt token) -- API for avatar removal provided as a part of `AvatarStore` -- User can leverage one of the provided stores: - - `avatar.LocalFS` - file system, each avatar in a separate file - - `avatar.BoltDB` - single [boltdb](https://go.etcd.io/bbolt) file (embedded KV store). - - `avatar.GridFS` - external [GridFS](https://docs.mongodb.com/manual/core/gridfs/) (mongo db). -- In case of need custom implementations of other stores can be passed in and used by `auth` library. Each store has to implement `avatar.Store` [interface](https://github.com/go-pkgz/auth/blob/master/avatar/store.go#L25). -- All avatar-related setup done as a part of `auth.Opts` and needs: - - `AvatarStore` - avatar store to use, i.e. `avatar.NewLocalFS("/tmp/avatars")` or more generic `avatar.NewStore(uri)` - - file system uri - `file:///tmp/location` or just `/tmp/location` - - boltdb - `bolt://tmp/avatars.bdb` - - mongo - `"mongodb://127.0.0.1:27017/test?ava_db=db1&ava_coll=coll1` - - `AvatarRoutePath` - route prefix for direct links to proxied avatar. For example `/api/v1/avatars` will make full links like this - `http://example.com/api/v1/avatars/1234567890123.image`. The url will be stored in user's token and retrieved by middleware (see "User Info") - - `AvatarResizeLimit` - size (in pixels) used to resize the avatar. Pls note - resize happens once as a part of `Put` call, i.e. on login. 0 size (default) disables resizing. - -### Direct authentication - -In addition to oauth2 providers `auth.Service` allows to use direct user-defined authentication. This is done by adding direct provider with `auth.AddDirectProvider`. - -```go - service.AddDirectProvider("local", provider.CredCheckerFunc(func(user, password string) (ok bool, err error) { - ok, err = checkUserSomehow(user, password) - return ok, err - })) -``` - -Such provider acts like any other, i.e. will be registered as `/auth/local/login`. - -The API for this provider supports both GET and POST requests: - -* POST request could be encoded as application/x-www-form-urlencoded or application/json: - ``` - POST /auth//login?session=[1|0] - body: application/x-www-form-urlencoded - user=&passwd=&aud= - ``` - ``` - POST /auth//login?session=[1|0] - body: application/json - { - "user": "name", - "passwd": "xyz", - "aud": "bar", - } - ``` -* GET request with user credentials provided as query params, but be aware that [the https query string is not secure](https://stackoverflow.com/a/323286/633961): - ``` - GET /auth//login?user=&passwd=&aud=&session=[1|0] - ``` - -_note: password parameter doesn't have to be naked/real password and can be any kind of password hash prepared by caller._ - -### Verified authentication - -Another non-oauth2 provider allowing user-confirmed authentication, for example by email or slack or telegram. This is -done by adding confirmed provider with `auth.AddVerifProvider`. - -```go - msgTemplate := "Confirmation email, token: {{.Token}}" - service.AddVerifProvider("email", msgTemplate, sender) -``` - -Message template may use the follow elements: - -- `{{.Address}}` - user address, for example email -- `{{.User}}` - user name -- `{{.Token}}` - confirmation token -- `{{.Site}}` - site ID - -Sender should be provided by end-user and implements a single function interface - -```go -type Sender interface { - Send(address string, text string) error -} -``` - -For convenience a functional wrapper `SenderFunc` provided. Email sender provided in `provider/sender` package and can be -used as `Sender`. - -The API for this provider: - - - `GET /auth//login?user=&address=
&aud=&from=` - send confirmation request to user - - `GET /auth//login?token=&sess=[1|0]` - authorize with confirmation token - -The provider acts like any other, i.e. will be registered as `/auth/email/login`. - -### Email - -For email notify provider, please use `github.com/go-pkgz/auth/provider/sender` package: -```go - sndr := sender.NewEmailClient(sender.EmailParams{ - Host: "email.hostname", - Port: 567, - SMTPUserName: "username", - SMTPPassword: "pass", - StartTLS: true, - InsecureSkipVerify: false, - From: "notify@email.hostname", - Subject: "subject", - ContentType: "text/html", - Charset: "UTF-8", - }, log.Default()) - authenticator.AddVerifProvider("email", "template goes here", sndr) -``` - -See [that documentation](https://github.com/go-pkgz/email#options) for full options list. - -### Telegram - -Telegram provider allows your users to log in with Telegram account. First, you will need to create your bot. -Contact [@BotFather](https://t.me/botfather) and follow his instructions to create your own bot (call it, for example, "My site auth bot") - -Next initialize TelegramHandler with following parameters: -* `ProviderName` - Any unique name to distinguish between providers -* `SuccessMsg` - Message sent to user on successfull authentication -* `ErrorMsg` - Message sent on errors (e.g. login request expired) -* `Telegram` - Telegram API implementation. Use provider.NewTelegramAPI with following arguments - 1. The secret token bot father gave you - 2. An http.Client for accessing Telegram API's - -```go -token := os.Getenv("TELEGRAM_TOKEN") - -telegram := provider.TelegramHandler{ - ProviderName: "telegram", - ErrorMsg: "❌ Invalid auth request. Please try clicking link again.", - SuccessMsg: "✅ You have successfully authenticated!", - Telegram: provider.NewTelegramAPI(token, http.DefaultClient), - - L: log.Default(), - TokenService: service.TokenService(), - AvatarSaver: service.AvatarProxy(), -} -``` - -After that run provider and register it's handlers: -```go -// Run Telegram provider in the background -go func() { - err := telegram.Run(context.Background()) - if err != nil { - log.Fatalf("[PANIC] failed to start telegram: %v", err) - } -}() - -// Register Telegram provider -service.AddCustomHandler(&telegram) -``` - -Now all your users have to do is click one of the following links and press **start** -`tg://resolve?domain=&start=` or `https://t.me//?start=` - -Use the following routes to interact with provider: -1. `/auth//login` - Obtain auth token. Returns JSON object with `bot` (bot username) and `token` (token itself) fields. -2. `/auth//login?token=` - Check if auth request has been confirmed (i.e. user pressed start). Sets session cookie and returns user info on success, errors with 404 otherwise. - -3. `/auth//logout` - Invalidate user session. - -### Custom oauth2 - -This provider brings two extra functions: - -1. Adds ability to use any third-party oauth2 providers in addition to the list of directly supported. Included [example](https://github.com/go-pkgz/auth/blob/master/_example/main.go#L113) demonstrates how to do it for bitbucket. -In order to add a new oauth2 provider following input is required: - * `Name` - any name is allowed except the names from list of supported providers. It is possible to register more than one client for one given oauth2 provider (for example using different names `bitbucket_dev` and `bitbucket_prod`) - * `Client` - ID and secret of client - * `Endpoint` - auth URL and token URL. This information could be obtained from auth2 provider page - * `InfoURL` - oauth2 provider API method to read information of logged in user. This method could be found in documentation of oauth2 provider (e.g. for bitbucket https://developer.atlassian.com/bitbucket/api/2/reference/resource/user) - * `MapUserFn` - function to convert the response from `InfoURL` to `token.User` (s. example below) - * `Scopes` - minimal needed scope to read user information. Client should be authorized to these scopes - ```go - c := auth.Client{ - Cid: os.Getenv("AEXMPL_BITBUCKET_CID"), - Csecret: os.Getenv("AEXMPL_BITBUCKET_CSEC"), - } - - service.AddCustomProvider("bitbucket", c, provider.CustomHandlerOpt{ - Endpoint: oauth2.Endpoint{ - AuthURL: "https://bitbucket.org/site/oauth2/authorize", - TokenURL: "https://bitbucket.org/site/oauth2/access_token", - }, - InfoURL: "https://api.bitbucket.org/2.0/user/", - MapUserFn: func(data provider.UserData, _ []byte) token.User { - userInfo := token.User{ - ID: "bitbucket_" + token.HashID(sha1.New(), - data.Value("username")), - Name: data.Value("nickname"), - } - return userInfo - }, - Scopes: []string{"account"}, - }) - ``` -2. Adds local oauth2 server user can fully customize. It uses [`gopkg.in/oauth2.v3`](https://github.com/go-oauth2/oauth2) library and example shows how [to initialize](https://github.com/go-pkgz/auth/blob/master/_example/main.go#L227) the server and [setup a provider](https://github.com/go-pkgz/auth/blob/master/_example/main.go#L100). - * to start local oauth2 server following options are required: - * `URL` - url of oauth2 server with port - * `WithLoginPage` - flag to define whether login page should be shown - * `LoginPageHandler` - function to handle login request. If not specified default login page will be shown - ```go - sopts := provider.CustomServerOpt{ - URL: "http://127.0.0.1:9096", - L: options.Logger, - WithLoginPage: true, - } - prov := provider.NewCustomServer(srv, sopts) - - // Start server - go prov.Run(context.Background()) - ``` - * to register handler for local oauth2 following option are required: - * `Name` - any name except the names from list of supported providers - * `Client` - ID and secret of client - * `HandlerOpt` - handler options of custom oauth provider - ```go - service.AddCustomProvider("custom123", auth.Client{Cid: "cid", Csecret: "csecret"}, prov.HandlerOpt) - ``` - -### Self-implemented auth handler -Additionally it is possible to implement own auth handler. It may be useful if auth provider does not conform to oauth standard. Self-implemented handler has to implement `provider.Provider` interface. -```go -// customHandler implements provider.Provider interface -c := customHandler{} - -// add customHandler to stack of auth handlers -service.AddCustomHandler(c) -``` - -### Customization - -There are several ways to adjust functionality of the library: - -1. `SecretReader` - interface with a single method `Get(aud string) string` to return the secret used for JWT signing and verification -1. `ClaimsUpdater` - interface with `Update(claims Claims) Claims` method. This is the primary way to alter a token at login time and add any attributes, set ip, email, admin status, roles and so on. -1. `Validator` - interface with `Validate(token string, claims Claims) bool` method. This is post-token hook and will be called on **each request** wrapped with `Auth` middleware. This will be the place for special logic to reject some tokens or users. -1. `UserUpdater` - interface with `Update(claims token.User) token.User` method. This method will be called on **each request** wrapped with `UpdateUser` middleware. This will be the place for special logic modify User Info in request context. [Example of usage.](https://github.com/go-pkgz/auth/blob/19c1b6d26608494955a4480f8f6165af85b1deab/_example/main.go#L189) - -All of the interfaces above have corresponding Func adapters - `SecretFunc`, `ClaimsUpdFunc`, `ValidatorFunc` and `UserUpdFunc`. - -### Implementing black list logic or some other filters - -Restricting some users or some tokens is two step process: - -- `ClaimsUpdater` sets an attribute, like `blocked` (or `allowed`) -- `Validator` checks the attribute and returns true/false - -_This technique used in the [example](https://github.com/go-pkgz/auth/blob/master/_example/main.go#L56) code_ - -The process can be simplified by doing all checks directly in `Validator`, but depends on particular case such solution -can be too expensive because `Validator` runs on each request as a part of auth middleware. In contrast, `ClaimsUpdater` called on token creation/refresh only. - -### Multi-tenant services and support for different audiences - -For complex systems a single authenticator may serve multiple distinct subsystems or multiple set of independent users. For example some SaaS offerings may need to provide different authentications for different customers and prevent use of tokens/cookies made by another customer. - -Such functionality can be implemented in 3 different ways: - -- Different instances of `auth.Service` each one with different secret. Doing this way will ensure the highest level of isolation and cookies/tokens won't be even parsable across the instances. Practically such architecture can be too complicated and not always possible. -– Handling "allowed audience" as a part of `ClaimsUpdater` and `Validator` chain. I.e. `ClaimsUpdater` sets a claim indicating expected audience code/id and `Validator` making sure it matches. This way a single `auth.Service` could handle multiple groups of auth tokens and reject some based on the audience. -- Using the standard JWT `aud` claim. This method conceptually very similar to the previous one, but done by library internally and consumer don't need to define special `ClaimsUpdater` and `Validator` logic. - -In order to allow `aud` support the list of allowed audiences should be passed in as `opts.Audiences` parameter. Non-empty value will trigger internal checks for token generation (will reject token creation for alien `aud`) as well as `Auth` middleware. - -### Dev provider - -Working with oauth2 providers can be a pain, especially during development phase. A special, development-only provider `dev` can make it less painful. This one can be registered directly, i.e. `service.AddProvider("dev", "", "")` or `service.AddDevProvider(port)` and should be activated like this: - -```go - // runs dev oauth2 server on :8084 by default - go func() { - devAuthServer, err := service.DevAuth() - if err != nil { - log.Fatal(err) - } - devAuthServer.Run() - }() -``` - -It will run fake aouth2 "server" on port :8084 and user could login with any user name. See [example](https://github.com/go-pkgz/auth/blob/master/_example/main.go) for more details. - -_Warning: this is not the real oauth2 server but just a small fake thing for development and testing only. Don't use `dev` provider with any production code._ - -By default, Dev provider doesn't return `email` claim from `/user` endpoint, to match behaviour of other providers which only request minimal scopes. -However sometimes it is useful to have `email` included into user info. This can be done by configuring `devAuthServer.GetEmailFn` function: - -```go - go func() { - devAuthServer, err := service.DevAuth() - devOauth2Srv.GetEmailFn = func(username string) string { - return username + "@example.com" - } - if err != nil { - log.Fatal(err) - } - devAuthServer.Run() - }() -``` - -### Other ways to authenticate - -In addition to the primary method (i.e. JWT cookie with XSRF header) there are two more ways to authenticate: - -1. Send JWT header as `X-JWT`. This shouldn't be used for web application, however can be helpful for service-to-service authentication. -2. Send JWT token as query parameter, i.e. `/something?token=` -3. Basic access authentication, for more details see below [Basic authentication](#basic-authentication). - -### Basic authentication - -In some cases the `middleware.Authenticator` allow use [Basic access authentication](https://en.wikipedia.org/wiki/Basic_access_authentication), which transmits credentials as user-id/password pairs, encoded using Base64 ([RFC7235](https://tools.ietf.org/html/rfc7617)). -When basic authentication used, client doesn't get auth token in response. It's auth type expect credentials in a header `Authorization` at every client request. It can be helpful, if client side not support cookie/token store (e.g. embedded device or custom apps). -This mode disabled by default and will be enabled with options. - -The `auth` package has two options of basic authentication: -- simple basic auth will be enabled if `Opts.AdminPasswd` defined. This will allow access with basic auth admin: with user [admin](https://github.com/go-pkgz/auth/blob/master/middleware/auth.go#L24). Such method can be used for automation scripts. -- basic auth with custom checker [function](https://github.com/go-pkgz/auth/blob/master/middleware/auth.go#L47), which allow adding user data from store to context of request. It will be enabled if `Opts.BasicAuthChecker` defined. When `BasicAuthChecker` defined then `Opts.AdminPasswd` option will be ignore. -```go -options := auth.Opts{ - //... - AdminPasswd: "admin_secret_password", // will ignore if BasicAuthChecker defined - BasicAuthChecker: func(user, passwd string) (bool, token.User, error) { - if user == "basic_user" && passwd == "123456" { - return true, token.User{Name: user, Role: "test_r"}, nil - } - return false, token.User{}, errors.New("basic auth credentials check failed") - } - //... -} -``` -### Logging - -By default, this library doesn't print anything to stdout/stderr, however user can pass a logger implementing `logger.L` interface with a single method `Logf(format string, args ...interface{})`. Functional adapter for this interface included as `logger.Func`. There are two predefined implementations in the `logger` package - `NoOp` (prints nothing, default) and `Std` wrapping `log.Printf` from stdlib. - -## Register oauth2 providers - -Authentication handled by external providers. You should setup oauth2 for all (or some) of them to allow users to authenticate. It is not mandatory to have all of them, but at least one should be correctly configured. - -#### Google Auth Provider - -1. Create a new project: https://console.developers.google.com/project -2. Choose the new project from the top right project dropdown (only if another project is selected) -3. In the project Dashboard center pane, choose **"API Manager"** -4. In the left Nav pane, choose **"Credentials"** -5. In the center pane, choose the **"OAuth consent screen"** tab. - * Select "**External**" and click "Create" - * Fill in **"App name"** and select **User support email** - * Upload a logo, if you want to - * In the **App Domain** section: - * **Application home page** - your site URL, e.g., `https://mysite.com` - * **Application privacy policy link** - `/web/privacy.html` of your Remark42 installation, e.g. `https://remark42.mysite.com/web/privacy.html` (please check that it works) - * **Terms of service** - leave empty - * **Authorized domains** - your site domain, e.g., `mysite.com` - * **Developer contact information** - add your email, and then click **Save and continue** - * On the **Scopes** tab, just click **Save and continue** - * On the **Test users**, add your email, then click **Save and continue** - * Before going to the next step, set the app to "Production" and send it to verification -6. In the center pane, choose the **"Credentials"** tab - * Open the **"Create credentials"** drop-down - * Choose **"OAuth client ID"** - * Choose **"Web application"** - * Application **Name** is freeform; choose something appropriate, like "Comments on mysite.com" - * **Authorized JavaScript Origins** should be your domain, e.g., `https://remark42.mysite.com` - * **Authorized redirect URIs** is the location of OAuth2/callback constructed as domain + `/auth/google/callback`, e.g., `https://remark42.mysite.com/auth/google/callback` - * Click **"Create"** -7. Take note of the **Client ID** and **Client Secret** - -_instructions for google oauth2 setup borrowed from [oauth2_proxy](https://github.com/bitly/oauth2_proxy)_ - -#### Microsoft Auth Provider - -1. Register a new application [using the Azure portal](https://docs.microsoft.com/en-us/graph/auth-register-app-v2). -2. Under **"Authentication/Platform configurations/Web"** enter the correct url constructed as domain + `/auth/microsoft/callback`. i.e. `https://example.mysite.com/auth/microsoft/callback` -3. In "Overview" take note of the **Application (client) ID** -4. Choose the new project from the top right project dropdown (only if another project is selected) -5. Select "Certificates & secrets" and click on "+ New Client Secret". - - -#### GitHub Auth Provider - -1. Create a new **"OAuth App"**: https://github.com/settings/developers -1. Fill **"Application Name"** and **"Homepage URL"** for your site -1. Under **"Authorization callback URL"** enter the correct url constructed as domain + `/auth/github/callback`. ie `https://example.mysite.com/auth/github/callback` -1. Take note of the **Client ID** and **Client Secret** - -#### Facebook Auth Provider - -1. From https://developers.facebook.com select **"My Apps"** / **"Add a new App"** -1. Set **"Display Name"** and **"Contact email"** -1. Choose **"Facebook Login"** and then **"Web"** -1. Set "Site URL" to your domain, ex: `https://example.mysite.com` -1. Under **"Facebook login"** / **"Settings"** fill "Valid OAuth redirect URIs" with your callback url constructed as domain + `/auth/facebook/callback` -1. Select **"App Review"** and turn public flag on. This step may ask you to provide a link to your privacy policy. - - -#### Apple Auth Provider - -To configure this provider, a user requires an Apple developer account (without it setting up a sign in with Apple is impossible). [Sign in with Apple](https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api) lets users log in to your app using their two-factor authentication Apple ID. - -Follow to next steps for configuring on the Apple side: - -1. Log in [to the developer account](https://developer.apple.com/account). -1. If you don't have an App ID yet, [create one](https://developer.apple.com/account/resources/identifiers/add/bundleId). Later on, you'll need **TeamID**, which is an "App ID Prefix" value. -1. Enable the "Sign in with Apple" capability for your App ID in [the Certificates, Identifiers & Profiles](https://developer.apple.com/account/resources/identifiers/list) section. -1. Create [Service ID](https://developer.apple.com/account/resources/identifiers/list/serviceId) and bind with App ID from the previous step. Apple will display the description field value to end-users on sign-in. You'll need that service **Identifier as a ClientID** later on**.** -1. Configure "Sign in with Apple" for created Service ID. Add domain where you will use that auth on to "Domains and subdomains" and its main page URL (like `https://example.com/` to "Return URLs". -1. Register a [New Key](https://developer.apple.com/account/resources/authkeys/list) (private key) for the "Sign in with Apple" feature and download it. Write down the **Key ID**. This key will be used to create [JWT](https://developer.apple.com/documentation/sign_in_with_apple/generate_and_validate_tokens#3262048) Client Secret. -1. Add your domain name and sender email in the Certificates, Identifiers & Profiles >> [More](https://developer.apple.com/account/resources/services/configure) section as a new Email Source. - -After completing the previous steps, you can proceed with configuring the Apple auth provider. Here are the parameters for AppleConfig: - -- _ClientID_ (**required**) - Service ID (or App ID) which is used for Sign with Apple -- _TeamID_ (**required**) - Identifier a developer account (use as prefix for all App ID) -- _KeyID_ (**required**) - Identifier a generated key for Sign with Apple -- _ResponseMode_ - Response Mode, please see [documentation](https://developer.apple.com/documentation/sign_in_with_apple/request_an_authorization_to_the_sign_in_with_apple_server?changes=_1_2#4066168) for reference, default is `form_post` - -```go - // apple config parameters - appleCfg := provider.AppleConfig{ - TeamID: os.Getenv("AEXMPL_APPLE_TID"), // developer account identifier - ClientID: os.Getenv("AEXMPL_APPLE_CID"), // Service ID (or App ID) - KeyID: os.Getenv("AEXMPL_APPLE_KEYID"), // private key identifier - } -``` - -Then add an Apple provider that accepts the following parameters: -* `appleConfig (provider.AppleConfig)` created above -* `privateKeyLoader (PrivateKeyLoaderInterface)` - -`PrivateKeyLoaderInterface` [implements](https://github.com/go-pkgz/auth/blob/master/provider/apple.go#L98:L100) a loader for the private key (which you downloaded above) to create a `client_secret`. The user can use a pre-defined function `provider.LoadApplePrivateKeyFromFile(filePath string)` to load the private key from local file. - -`AddAppleProvide` tries to load private key at call and return an error if load failed. Always check error when calling this provider. - -```go - if err := service.AddAppleProvider(appleCfg, provider.LoadApplePrivateKeyFromFile("PATH_TO_PRIVATE_KEY_FILE")); err != nil { - log.Fatalf("[ERROR] failed create to AppleProvider: %v", err) - } -``` - -**Limitation:** - -* Map a userName (if specific scope defined) is only sent in the upon initial user sign up. - Subsequent logins to your app using Sign In with Apple with the same account do not share any user info and will only return a user identifier in IDToken claims. - This behaves correctly until a user delete sign in for you service with Apple ID in own Apple account profile (security section). - It is recommend that you securely cache the at first login containing the user info for bind it with a user UID at next login. - Provider always get user `UID` (`sub` claim) in `IDToken`. - -* Apple doesn't have an API for fetch avatar and user info. - -See [example](https://github.com/go-pkgz/auth/blob/master/_example/main.go#L83:L93) before use. - -#### Yandex Auth Provider - -1. Create a new **"OAuth App"**: https://oauth.yandex.com/client/new -1. Fill **"App name"** for your site -1. Under **Platforms** select **"Web services"** and enter **"Callback URI #1"** constructed as domain + `/auth/yandex/callback`. ie `https://example.mysite.com/auth/yandex/callback` -1. Select **Permissions**. You need following permissions only from the **"Yandex.Passport API"** section: - * Access to user avatar - * Access to username, first name and surname, gender -1. Fill out the rest of fields if needed -1. Take note of the **ID** and **Password** - -For more details refer to [Yandex OAuth](https://tech.yandex.com/oauth/doc/dg/concepts/about-docpage/) and [Yandex.Passport](https://tech.yandex.com/passport/doc/dg/index-docpage/) API documentation. - -##### Battle.net Auth Provider - -1. Log into Battle.net as a developer: https://develop.battle.net/nav/login-redirect -1. Click "+ CREATE CLIENT" https://develop.battle.net/access/clients/create -1. For "Client name", enter whatever you want -1. For "Redirect URLs", one of the lines must be "http\[s\]://your_remark_installation:port//auth/battlenet/callback", e.g. https://localhost:8443/auth/battlenet/callback or https://remark.mysite.com/auth/battlenet/callback -1. For "Service URL", enter the URL to your site or check "I do not have a service URL for this client." checkbox if you don't have any -1. For "Intended use", describe the application you're developing -1. Click "Save". -1. You can see your client ID and client secret at https://develop.battle.net/access/clients by clicking the client you created - -For more details refer to [Complete Guide of Battle.net OAuth API and Login Button](https://hakanu.net/oauth/2017/01/26/complete-guide-of-battle-net-oauth-api-and-login-button/) or [the official Battle.net OAuth2 guide](https://develop.battle.net/documentation/guides/using-oauth) - -#### Patreon Auth Provider #### -1. Create a new Patreon client https://www.patreon.com/portal/registration/register-clients -1. Fill **"App Name"**, **"Description"**, **"App Category"** and **"Author"** for your site -1. Under **"Redirect URIs"** enter the correct url constructed as domain + `/auth/patreon/callback`. ie `https://example.mysite.com/auth/patreon/callback` -1. Take note of the **Client ID** and **Client Secret** - -#### Discord Auth Provider #### -1. Log into Discord Developer Portal https://discord.com/developers/applications -2. Click on **New Application** to create the application required for Oauth -3. After filling **"NAME"**, navigate to **"OAuth2"** option on the left sidebar -4. Under **"Redirects"** enter the correct url constructed as domain + `/auth/discord/callback`. ie `https://remark42.mysite.com/auth/discord/callback` -5. Take note of the **CLIENT ID** and **CLIENT SECRET** - -#### Twitter Auth Provider -1. Create a new twitter application https://developer.twitter.com/en/apps -1. Fill **App name** and **Description** and **URL** of your site -1. In the field **Callback URLs** enter the correct url of your callback handler e.g. https://example.mysite.com/{route}/twitter/callback -1. Under **Key and tokens** take note of the **Consumer API Key** and **Consumer API Secret key**. Those will be used as `cid` and `csecret` - -## XSRF Protections -By default, the XSRF protections will apply to all requests which reach the `middlewares.Auth`, -`middlewares.Admin` or `middlewares.RBAC` middlewares. This will require setting a request header -with a key of `` containing the value of the cookie named ``. - -To disable all XSRF protections, set `DisableXSRF` to `true`. This should probably only be used -during testing or debugging. - -When setting a custom request header is not possible, such as when building a web application which -is not a Single-Page-Application and HTML link tags are used to navigate pages, specific HTTP methods -may be excluded using the `XSRFIgnoreMethods` option. For example, to disable GET requests, set this -option to `XSRFIgnoreMethods: []string{"GET"}`. Adding methods other than GET to this list may result -in XSRF vulnerabilities. - -## Status - -The library extracted from [remark42](https://github.com/umputun/remark) project. The original code in production use on multiple sites and seems to work fine. - -`go-pkgz/auth` library still in development and until version 1 released some breaking changes possible. diff --git a/backend/vendor/github.com/go-pkgz/auth/LICENSE b/backend/vendor/github.com/go-pkgz/auth/v2/LICENSE similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/LICENSE rename to backend/vendor/github.com/go-pkgz/auth/v2/LICENSE diff --git a/backend/vendor/github.com/go-pkgz/auth/auth.go b/backend/vendor/github.com/go-pkgz/auth/v2/auth.go similarity index 92% rename from backend/vendor/github.com/go-pkgz/auth/auth.go rename to backend/vendor/github.com/go-pkgz/auth/v2/auth.go index 33366b2034..4245ac4c12 100644 --- a/backend/vendor/github.com/go-pkgz/auth/auth.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/auth.go @@ -9,11 +9,11 @@ import ( "github.com/go-pkgz/rest" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/middleware" - "github.com/go-pkgz/auth/provider" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/middleware" + "github.com/go-pkgz/auth/v2/provider" + "github.com/go-pkgz/auth/v2/token" ) // Client is a type of auth client @@ -99,24 +99,25 @@ func NewService(opts Opts) (res *Service) { } jwtService := token.NewService(token.Opts{ - SecretReader: opts.SecretReader, - ClaimsUpd: opts.ClaimsUpd, - SecureCookies: opts.SecureCookies, - TokenDuration: opts.TokenDuration, - CookieDuration: opts.CookieDuration, - DisableXSRF: opts.DisableXSRF, - DisableIAT: opts.DisableIAT, - JWTCookieName: opts.JWTCookieName, - JWTCookieDomain: opts.JWTCookieDomain, - JWTHeaderKey: opts.JWTHeaderKey, - XSRFCookieName: opts.XSRFCookieName, - XSRFHeaderKey: opts.XSRFHeaderKey, - SendJWTHeader: opts.SendJWTHeader, - JWTQuery: opts.JWTQuery, - Issuer: res.issuer, - AudienceReader: opts.AudienceReader, - AudSecrets: opts.AudSecrets, - SameSite: opts.SameSiteCookie, + SecretReader: opts.SecretReader, + ClaimsUpd: opts.ClaimsUpd, + SecureCookies: opts.SecureCookies, + TokenDuration: opts.TokenDuration, + CookieDuration: opts.CookieDuration, + DisableXSRF: opts.DisableXSRF, + DisableIAT: opts.DisableIAT, + JWTCookieName: opts.JWTCookieName, + JWTCookieDomain: opts.JWTCookieDomain, + JWTHeaderKey: opts.JWTHeaderKey, + XSRFCookieName: opts.XSRFCookieName, + XSRFHeaderKey: opts.XSRFHeaderKey, + XSRFIgnoreMethods: opts.XSRFIgnoreMethods, + SendJWTHeader: opts.SendJWTHeader, + JWTQuery: opts.JWTQuery, + Issuer: res.issuer, + AudienceReader: opts.AudienceReader, + AudSecrets: opts.AudSecrets, + SameSite: opts.SameSiteCookie, }) if opts.SecretReader == nil { diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/avatar.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/avatar.go similarity index 99% rename from backend/vendor/github.com/go-pkgz/auth/avatar/avatar.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/avatar.go index cab724ba5f..a1d749a621 100644 --- a/backend/vendor/github.com/go-pkgz/auth/avatar/avatar.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/avatar.go @@ -19,8 +19,8 @@ import ( "github.com/rrivera/identicon" "golang.org/x/image/draw" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) // http.sniffLen is 512 bytes which is how much we need to read to detect content type diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/bolt.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/bolt.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/avatar/bolt.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/bolt.go diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/gridfs.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/gridfs.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/avatar/gridfs.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/gridfs.go diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/localfs.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/localfs.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/avatar/localfs.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/localfs.go diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/noop.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/noop.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/avatar/noop.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/noop.go diff --git a/backend/vendor/github.com/go-pkgz/auth/avatar/store.go b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/store.go similarity index 99% rename from backend/vendor/github.com/go-pkgz/auth/avatar/store.go rename to backend/vendor/github.com/go-pkgz/auth/v2/avatar/store.go index ab51a1b8d9..cd2a38151f 100644 --- a/backend/vendor/github.com/go-pkgz/auth/avatar/store.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/avatar/store.go @@ -19,7 +19,7 @@ import ( "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" ) // imgSfx for avatars diff --git a/backend/vendor/github.com/go-pkgz/auth/logger/interface.go b/backend/vendor/github.com/go-pkgz/auth/v2/logger/interface.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/logger/interface.go rename to backend/vendor/github.com/go-pkgz/auth/v2/logger/interface.go diff --git a/backend/vendor/github.com/go-pkgz/auth/middleware/auth.go b/backend/vendor/github.com/go-pkgz/auth/v2/middleware/auth.go similarity index 96% rename from backend/vendor/github.com/go-pkgz/auth/middleware/auth.go rename to backend/vendor/github.com/go-pkgz/auth/v2/middleware/auth.go index 64d6c7ced0..6e8c5ed8e6 100644 --- a/backend/vendor/github.com/go-pkgz/auth/middleware/auth.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/middleware/auth.go @@ -10,9 +10,9 @@ import ( "net/http" "strings" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/provider" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/provider" + "github.com/go-pkgz/auth/v2/token" ) // Authenticator is top level auth object providing middlewares @@ -28,8 +28,8 @@ type Authenticator struct { // RefreshCache defines interface storing and retrieving refreshed tokens type RefreshCache interface { - Get(key interface{}) (value interface{}, ok bool) - Set(key, value interface{}) + Get(key string) (value token.Claims, ok bool) + Set(key string, value token.Claims) } // TokenService defines interface accessing tokens @@ -173,11 +173,11 @@ func (a *Authenticator) refreshExpiredToken(w http.ResponseWriter, claims token. if a.RefreshCache != nil { if c, ok := a.RefreshCache.Get(tkn); ok { // already in cache - return c.(token.Claims), nil + return c, nil } } - claims.ExpiresAt = 0 // this will cause now+duration for refreshed token + claims.ExpiresAt = nil // this will cause now+duration for refreshed token c, err := a.JWTService.Set(w, claims) // Set changes token if err != nil { return token.Claims{}, err diff --git a/backend/vendor/github.com/go-pkgz/auth/middleware/user_updater.go b/backend/vendor/github.com/go-pkgz/auth/v2/middleware/user_updater.go similarity index 96% rename from backend/vendor/github.com/go-pkgz/auth/middleware/user_updater.go rename to backend/vendor/github.com/go-pkgz/auth/v2/middleware/user_updater.go index 34dc5dcd2c..1103703beb 100644 --- a/backend/vendor/github.com/go-pkgz/auth/middleware/user_updater.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/middleware/user_updater.go @@ -3,7 +3,7 @@ package middleware import ( "net/http" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" ) // UserUpdater defines interface adding extras or modifying UserInfo in request context diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/apple.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/apple.go similarity index 96% rename from backend/vendor/github.com/go-pkgz/auth/provider/apple.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/apple.go index 2663cf11da..4a2fbcd0cf 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/apple.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/apple.go @@ -24,10 +24,10 @@ import ( "golang.org/x/oauth2" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) const ( @@ -41,7 +41,7 @@ const ( appleRequestContentType = "application/x-www-form-urlencoded" // UserAgent required to every request to Apple REST API - defaultUserAgent = "github.com/go-pkgz/auth" + defaultUserAgent = "github.com/go-pkgz/auth/v2" // AcceptJSONHeader is the content to accept from response AcceptJSONHeader = "application/json" @@ -261,11 +261,11 @@ func (ah *AppleHandler) LoginHandler(w http.ResponseWriter, r *http.Request) { From: r.URL.Query().Get("from"), }, SessionOnly: r.URL.Query().Get("session") != "" && r.URL.Query().Get("session") != "0", - StandardClaims: jwt.StandardClaims{ - Id: cid, - Audience: r.URL.Query().Get("site"), - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + ID: cid, + Audience: jwt.ClaimStrings{r.URL.Query().Get("site")}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, } @@ -370,9 +370,9 @@ func (ah AppleHandler) AuthHandler(w http.ResponseWriter, r *http.Request) { claims := token.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ + RegisteredClaims: jwt.RegisteredClaims{ Issuer: ah.Issuer, - Id: cid, + ID: cid, Audience: oauthClaims.Audience, }, SessionOnly: false, @@ -467,13 +467,13 @@ func (ah *AppleHandler) createClientSecret() (string, error) { } // Create a claims now := time.Now() - exp := now.Add(time.Minute * 30).Unix() // default value + exp := now.Add(time.Minute * 30) // default value - claims := &jwt.StandardClaims{ + claims := &jwt.RegisteredClaims{ Issuer: ah.conf.TeamID, - IssuedAt: now.Unix(), - ExpiresAt: exp, - Audience: "https://appleid.apple.com", + IssuedAt: jwt.NewNumericDate(now), + ExpiresAt: jwt.NewNumericDate(exp), + Audience: []string{"https://appleid.apple.com"}, Subject: ah.conf.ClientID, } diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/apple_pubkeys.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/apple_pubkeys.go similarity index 99% rename from backend/vendor/github.com/go-pkgz/auth/provider/apple_pubkeys.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/apple_pubkeys.go index 5c3563e5b3..364503dd55 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/apple_pubkeys.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/apple_pubkeys.go @@ -16,7 +16,7 @@ import ( "net/http" "time" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" ) // appleKeysURL is the endpoint URL for fetch Apple’s public key diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/custom_server.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/custom_server.go similarity index 98% rename from backend/vendor/github.com/go-pkgz/auth/provider/custom_server.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/custom_server.go index 0ca145e3d0..d77a59412a 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/custom_server.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/custom_server.go @@ -15,9 +15,9 @@ import ( goauth2 "github.com/go-oauth2/oauth2/v4/server" "golang.org/x/oauth2" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) // CustomHandlerOpt are options to initialize a handler for oauth2 server diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/dev_provider.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/dev_provider.go similarity index 98% rename from backend/vendor/github.com/go-pkgz/auth/provider/dev_provider.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/dev_provider.go index e93bb0e605..136877a2be 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/dev_provider.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/dev_provider.go @@ -11,9 +11,9 @@ import ( "golang.org/x/oauth2" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) const ( diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/direct.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/direct.go similarity index 96% rename from backend/vendor/github.com/go-pkgz/auth/provider/direct.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/direct.go index 742ebd5ab3..7d94017707 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/direct.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/direct.go @@ -9,10 +9,10 @@ import ( "time" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) const ( @@ -120,10 +120,10 @@ func (p DirectHandler) LoginHandler(w http.ResponseWriter, r *http.Request) { claims := token.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ - Id: cid, + RegisteredClaims: jwt.RegisteredClaims{ + ID: cid, Issuer: p.Issuer, - Audience: creds.Audience, + Audience: []string{creds.Audience}, }, SessionOnly: sessOnly, } diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/oauth1.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth1.go similarity index 93% rename from backend/vendor/github.com/go-pkgz/auth/provider/oauth1.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth1.go index 4aec7f56f4..6a51b0da67 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/oauth1.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth1.go @@ -10,10 +10,10 @@ import ( "github.com/dghubble/oauth1" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) // Oauth1Handler implements /login, /callback and /logout handlers for oauth1 flow @@ -55,11 +55,11 @@ func (h Oauth1Handler) LoginHandler(w http.ResponseWriter, r *http.Request) { From: r.URL.Query().Get("from"), }, SessionOnly: r.URL.Query().Get("session") != "" && r.URL.Query().Get("session") != "0", - StandardClaims: jwt.StandardClaims{ - Id: cid, - Audience: r.URL.Query().Get("site"), - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + ID: cid, + Audience: []string{r.URL.Query().Get("site")}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, } @@ -140,9 +140,9 @@ func (h Oauth1Handler) AuthHandler(w http.ResponseWriter, r *http.Request) { } claims := token.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ + RegisteredClaims: jwt.RegisteredClaims{ Issuer: h.Issuer, - Id: cid, + ID: cid, Audience: oauthClaims.Audience, }, SessionOnly: oauthClaims.SessionOnly, diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/oauth2.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth2.go similarity index 94% rename from backend/vendor/github.com/go-pkgz/auth/provider/oauth2.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth2.go index 6161357e91..a985cd98a9 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/oauth2.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/oauth2.go @@ -10,11 +10,11 @@ import ( "time" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" "golang.org/x/oauth2" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) // Oauth2Handler implements /login, /callback and /logout handlers from aouth2 flow @@ -111,11 +111,11 @@ func (p Oauth2Handler) LoginHandler(w http.ResponseWriter, r *http.Request) { From: r.URL.Query().Get("from"), }, SessionOnly: r.URL.Query().Get("session") != "" && r.URL.Query().Get("session") != "0", - StandardClaims: jwt.StandardClaims{ - Id: cid, - Audience: aud, - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + ID: cid, + Audience: []string{aud}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, NoAva: r.URL.Query().Get("noava") == "1", } @@ -208,9 +208,9 @@ func (p Oauth2Handler) AuthHandler(w http.ResponseWriter, r *http.Request) { } claims := token.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ + RegisteredClaims: jwt.RegisteredClaims{ Issuer: p.Issuer, - Id: cid, + ID: cid, Audience: oauthClaims.Audience, }, SessionOnly: oauthClaims.SessionOnly, diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/providers.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/providers.go similarity index 99% rename from backend/vendor/github.com/go-pkgz/auth/provider/providers.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/providers.go index 9711781f1e..471fa312f9 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/providers.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/providers.go @@ -8,7 +8,7 @@ import ( "github.com/dghubble/oauth1" "github.com/dghubble/oauth1/twitter" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" "golang.org/x/oauth2" "golang.org/x/oauth2/facebook" "golang.org/x/oauth2/github" diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/sender/email.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/sender/email.go similarity index 98% rename from backend/vendor/github.com/go-pkgz/auth/provider/sender/email.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/sender/email.go index 2c77370257..b70a71d416 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/sender/email.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/sender/email.go @@ -4,7 +4,7 @@ package sender import ( "time" - "github.com/go-pkgz/auth/logger" + "github.com/go-pkgz/auth/v2/logger" "github.com/go-pkgz/email" ) diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/service.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/service.go similarity index 98% rename from backend/vendor/github.com/go-pkgz/auth/provider/service.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/service.go index 953d416769..f085b5f2a0 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/service.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/service.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/token" ) const ( diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/telegram.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/telegram.go similarity index 97% rename from backend/vendor/github.com/go-pkgz/auth/provider/telegram.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/telegram.go index 177c1c0266..906fe59f9a 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/telegram.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/telegram.go @@ -17,10 +17,10 @@ import ( "github.com/go-pkgz/repeater" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" - "github.com/go-pkgz/auth/logger" - authtoken "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/logger" + authtoken "github.com/go-pkgz/auth/v2/token" ) // TelegramHandler implements login via telegram @@ -302,12 +302,12 @@ func (th *TelegramHandler) LoginHandler(w http.ResponseWriter, r *http.Request) claims := authtoken.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ - Audience: r.URL.Query().Get("site"), - Id: queryToken, + RegisteredClaims: jwt.RegisteredClaims{ + Audience: []string{r.URL.Query().Get("site")}, + ID: queryToken, Issuer: th.ProviderName, - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), }, SessionOnly: false, // TODO review? } diff --git a/backend/vendor/github.com/go-pkgz/auth/provider/verify.go b/backend/vendor/github.com/go-pkgz/auth/v2/provider/verify.go similarity index 93% rename from backend/vendor/github.com/go-pkgz/auth/provider/verify.go rename to backend/vendor/github.com/go-pkgz/auth/v2/provider/verify.go index 8b0a03ddd9..0fc9ca6e9e 100644 --- a/backend/vendor/github.com/go-pkgz/auth/provider/verify.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/provider/verify.go @@ -10,11 +10,11 @@ import ( "time" "github.com/go-pkgz/rest" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" - "github.com/go-pkgz/auth/avatar" - "github.com/go-pkgz/auth/logger" - "github.com/go-pkgz/auth/token" + "github.com/go-pkgz/auth/v2/avatar" + "github.com/go-pkgz/auth/v2/logger" + "github.com/go-pkgz/auth/v2/token" ) // VerifyHandler implements non-oauth2 provider authorizing users with some confirmation. @@ -111,8 +111,8 @@ func (e VerifyHandler) LoginHandler(w http.ResponseWriter, r *http.Request) { claims := token.Claims{ User: &u, - StandardClaims: jwt.StandardClaims{ - Id: cid, + RegisteredClaims: jwt.RegisteredClaims{ + ID: cid, Issuer: e.Issuer, Audience: confClaims.Audience, }, @@ -146,10 +146,10 @@ func (e VerifyHandler) sendConfirmation(w http.ResponseWriter, r *http.Request) ID: user + "::" + address, }, SessionOnly: r.URL.Query().Get("session") != "" && r.URL.Query().Get("session") != "0", - StandardClaims: jwt.StandardClaims{ - Audience: site, - ExpiresAt: time.Now().Add(30 * time.Minute).Unix(), - NotBefore: time.Now().Add(-1 * time.Minute).Unix(), + RegisteredClaims: jwt.RegisteredClaims{ + Audience: []string{site}, + ExpiresAt: jwt.NewNumericDate(time.Now().Add(30 * time.Minute)), + NotBefore: jwt.NewNumericDate(time.Now().Add(-1 * time.Minute)), Issuer: e.Issuer, }, } diff --git a/backend/vendor/github.com/go-pkgz/auth/token/jwt.go b/backend/vendor/github.com/go-pkgz/auth/v2/token/jwt.go similarity index 86% rename from backend/vendor/github.com/go-pkgz/auth/token/jwt.go rename to backend/vendor/github.com/go-pkgz/auth/v2/token/jwt.go index 56cae21975..bb2ea58266 100644 --- a/backend/vendor/github.com/go-pkgz/auth/token/jwt.go +++ b/backend/vendor/github.com/go-pkgz/auth/v2/token/jwt.go @@ -3,13 +3,15 @@ package token import ( "encoding/json" + "errors" "fmt" "net/http" "slices" "strings" + "sync" "time" - "github.com/golang-jwt/jwt" + "github.com/golang-jwt/jwt/v5" ) // Service wraps jwt operations @@ -20,7 +22,7 @@ type Service struct { // Claims stores user info for token and state & from from login type Claims struct { - jwt.StandardClaims + jwt.RegisteredClaims User *User `json:"user,omitempty"` // user info SessionOnly bool `json:"sess_only,omitempty"` Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake @@ -80,6 +82,11 @@ type Opts struct { // NewService makes JWT service func NewService(opts Opts) *Service { + var once sync.Once + once.Do(func() { + jwt.MarshalSingleStringAsArray = false + }) + res := Service{Opts: opts} setDefault := func(fld *string, def string) { @@ -97,7 +104,7 @@ func NewService(opts Opts) *Service { setDefault(&res.JWTCookieDomain, defaultJWTCookieDomain) if opts.XSRFIgnoreMethods == nil { - opts.XSRFIgnoreMethods = defaultXSRFIgnoreMethods + res.XSRFIgnoreMethods = defaultXSRFIgnoreMethods } if opts.TokenDuration == 0 { @@ -131,7 +138,7 @@ func (j *Service) Token(claims Claims) (string, error) { return "", fmt.Errorf("aud rejected: %w", err) } - secret, err := j.SecretReader.Get(claims.Audience) // get secret via consumer defined SecretReader + secret, err := j.SecretReader.Get(claims.Audience[0]) // get secret via consumer defined SecretReader if err != nil { return "", fmt.Errorf("can't get secret: %w", err) } @@ -145,7 +152,7 @@ func (j *Service) Token(claims Claims) (string, error) { // Parse token string and verify. Not checking for expiration func (j *Service) Parse(tokenString string) (Claims, error) { - parser := jwt.Parser{SkipClaimsValidation: true} // allow parsing of expired tokens + parser := jwt.NewParser(jwt.WithoutClaimsValidation()) if j.SecretReader == nil { return Claims{}, fmt.Errorf("secret reader not defined") @@ -189,7 +196,7 @@ func (j *Service) Parse(tokenString string) (Claims, error) { // aud pre-parse token and extracts aud from the claim // important! this step ignores token verification, should not be used for any validations func (j *Service) aud(tokenString string) (string, error) { - parser := jwt.Parser{} + parser := jwt.NewParser() token, _, err := parser.ParseUnverified(tokenString, &Claims{}) if err != nil { return "", fmt.Errorf("can't pre-parse token: %w", err) @@ -198,34 +205,44 @@ func (j *Service) aud(tokenString string) (string, error) { if !ok { return "", fmt.Errorf("invalid token") } - if strings.TrimSpace(claims.Audience) == "" { + + if len(claims.Audience) == 0 { + return "", fmt.Errorf("empty aud") + } + aud := claims.Audience[0] + + if strings.TrimSpace(aud) == "" { return "", fmt.Errorf("empty aud") } - return claims.Audience, nil + return aud, nil } func (j *Service) validate(claims *Claims) error { - cerr := claims.Valid() + validator := jwt.NewValidator() + err := validator.Validate(claims) - if cerr == nil { + if err == nil { return nil } - if e, ok := cerr.(*jwt.ValidationError); ok { - if e.Errors == jwt.ValidationErrorExpired { - return nil // allow expired tokens + // Ignore "ErrTokenExpired" if it is the only error. + if errors.Is(err, jwt.ErrTokenExpired) { + if uw, ok := err.(interface{ Unwrap() []error }); ok && len(uw.Unwrap()) == 1 { + return nil } } - return cerr + return err } // Set creates token cookie with xsrf cookie and put it to ResponseWriter // accepts claims and sets expiration if none defined. permanent flag means long-living cookie, // false makes it session only. func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) { - if claims.ExpiresAt == 0 { - claims.ExpiresAt = time.Now().Add(j.TokenDuration).Unix() + nowUnix := time.Now().Unix() + + if claims.ExpiresAt == nil || claims.ExpiresAt.Time.Unix() == 0 { + claims.ExpiresAt = jwt.NewNumericDate(time.Unix(nowUnix, 0).Add(j.TokenDuration)) } if claims.Issuer == "" { @@ -233,7 +250,7 @@ func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) { } if !j.DisableIAT { - claims.IssuedAt = time.Now().Unix() + claims.IssuedAt = jwt.NewNumericDate(time.Unix(nowUnix, 0)) } tokenString, err := j.Token(claims) @@ -255,7 +272,7 @@ func (j *Service) Set(w http.ResponseWriter, claims Claims) (Claims, error) { MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite} http.SetCookie(w, &jwtCookie) - xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.Id, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain, + xsrfCookie := http.Cookie{Name: j.XSRFCookieName, Value: claims.ID, HttpOnly: false, Path: "/", Domain: j.JWTCookieDomain, MaxAge: cookieExpiration, Secure: j.SecureCookies, SameSite: j.SameSite} http.SetCookie(w, &xsrfCookie) @@ -296,7 +313,10 @@ func (j *Service) Get(r *http.Request) (Claims, string, error) { // promote claim's aud to User.Audience if claims.User != nil { - claims.User.Audience = claims.Audience + if len(claims.Audience) != 1 { + return Claims{}, "", fmt.Errorf("aud is not of size 1") + } + claims.User.Audience = claims.Audience[0] } if !fromCookie && j.IsExpired(claims) { @@ -309,7 +329,7 @@ func (j *Service) Get(r *http.Request) (Claims, string, error) { if fromCookie && claims.User != nil { xsrf := r.Header.Get(j.XSRFHeaderKey) - if claims.Id != xsrf { + if claims.ID != xsrf { return Claims{}, "", fmt.Errorf("xsrf mismatch") } } @@ -319,7 +339,9 @@ func (j *Service) Get(r *http.Request) (Claims, string, error) { // IsExpired returns true if claims expired func (j *Service) IsExpired(claims Claims) bool { - return !claims.VerifyExpiresAt(time.Now().Unix(), true) + validator := jwt.NewValidator(jwt.WithExpirationRequired()) + err := validator.Validate(claims) + return errors.Is(err, jwt.ErrTokenExpired) } // Reset token's cookies @@ -337,25 +359,32 @@ func (j *Service) Reset(w http.ResponseWriter) { // checkAuds verifies if claims.Audience in the list of allowed by audReader func (j *Service) checkAuds(claims *Claims, audReader Audience) error { + // marshal the audience. if audReader == nil { // lack of any allowed means any return nil } + + if len(claims.Audience) == 0 { + return fmt.Errorf("no audience provided") + } + claimsAudience := claims.Audience[0] + auds, err := audReader.Get() if err != nil { return fmt.Errorf("failed to get auds: %w", err) } for _, a := range auds { - if strings.EqualFold(a, claims.Audience) { + if strings.EqualFold(a, claimsAudience) { return nil } } - return fmt.Errorf("aud %q not allowed", claims.Audience) + return fmt.Errorf("aud %q not allowed", claimsAudience) } func (c Claims) String() string { b, err := json.Marshal(c) if err != nil { - return fmt.Sprintf("%+v %+v", c.StandardClaims, c.User) + return fmt.Sprintf("%+v %+v", c.RegisteredClaims, c.User) } return string(b) } diff --git a/backend/vendor/github.com/go-pkgz/auth/token/user.go b/backend/vendor/github.com/go-pkgz/auth/v2/token/user.go similarity index 100% rename from backend/vendor/github.com/go-pkgz/auth/token/user.go rename to backend/vendor/github.com/go-pkgz/auth/v2/token/user.go diff --git a/backend/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md b/backend/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md deleted file mode 100644 index c4efbd2a8c..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/MIGRATION_GUIDE.md +++ /dev/null @@ -1,22 +0,0 @@ -## Migration Guide (v3.2.1) - -Starting from [v3.2.1](https://github.com/golang-jwt/jwt/releases/tag/v3.2.1]), the import path has changed from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`. Future releases will be using the `github.com/golang-jwt/jwt` import path and continue the existing versioning scheme of `v3.x.x+incompatible`. Backwards-compatible patches and fixes will be done on the `v3` release branch, where as new build-breaking features will be developed in a `v4` release, possibly including a SIV-style import path. - -### go.mod replacement - -In a first step, the easiest way is to use `go mod edit` to issue a replacement. - -``` -go mod edit -replace github.com/dgrijalva/jwt-go=github.com/golang-jwt/jwt@v3.2.1+incompatible -go mod tidy -``` - -This will still keep the old import path in your code but replace it with the new package and also introduce a new indirect dependency to `github.com/golang-jwt/jwt`. Try to compile your project; it should still work. - -### Cleanup - -If your code still consistently builds, you can replace all occurences of `github.com/dgrijalva/jwt-go` with `github.com/golang-jwt/jwt`, either manually or by using tools such as `sed`. Finally, the `replace` directive in the `go.mod` file can be removed. - -## Older releases (before v3.2.0) - -The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. \ No newline at end of file diff --git a/backend/vendor/github.com/golang-jwt/jwt/README.md b/backend/vendor/github.com/golang-jwt/jwt/README.md deleted file mode 100644 index 9b653e46b0..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/README.md +++ /dev/null @@ -1,113 +0,0 @@ -# jwt-go - -[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt) - -A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). - -**IMPORT PATH CHANGE:** Starting from [v3.2.1](https://github.com/golang-jwt/jwt/releases/tag/v3.2.1), the import path has changed from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt`. After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. - -Future releases will be using the `github.com/golang-jwt/jwt` import path and continue the existing versioning scheme of `v3.x.x+incompatible`. Backwards-compatible patches and fixes will be done on the `v3` release branch, where as new build-breaking features will be developed in a `v4` release, possibly including a SIV-style import path. - -**SECURITY NOTICE:** Some older versions of Go have a security issue in the crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue [dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more detail. - -**SECURITY NOTICE:** It's important that you [validate the `alg` presented is what you expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). This library attempts to make it easy to do the right thing by requiring key types match the expected alg, but you should take the extra step to verify it in your usage. See the examples provided. - -### Supported Go versions - -Our support of Go versions is aligned with Go's [version release policy](https://golang.org/doc/devel/release#policy). -So we will support a major version of Go until there are two newer major releases. -We no longer support building jwt-go with unsupported Go versions, as these contain security vulnerabilities -which will not be fixed. - -## What the heck is a JWT? - -JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web Tokens. - -In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is made of three parts, separated by `.`'s. The first two parts are JSON objects, that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) encoded. The last part is the signature, encoded the same way. - -The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used. - -The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to [RFC 7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about reserved keys and the proper way to add your own. - -## What's in the box? - -This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own. - -## Examples - -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt) for examples of usage: - -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt#pkg-examples) - -## Extensions - -This library publishes all the necessary components for adding your own signing methods. Simply implement the `SigningMethod` interface and register a factory method using `RegisterSigningMethod`. - -Here's an example of an extension that integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS): https://github.com/someone1/gcp-jwt-go - -## Compliance - -This library was last reviewed to comply with [RTF 7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few notable differences: - -* In order to protect against accidental use of [Unsecured JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using `alg=none` will only be accepted if the constant `jwt.UnsafeAllowNoneSignatureType` is provided as the key. - -## Project Status & Versioning - -This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason). - -This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull requests will land on `main`. Periodically, versions will be tagged from `main`. You can find all the releases on [the project releases page](https://github.com/golang-jwt/jwt/releases). - -While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: `gopkg.in/golang-jwt/jwt.v3`. It will do the right thing WRT semantic versioning. - -**BREAKING CHANGES:*** -* Version 3.0.0 includes _a lot_ of changes from the 2.x line, including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in `VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating your code. - -## Usage Tips - -### Signing vs Encryption - -A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data: - -* The author of the token was in the possession of the signing secret -* The data has not been modified since it was signed - -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. - -### Choosing a Signing Method - -There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric. - -Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any `[]byte` can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation. - -Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification. - -### Signing Methods and Key Types - -Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: - -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation - -### JWT and OAuth - -It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication. - -Without going too far down the rabbit hole, here's a description of the interaction of these technologies: - -* OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth. -* OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that _should_ only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token. -* Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL. - -### Troubleshooting - -This library uses descriptive error messages whenever possible. If you are not getting the expected result, have a look at the errors. The most common place people get stuck is providing the correct type of key to the parser. See the above section on signing methods and key types. - -## More - -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt). - -The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/backend/vendor/github.com/golang-jwt/jwt/claims.go b/backend/vendor/github.com/golang-jwt/jwt/claims.go deleted file mode 100644 index f1dba3cb91..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/claims.go +++ /dev/null @@ -1,146 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// For a type to be a Claims object, it must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// Structured version of Claims Section, as referenced at -// https://tools.ietf.org/html/rfc7519#section-4.1 -// See examples for how to use this with your own claim types -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("token is expired by %v", delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = fmt.Errorf("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = fmt.Errorf("token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud([]string{c.Audience}, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - return verifyExp(c.ExpiresAt, cmp, req) -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - return verifyIat(c.IssuedAt, cmp, req) -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - return verifyNbf(c.NotBefore, cmp, req) -} - -// ----- helpers - -func verifyAud(aud []string, cmp string, required bool) bool { - if len(aud) == 0 { - return !required - } - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if len(stringClaims) == 0 { - return !required - } - - return result -} - -func verifyExp(exp int64, now int64, required bool) bool { - if exp == 0 { - return !required - } - return now <= exp -} - -func verifyIat(iat int64, now int64, required bool) bool { - if iat == 0 { - return !required - } - return now >= iat -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyNbf(nbf int64, now int64, required bool) bool { - if nbf == 0 { - return !required - } - return now >= nbf -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/errors.go b/backend/vendor/github.com/golang-jwt/jwt/errors.go deleted file mode 100644 index 1c93024aad..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// Helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// The error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Validation error is an error type -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/map_claims.go b/backend/vendor/github.com/golang-jwt/jwt/map_claims.go deleted file mode 100644 index 72c79f92e5..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/map_claims.go +++ /dev/null @@ -1,120 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - // "fmt" -) - -// Claims type that uses the map[string]interface{} for JSON decoding -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// VerifyAudience Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - var aud []string - switch v := m["aud"].(type) { - case string: - aud = append(aud, v) - case []string: - aud = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return false - } - aud = append(aud, vs) - } - } - return verifyAud(aud, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - exp, ok := m["exp"] - if !ok { - return !req - } - switch expType := exp.(type) { - case float64: - return verifyExp(int64(expType), cmp, req) - case json.Number: - v, _ := expType.Int64() - return verifyExp(v, cmp, req) - } - return false -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - iat, ok := m["iat"] - if !ok { - return !req - } - switch iatType := iat.(type) { - case float64: - return verifyIat(int64(iatType), cmp, req) - case json.Number: - v, _ := iatType.Int64() - return verifyIat(v, cmp, req) - } - return false -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - nbf, ok := m["nbf"] - if !ok { - return !req - } - switch nbfType := nbf.(type) { - case float64: - return verifyNbf(int64(nbfType), cmp, req) - case json.Number: - v, _ := nbfType.Int64() - return verifyNbf(v, cmp, req) - } - return false -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if !m.VerifyExpiresAt(now, false) { - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if !m.VerifyIssuedAt(now, false) { - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if !m.VerifyNotBefore(now, false) { - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/parser.go b/backend/vendor/github.com/golang-jwt/jwt/parser.go deleted file mode 100644 index d6901d9adb..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/parser.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// WARNING: Don't use this method unless you know what you're doing -// -// This method parses the token but doesn't validate the signature. It's only -// ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from -// it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/signing_method.go b/backend/vendor/github.com/golang-jwt/jwt/signing_method.go deleted file mode 100644 index ed1f212b21..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/signing_method.go +++ /dev/null @@ -1,35 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// Implement SigningMethod to add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// Register the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// Get a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/token.go b/backend/vendor/github.com/golang-jwt/jwt/token.go deleted file mode 100644 index 6b30ced120..0000000000 --- a/backend/vendor/github.com/golang-jwt/jwt/token.go +++ /dev/null @@ -1,104 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i := range parts { - var jsonValue []byte - if i == 0 { - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - } else { - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return new(Parser).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return base64.RawURLEncoding.EncodeToString(seg) -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - return base64.RawURLEncoding.DecodeString(seg) -} diff --git a/backend/vendor/github.com/golang-jwt/jwt/.gitignore b/backend/vendor/github.com/golang-jwt/jwt/v5/.gitignore similarity index 100% rename from backend/vendor/github.com/golang-jwt/jwt/.gitignore rename to backend/vendor/github.com/golang-jwt/jwt/v5/.gitignore diff --git a/backend/vendor/github.com/golang-jwt/jwt/LICENSE b/backend/vendor/github.com/golang-jwt/jwt/v5/LICENSE similarity index 100% rename from backend/vendor/github.com/golang-jwt/jwt/LICENSE rename to backend/vendor/github.com/golang-jwt/jwt/v5/LICENSE diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/backend/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md new file mode 100644 index 0000000000..ff9c57e1d8 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md @@ -0,0 +1,195 @@ +# Migration Guide (v5.0.0) + +Version `v5` contains a major rework of core functionalities in the `jwt-go` +library. This includes support for several validation options as well as a +re-design of the `Claims` interface. Lastly, we reworked how errors work under +the hood, which should provide a better overall developer experience. + +Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), +the import path will be: + + "github.com/golang-jwt/jwt/v5" + +For most users, changing the import path *should* suffice. However, since we +intentionally changed and cleaned some of the public API, existing programs +might need to be updated. The following sections describe significant changes +and corresponding updates for existing programs. + +## Parsing and Validation Options + +Under the hood, a new `Validator` struct takes care of validating the claims. A +long awaited feature has been the option to fine-tune the validation of tokens. +This is now possible with several `ParserOption` functions that can be appended +to most `Parse` functions, such as `ParseWithClaims`. The most important options +and changes are: + * Added `WithLeeway` to support specifying the leeway that is allowed when + validating time-based claims, such as `exp` or `nbf`. + * Changed default behavior to not check the `iat` claim. Usage of this claim + is OPTIONAL according to the JWT RFC. The claim itself is also purely + informational according to the RFC, so a strict validation failure is not + recommended. If you want to check for sensible values in these claims, + please use the `WithIssuedAt` parser option. + * Added `WithAudience`, `WithSubject` and `WithIssuer` to support checking for + expected `aud`, `sub` and `iss`. + * Added `WithStrictDecoding` and `WithPaddingAllowed` options to allow + previously global settings to enable base64 strict encoding and the parsing + of base64 strings with padding. The latter is strictly speaking against the + standard, but unfortunately some of the major identity providers issue some + of these incorrect tokens. Both options are disabled by default. + +## Changes to the `Claims` interface + +### Complete Restructuring + +Previously, the claims interface was satisfied with an implementation of a +`Valid() error` function. This had several issues: + * The different claim types (struct claims, map claims, etc.) then contained + similar (but not 100 % identical) code of how this validation was done. This + lead to a lot of (almost) duplicate code and was hard to maintain + * It was not really semantically close to what a "claim" (or a set of claims) + really is; which is a list of defined key/value pairs with a certain + semantic meaning. + +Since all the validation functionality is now extracted into the validator, all +`VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. +Instead, the interface now represents a list of getters to retrieve values with +a specific meaning. This allows us to completely decouple the validation logic +with the underlying storage representation of the claim, which could be a +struct, a map or even something stored in a database. + +```go +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} +``` + +Users that previously directly called the `Valid` function on their claims, +e.g., to perform validation independently of parsing/verifying a token, can now +use the `jwt.NewValidator` function to create a `Validator` independently of the +`Parser`. + +```go +var v = jwt.NewValidator(jwt.WithLeeway(5*time.Second)) +v.Validate(myClaims) +``` + +### Supported Claim Types and Removal of `StandardClaims` + +The two standard claim types supported by this library, `MapClaims` and +`RegisteredClaims` both implement the necessary functions of this interface. The +old `StandardClaims` struct, which has already been deprecated in `v4` is now +removed. + +Users using custom claims, in most cases, will not experience any changes in the +behavior as long as they embedded `RegisteredClaims`. If they created a new +claim type from scratch, they now need to implemented the proper getter +functions. + +### Migrating Application Specific Logic of the old `Valid` + +Previously, users could override the `Valid` method in a custom claim, for +example to extend the validation with application-specific claims. However, this +was always very dangerous, since once could easily disable the standard +validation and signature checking. + +In order to avoid that, while still supporting the use-case, a new +`ClaimsValidator` interface has been introduced. This interface consists of the +`Validate() error` function. If the validator sees, that a `Claims` struct +implements this interface, the errors returned to the `Validate` function will +be *appended* to the regular standard validation. It is not possible to disable +the standard validation anymore (even only by accident). + +Usage examples can be found in [example_test.go](./example_test.go), to build +claims structs like the following. + +```go +// MyCustomClaims includes all registered claims, plus Foo. +type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims +} + +// Validate can be used to execute additional application-specific claims +// validation. +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return errors.New("must be foobar") + } + + return nil +} +``` + +## Changes to the `Token` and `Parser` struct + +The previously global functions `DecodeSegment` and `EncodeSegment` were moved +to the `Parser` and `Token` struct respectively. This will allow us in the +future to configure the behavior of these two based on options supplied on the +parser or the token (creation). This also removes two previously global +variables and moves them to parser options `WithStrictDecoding` and +`WithPaddingAllowed`. + +In order to do that, we had to adjust the way signing methods work. Previously +they were given a base64 encoded signature in `Verify` and were expected to +return a base64 encoded version of the signature in `Sign`, both as a `string`. +However, this made it necessary to have `DecodeSegment` and `EncodeSegment` +global and was a less than perfect design because we were repeating +encoding/decoding steps for all signing methods. Now, `Sign` and `Verify` +operate on a decoded signature as a `[]byte`, which feels more natural for a +cryptographic operation anyway. Lastly, `Parse` and `SignedString` take care of +the final encoding/decoding part. + +In addition to that, we also changed the `Signature` field on `Token` from a +`string` to `[]byte` and this is also now populated with the decoded form. This +is also more consistent, because the other parts of the JWT, mainly `Header` and +`Claims` were already stored in decoded form in `Token`. Only the signature was +stored in base64 encoded form, which was redundant with the information in the +`Raw` field, which contains the complete token as base64. + +```go +type Token struct { + Raw string // Raw contains the raw token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form + Valid bool // Valid specifies if the token is valid +} +``` + +Most (if not all) of these changes should not impact the normal usage of this +library. Only users directly accessing the `Signature` field as well as +developers of custom signing methods should be affected. + +# Migration Guide (v4.0.0) + +Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), +the import path will be: + + "github.com/golang-jwt/jwt/v4" + +The `/v4` version will be backwards compatible with existing `v3.x.y` tags in +this repo, as well as `github.com/dgrijalva/jwt-go`. For most users this should +be a drop-in replacement, if you're having troubles migrating, please open an +issue. + +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or +`github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually +or by using tools such as `sed` or `gofmt`. + +And then you'd typically run: + +``` +go get github.com/golang-jwt/jwt/v4 +go mod tidy +``` + +# Older releases (before v3.2.0) + +The original migration guide for older releases can be found at +https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/README.md b/backend/vendor/github.com/golang-jwt/jwt/v5/README.md new file mode 100644 index 0000000000..964598a317 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/README.md @@ -0,0 +1,167 @@ +# jwt-go + +[![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) +[![Go +Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +[![Coverage Status](https://coveralls.io/repos/github/golang-jwt/jwt/badge.svg?branch=main)](https://coveralls.io/github/golang-jwt/jwt?branch=main) + +A [go](http://www.golang.org) (or 'golang' for search engine friendliness) +implementation of [JSON Web +Tokens](https://datatracker.ietf.org/doc/html/rfc7519). + +Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) +this project adds Go module support, but maintains backwards compatibility with +older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. See the +[`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version +v5.0.0 introduces major improvements to the validation of tokens, but is not +entirely backwards compatible. + +> After the original author of the library suggested migrating the maintenance +> of `jwt-go`, a dedicated team of open source maintainers decided to clone the +> existing library into this repository. See +> [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a +> detailed discussion on this topic. + + +**SECURITY NOTICE:** Some older versions of Go have a security issue in the +crypto/elliptic. Recommendation is to upgrade to at least 1.15 See issue +[dgrijalva/jwt-go#216](https://github.com/dgrijalva/jwt-go/issues/216) for more +detail. + +**SECURITY NOTICE:** It's important that you [validate the `alg` presented is +what you +expect](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/). +This library attempts to make it easy to do the right thing by requiring key +types match the expected alg, but you should take the extra step to verify it in +your usage. See the examples provided. + +### Supported Go versions + +Our support of Go versions is aligned with Go's [version release +policy](https://golang.org/doc/devel/release#policy). So we will support a major +version of Go until there are two newer major releases. We no longer support +building jwt-go with unsupported Go versions, as these contain security +vulnerabilities which will not be fixed. + +## What the heck is a JWT? + +JWT.io has [a great introduction](https://jwt.io/introduction) to JSON Web +Tokens. + +In short, it's a signed JSON object that does something useful (for example, +authentication). It's commonly used for `Bearer` tokens in Oauth 2. A token is +made of three parts, separated by `.`'s. The first two parts are JSON objects, +that have been [base64url](https://datatracker.ietf.org/doc/html/rfc4648) +encoded. The last part is the signature, encoded the same way. + +The first part is called the header. It contains the necessary information for +verifying the last part, the signature. For example, which encryption method +was used for signing and what key was used. + +The part in the middle is the interesting bit. It's called the Claims and +contains the actual stuff you care about. Refer to [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) for information about +reserved keys and the proper way to add your own. + +## What's in the box? + +This library supports the parsing and verification as well as the generation and +signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, +RSA-PSS, and ECDSA, though hooks are present for adding your own. + +## Installation Guidelines + +1. To install the jwt package, you first need to have + [Go](https://go.dev/doc/install) installed, then you can use the command + below to add `jwt-go` as a dependency in your Go program. + +```sh +go get -u github.com/golang-jwt/jwt/v5 +``` + +2. Import it in your code: + +```go +import "github.com/golang-jwt/jwt/v5" +``` + +## Usage + +A detailed usage guide, including how to sign and verify tokens can be found on +our [documentation website](https://golang-jwt.github.io/jwt/usage/create/). + +## Examples + +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +for examples of usage: + +* [Simple example of parsing and validating a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) +* [Simple example of building and signing a + token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) +* [Directory of + Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) + +## Compliance + +This library was last reviewed to comply with [RFC +7519](https://datatracker.ietf.org/doc/html/rfc7519) dated May 2015 with a few +notable differences: + +* In order to protect against accidental use of [Unsecured + JWTs](https://datatracker.ietf.org/doc/html/rfc7519#section-6), tokens using + `alg=none` will only be accepted if the constant + `jwt.UnsafeAllowNoneSignatureType` is provided as the key. + +## Project Status & Versioning + +This library is considered production ready. Feedback and feature requests are +appreciated. The API should be considered stable. There should be very few +backwards-incompatible changes outside of major version updates (and only with +good reason). + +This project uses [Semantic Versioning 2.0.0](http://semver.org). Accepted pull +requests will land on `main`. Periodically, versions will be tagged from +`main`. You can find all the releases on [the project releases +page](https://github.com/golang-jwt/jwt/releases). + +**BREAKING CHANGES:*** A full list of breaking changes is available in +`VERSION_HISTORY.md`. See `MIGRATION_GUIDE.md` for more information on updating +your code. + +## Extensions + +This library publishes all the necessary components for adding your own signing +methods or key functions. Simply implement the `SigningMethod` interface and +register a factory method using `RegisterSigningMethod` or provide a +`jwt.Keyfunc`. + +A common use case would be integrating with different 3rd party signature +providers, like key management services from various cloud providers or Hardware +Security Modules (HSMs) or to implement additional standards. + +| Extension | Purpose | Repo | +| --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | +| GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | +| AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | + +*Disclaimer*: Unless otherwise specified, these integrations are maintained by +third parties and should not be considered as a primary offer by any of the +mentioned cloud providers + +## More + +Go package documentation can be found [on +pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). Additional +documentation can be found on [our project +page](https://golang-jwt.github.io/jwt/). + +The command line utility included in this project (cmd/jwt) provides a +straightforward example of token creation and parsing as well as a useful tool +for debugging your own integration. You'll also find several implementation +examples in the documentation. + +[golang-jwt](https://github.com/orgs/golang-jwt) incorporates a modified version +of the JWT logo, which is distributed under the terms of the [MIT +License](https://github.com/jsonwebtoken/jsonwebtoken.github.io/blob/master/LICENSE.txt). diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md b/backend/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md new file mode 100644 index 0000000000..b08402c342 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md @@ -0,0 +1,19 @@ +# Security Policy + +## Supported Versions + +As of February 2022 (and until this document is updated), the latest version `v4` is supported. + +## Reporting a Vulnerability + +If you think you found a vulnerability, and even if you are not sure, please report it to jwt-go-security@googlegroups.com or one of the other [golang-jwt maintainers](https://github.com/orgs/golang-jwt/people). Please try be explicit, describe steps to reproduce the security issue with code example(s). + +You will receive a response within a timely manner. If the issue is confirmed, we will do our best to release a patch as soon as possible given the complexity of the problem. + +## Public Discussions + +Please avoid publicly discussing a potential security vulnerability. + +Let's take this offline and find a solution first, this limits the potential impact as much as possible. + +We appreciate your help! diff --git a/backend/vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md b/backend/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md similarity index 94% rename from backend/vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md rename to backend/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md index 637f2ba616..b5039e49c1 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/VERSION_HISTORY.md +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md @@ -1,13 +1,19 @@ -## `jwt-go` Version History +# `jwt-go` Version History -#### 3.2.2 +The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. + +## 4.0.0 + +* Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. + +## 3.2.2 * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). -#### 3.2.1 +## 3.2.1 * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` @@ -113,17 +119,17 @@ It is likely the only integration change required here will be to change `func(t * Refactored the RSA implementation to be easier to read * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` -#### 1.0.2 +## 1.0.2 * Fixed bug in parsing public keys from certificates * Added more tests around the parsing of keys for RS256 * Code refactoring in RS256 implementation. No functional changes -#### 1.0.1 +## 1.0.1 * Fixed panic if RS256 signing method was passed an invalid key -#### 1.0.0 +## 1.0.0 * First versioned release * API stabilized diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/claims.go b/backend/vendor/github.com/golang-jwt/jwt/v5/claims.go new file mode 100644 index 0000000000..d50ff3dad8 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/claims.go @@ -0,0 +1,16 @@ +package jwt + +// Claims represent any form of a JWT Claims Set according to +// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a +// common basis for validation, it is required that an implementation is able to +// supply at least the claim names provided in +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, +// `iat`, `nbf`, `iss`, `sub` and `aud`. +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/doc.go b/backend/vendor/github.com/golang-jwt/jwt/v5/doc.go similarity index 100% rename from backend/vendor/github.com/golang-jwt/jwt/doc.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/doc.go diff --git a/backend/vendor/github.com/golang-jwt/jwt/ecdsa.go b/backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go similarity index 83% rename from backend/vendor/github.com/golang-jwt/jwt/ecdsa.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go index 15e23435df..c929e4a02f 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/ecdsa.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go @@ -13,7 +13,7 @@ var ( ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") ) -// Implements the ECDSA family of signing methods signing methods +// SigningMethodECDSA implements the ECDSA family of signing methods. // Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification type SigningMethodECDSA struct { Name string @@ -53,24 +53,16 @@ func (m *SigningMethodECDSA) Alg() string { return m.Name } -// Implements the Verify method from SigningMethod +// Verify implements token verification for the SigningMethod. // For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodECDSA) Verify(signingString string, sig []byte, key interface{}) error { // Get the key var ecdsaKey *ecdsa.PublicKey switch k := key.(type) { case *ecdsa.PublicKey: ecdsaKey = k default: - return ErrInvalidKeyType + return newError("ECDSA verify expects *ecdsa.PublicKey", ErrInvalidKeyType) } if len(sig) != 2*m.KeySize { @@ -95,21 +87,21 @@ func (m *SigningMethodECDSA) Verify(signingString, signature string, key interfa return ErrECDSAVerification } -// Implements the Sign method from SigningMethod +// Sign implements token signing for the SigningMethod. // For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) ([]byte, error) { // Get the key var ecdsaKey *ecdsa.PrivateKey switch k := key.(type) { case *ecdsa.PrivateKey: ecdsaKey = k default: - return "", ErrInvalidKeyType + return nil, newError("ECDSA sign expects *ecdsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -120,7 +112,7 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string curveBits := ecdsaKey.Curve.Params().BitSize if m.CurveBits != curveBits { - return "", ErrInvalidKey + return nil, ErrInvalidKey } keyBytes := curveBits / 8 @@ -135,8 +127,8 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output. s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output. - return EncodeSegment(out), nil + return out, nil } else { - return "", err + return nil, err } } diff --git a/backend/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go b/backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go similarity index 81% rename from backend/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go index db9f4be7d8..5700636d35 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/ecdsa_utils.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go @@ -8,11 +8,11 @@ import ( ) var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") + ErrNotECPublicKey = errors.New("key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("key is not a valid ECDSA private key") ) -// Parse PEM encoded Elliptic Curve Private Key Structure +// ParseECPrivateKeyFromPEM parses a PEM encoded Elliptic Curve Private Key Structure func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { var err error @@ -39,7 +39,7 @@ func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { return pkey, nil } -// Parse PEM encoded PKCS1 or PKCS8 public key +// ParseECPublicKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 public key func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { var err error diff --git a/backend/vendor/github.com/golang-jwt/jwt/ed25519.go b/backend/vendor/github.com/golang-jwt/jwt/v5/ed25519.go similarity index 52% rename from backend/vendor/github.com/golang-jwt/jwt/ed25519.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/ed25519.go index a2f8ddbe9b..c2138119e5 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/ed25519.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/ed25519.go @@ -1,16 +1,17 @@ package jwt import ( - "errors" - + "crypto" "crypto/ed25519" + "crypto/rand" + "errors" ) var ( ErrEd25519Verification = errors.New("ed25519: verification error") ) -// Implements the EdDSA family +// SigningMethodEd25519 implements the EdDSA family. // Expects ed25519.PrivateKey for signing and ed25519.PublicKey for verification type SigningMethodEd25519 struct{} @@ -30,27 +31,20 @@ func (m *SigningMethodEd25519) Alg() string { return "EdDSA" } -// Implements the Verify method from SigningMethod +// Verify implements token verification for the SigningMethod. // For this verify method, key must be an ed25519.PublicKey -func (m *SigningMethodEd25519) Verify(signingString, signature string, key interface{}) error { - var err error +func (m *SigningMethodEd25519) Verify(signingString string, sig []byte, key interface{}) error { var ed25519Key ed25519.PublicKey var ok bool if ed25519Key, ok = key.(ed25519.PublicKey); !ok { - return ErrInvalidKeyType + return newError("Ed25519 verify expects ed25519.PublicKey", ErrInvalidKeyType) } if len(ed25519Key) != ed25519.PublicKeySize { return ErrInvalidKey } - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - // Verify the signature if !ed25519.Verify(ed25519Key, []byte(signingString), sig) { return ErrEd25519Verification @@ -59,23 +53,27 @@ func (m *SigningMethodEd25519) Verify(signingString, signature string, key inter return nil } -// Implements the Sign method from SigningMethod +// Sign implements token signing for the SigningMethod. // For this signing method, key must be an ed25519.PrivateKey -func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) (string, error) { - var ed25519Key ed25519.PrivateKey +func (m *SigningMethodEd25519) Sign(signingString string, key interface{}) ([]byte, error) { + var ed25519Key crypto.Signer var ok bool - if ed25519Key, ok = key.(ed25519.PrivateKey); !ok { - return "", ErrInvalidKeyType + if ed25519Key, ok = key.(crypto.Signer); !ok { + return nil, newError("Ed25519 sign expects crypto.Signer", ErrInvalidKeyType) + } + + if _, ok := ed25519Key.Public().(ed25519.PublicKey); !ok { + return nil, ErrInvalidKey } - // ed25519.Sign panics if private key not equal to ed25519.PrivateKeySize - // this allows to avoid recover usage - if len(ed25519Key) != ed25519.PrivateKeySize { - return "", ErrInvalidKey + // Sign the string and return the result. ed25519 performs a two-pass hash + // as part of its algorithm. Therefore, we need to pass a non-prehashed + // message into the Sign function, as indicated by crypto.Hash(0) + sig, err := ed25519Key.Sign(rand.Reader, []byte(signingString), crypto.Hash(0)) + if err != nil { + return nil, err } - // Sign the string and return the encoded result - sig := ed25519.Sign(ed25519Key, []byte(signingString)) - return EncodeSegment(sig), nil + return sig, nil } diff --git a/backend/vendor/github.com/golang-jwt/jwt/ed25519_utils.go b/backend/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go similarity index 80% rename from backend/vendor/github.com/golang-jwt/jwt/ed25519_utils.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go index c6357275ef..cdb5e68e87 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/ed25519_utils.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go @@ -9,11 +9,11 @@ import ( ) var ( - ErrNotEdPrivateKey = errors.New("Key is not a valid Ed25519 private key") - ErrNotEdPublicKey = errors.New("Key is not a valid Ed25519 public key") + ErrNotEdPrivateKey = errors.New("key is not a valid Ed25519 private key") + ErrNotEdPublicKey = errors.New("key is not a valid Ed25519 public key") ) -// Parse PEM-encoded Edwards curve private key +// ParseEdPrivateKeyFromPEM parses a PEM-encoded Edwards curve private key func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { var err error @@ -38,7 +38,7 @@ func ParseEdPrivateKeyFromPEM(key []byte) (crypto.PrivateKey, error) { return pkey, nil } -// Parse PEM-encoded Edwards curve public key +// ParseEdPublicKeyFromPEM parses a PEM-encoded Edwards curve public key func ParseEdPublicKeyFromPEM(key []byte) (crypto.PublicKey, error) { var err error diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/errors.go b/backend/vendor/github.com/golang-jwt/jwt/v5/errors.go new file mode 100644 index 0000000000..23bb616ddd --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/errors.go @@ -0,0 +1,49 @@ +package jwt + +import ( + "errors" + "strings" +) + +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + ErrTokenMalformed = errors.New("token is malformed") + ErrTokenUnverifiable = errors.New("token is unverifiable") + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") + ErrTokenInvalidAudience = errors.New("token has invalid audience") + ErrTokenExpired = errors.New("token is expired") + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + ErrTokenInvalidSubject = errors.New("token has invalid subject") + ErrTokenNotValidYet = errors.New("token is not valid yet") + ErrTokenInvalidId = errors.New("token has invalid id") + ErrTokenInvalidClaims = errors.New("token has invalid claims") + ErrInvalidType = errors.New("invalid type for claim") +) + +// joinedError is an error type that works similar to what [errors.Join] +// produces, with the exception that it has a nice error string; mainly its +// error messages are concatenated using a comma, rather than a newline. +type joinedError struct { + errs []error +} + +func (je joinedError) Error() string { + msg := []string{} + for _, err := range je.errs { + msg = append(msg, err.Error()) + } + + return strings.Join(msg, ", ") +} + +// joinErrors joins together multiple errors. Useful for scenarios where +// multiple errors next to each other occur, e.g., in claims validation. +func joinErrors(errs ...error) error { + return &joinedError{ + errs: errs, + } +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go b/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go new file mode 100644 index 0000000000..a893d355e1 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go @@ -0,0 +1,47 @@ +//go:build go1.20 +// +build go1.20 + +package jwt + +import ( + "fmt" +) + +// Unwrap implements the multiple error unwrapping for this error type, which is +// possible in Go 1.20. +func (je joinedError) Unwrap() []error { + return je.errs +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. This makes use of Go 1.20's possibility to +// include more than one %w formatting directive in [fmt.Errorf]. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + var format string + var args []any + if message != "" { + format = "%w: %s" + args = []any{err, message} + } else { + format = "%w" + args = []any{err} + } + + for _, e := range more { + format += ": %w" + args = append(args, e) + } + + err = fmt.Errorf(format, args...) + return err +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go new file mode 100644 index 0000000000..2ad542f00c --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go @@ -0,0 +1,78 @@ +//go:build !go1.20 +// +build !go1.20 + +package jwt + +import ( + "errors" + "fmt" +) + +// Is implements checking for multiple errors using [errors.Is], since multiple +// error unwrapping is not possible in versions less than Go 1.20. +func (je joinedError) Is(err error) bool { + for _, e := range je.errs { + if errors.Is(e, err) { + return true + } + } + + return false +} + +// wrappedErrors is a workaround for wrapping multiple errors in environments +// where Go 1.20 is not available. It basically uses the already implemented +// functionality of joinedError to handle multiple errors with supplies a +// custom error message that is identical to the one we produce in Go 1.20 using +// multiple %w directives. +type wrappedErrors struct { + msg string + joinedError +} + +// Error returns the stored error string +func (we wrappedErrors) Error() string { + return we.msg +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. Since we cannot use of Go 1.20's possibility +// to include more than one %w formatting directive in [fmt.Errorf], we have to +// emulate that. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + // We cannot wrap multiple errors here with %w, so we have to be a little + // bit creative. Basically, we are using %s instead of %w to produce the + // same error message and then throw the result into a custom error struct. + var format string + var args []any + if message != "" { + format = "%s: %s" + args = []any{err, message} + } else { + format = "%s" + args = []any{err} + } + errs := []error{err} + + for _, e := range more { + format += ": %s" + args = append(args, e) + errs = append(errs, e) + } + + err = &wrappedErrors{ + msg: fmt.Sprintf(format, args...), + joinedError: joinedError{errs: errs}, + } + return err +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/hmac.go b/backend/vendor/github.com/golang-jwt/jwt/v5/hmac.go similarity index 53% rename from backend/vendor/github.com/golang-jwt/jwt/hmac.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/hmac.go index addbe5d401..aca600ce1b 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/hmac.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/hmac.go @@ -6,7 +6,7 @@ import ( "errors" ) -// Implements the HMAC-SHA family of signing methods signing methods +// SigningMethodHMAC implements the HMAC-SHA family of signing methods. // Expects key type of []byte for both signing and validation type SigningMethodHMAC struct { Name string @@ -45,18 +45,21 @@ func (m *SigningMethodHMAC) Alg() string { return m.Name } -// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { +// Verify implements token verification for the SigningMethod. Returns nil if +// the signature is valid. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types. +func (m *SigningMethodHMAC) Verify(signingString string, sig []byte, key interface{}) error { // Verify the key is the right type keyBytes, ok := key.([]byte) if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err + return newError("HMAC verify expects []byte", ErrInvalidKeyType) } // Can we use the specified hashing method? @@ -77,19 +80,25 @@ func (m *SigningMethodHMAC) Verify(signingString, signature string, key interfac return nil } -// Implements the Sign method from SigningMethod for this signing method. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { +// Sign implements token signing for the SigningMethod. Key must be []byte. +// +// Note it is not advised to provide a []byte which was converted from a 'human +// readable' string using a subset of ASCII characters. To maximize entropy, you +// should ideally be providing a []byte key which was produced from a +// cryptographically random source, e.g. crypto/rand. Additional information +// about this, and why we intentionally are not supporting string as a key can +// be found on our usage guide https://golang-jwt.github.io/jwt/usage/signing_methods/. +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) ([]byte, error) { if keyBytes, ok := key.([]byte); ok { if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := hmac.New(m.Hash.New, keyBytes) hasher.Write([]byte(signingString)) - return EncodeSegment(hasher.Sum(nil)), nil + return hasher.Sum(nil), nil } - return "", ErrInvalidKeyType + return nil, newError("HMAC sign expects []byte", ErrInvalidKeyType) } diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/backend/vendor/github.com/golang-jwt/jwt/v5/map_claims.go new file mode 100644 index 0000000000..b2b51a1f80 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/map_claims.go @@ -0,0 +1,109 @@ +package jwt + +import ( + "encoding/json" + "fmt" +) + +// MapClaims is a claims type that uses the map[string]interface{} for JSON +// decoding. This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// GetExpirationTime implements the Claims interface. +func (m MapClaims) GetExpirationTime() (*NumericDate, error) { + return m.parseNumericDate("exp") +} + +// GetNotBefore implements the Claims interface. +func (m MapClaims) GetNotBefore() (*NumericDate, error) { + return m.parseNumericDate("nbf") +} + +// GetIssuedAt implements the Claims interface. +func (m MapClaims) GetIssuedAt() (*NumericDate, error) { + return m.parseNumericDate("iat") +} + +// GetAudience implements the Claims interface. +func (m MapClaims) GetAudience() (ClaimStrings, error) { + return m.parseClaimsString("aud") +} + +// GetIssuer implements the Claims interface. +func (m MapClaims) GetIssuer() (string, error) { + return m.parseString("iss") +} + +// GetSubject implements the Claims interface. +func (m MapClaims) GetSubject() (string, error) { + return m.parseString("sub") +} + +// parseNumericDate tries to parse a key in the map claims type as a number +// date. This will succeed, if the underlying type is either a [float64] or a +// [json.Number]. Otherwise, nil will be returned. +func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { + v, ok := m[key] + if !ok { + return nil, nil + } + + switch exp := v.(type) { + case float64: + if exp == 0 { + return nil, nil + } + + return newNumericDateFromSeconds(exp), nil + case json.Number: + v, _ := exp.Float64() + + return newNumericDateFromSeconds(v), nil + } + + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) +} + +// parseClaimsString tries to parse a key in the map claims type as a +// [ClaimsStrings] type, which can either be a string or an array of string. +func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { + var cs []string + switch v := m[key].(type) { + case string: + cs = append(cs, v) + case []string: + cs = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + cs = append(cs, vs) + } + } + + return cs, nil +} + +// parseString tries to parse a key in the map claims type as a [string] type. +// If the key does not exist, an empty string is returned. If the key has the +// wrong type, an error is returned. +func (m MapClaims) parseString(key string) (string, error) { + var ( + ok bool + raw interface{} + iss string + ) + raw, ok = m[key] + if !ok { + return "", nil + } + + iss, ok = raw.(string) + if !ok { + return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + + return iss, nil +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/none.go b/backend/vendor/github.com/golang-jwt/jwt/v5/none.go similarity index 68% rename from backend/vendor/github.com/golang-jwt/jwt/none.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/none.go index f04d189d06..685c2ea306 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/none.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/none.go @@ -1,6 +1,6 @@ package jwt -// Implements the none signing method. This is required by the spec +// SigningMethodNone implements the none signing method. This is required by the spec // but you probably should never use it. var SigningMethodNone *signingMethodNone @@ -13,7 +13,7 @@ type unsafeNoneMagicConstant string func init() { SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { return SigningMethodNone @@ -25,18 +25,15 @@ func (m *signingMethodNone) Alg() string { } // Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { +func (m *signingMethodNone) Verify(signingString string, sig []byte, key interface{}) (err error) { // Key must be UnsafeAllowNoneSignatureType to prevent accidentally // accepting 'none' signing method if _, ok := key.(unsafeNoneMagicConstant); !ok { return NoneSignatureTypeDisallowedError } // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) + if len(sig) != 0 { + return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) } // Accept 'none' signing method. @@ -44,9 +41,10 @@ func (m *signingMethodNone) Verify(signingString, signature string, key interfac } // Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { +func (m *signingMethodNone) Sign(signingString string, key interface{}) ([]byte, error) { if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil + return []byte{}, nil } - return "", NoneSignatureTypeDisallowedError + + return nil, NoneSignatureTypeDisallowedError } diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/parser.go b/backend/vendor/github.com/golang-jwt/jwt/v5/parser.go new file mode 100644 index 0000000000..ecf99af78f --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/parser.go @@ -0,0 +1,238 @@ +package jwt + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + // If populated, only these methods will be considered valid. + validMethods []string + + // Use JSON Number format in JSON decoder. + useJSONNumber bool + + // Skip claims validation during token parsing. + skipClaimsValidation bool + + validator *Validator + + decodeStrict bool + + decodePaddingAllowed bool +} + +// NewParser creates a new Parser with the specified options +func NewParser(options ...ParserOption) *Parser { + p := &Parser{ + validator: &Validator{}, + } + + // Loop through our parsing options and apply them + for _, option := range options { + option(p) + } + + return p +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the key for validating. +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims +// interface. This provides default values which can be overridden and allows a caller to use their own type, rather +// than the default MapClaims implementation of Claims. +// +// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), +// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the +// proper memory for it before passing in the overall claims, otherwise you might run into a panic. +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } + + // Verify signing method is in the required set + if p.validMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.validMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) + } + } + + // Decode signature + token.Signature, err = p.DecodeSegment(parts[2]) + if err != nil { + return token, newError("could not base64 decode signature", ErrTokenMalformed, err) + } + text := strings.Join(parts[0:2], ".") + + // Lookup key(s) + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, newError("no keyfunc was provided", ErrTokenUnverifiable) + } + + got, err := keyFunc(token) + if err != nil { + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) + } + + switch have := got.(type) { + case VerificationKeySet: + if len(have.Keys) == 0 { + return token, newError("keyfunc returned empty verification key set", ErrTokenUnverifiable) + } + // Iterate through keys and verify signature, skipping the rest when a match is found. + // Return the last error if no match is found. + for _, key := range have.Keys { + if err = token.Method.Verify(text, token.Signature, key); err == nil { + break + } + } + default: + err = token.Method.Verify(text, token.Signature, have) + } + if err != nil { + return token, newError("", ErrTokenSignatureInvalid, err) + } + + // Validate Claims + if !p.skipClaimsValidation { + // Make sure we have at least a default validator + if p.validator == nil { + p.validator = NewValidator() + } + + if err := p.validator.Validate(claims); err != nil { + return token, newError("", ErrTokenInvalidClaims, err) + } + } + + // No errors so far, token is valid. + token.Valid = true + + return token, nil +} + +// ParseUnverified parses the token but doesn't validate the signature. +// +// WARNING: Don't use this method unless you know what you're doing. +// +// It's only ever useful in cases where you know the signature is valid (since it has already +// been or will be checked elsewhere in the stack) and you want to extract values from it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = p.DecodeSegment(parts[0]); err != nil { + return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) + } + + // parse Claims + token.Claims = claims + + claimBytes, err := p.DecodeSegment(parts[1]) + if err != nil { + return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) + } + + // If `useJSONNumber` is enabled then we must use *json.Decoder to decode + // the claims. However, this comes with a performance penalty so only use + // it if we must and, otherwise, simple use json.Unmarshal. + if !p.useJSONNumber { + // JSON Unmarshal. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = json.Unmarshal(claimBytes, &c) + } else { + err = json.Unmarshal(claimBytes, &claims) + } + } else { + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + dec.UseNumber() + // JSON Decode. Special case for map type to avoid weird pointer behavior. + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + } + if err != nil { + return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) + } + } else { + return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) + } + + return token, parts, nil +} + +// DecodeSegment decodes a JWT specific base64url encoding. This function will +// take into account whether the [Parser] is configured with additional options, +// such as [WithStrictDecoding] or [WithPaddingAllowed]. +func (p *Parser) DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding + + if p.decodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } + + if p.decodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the cryptographic key +// for verifying the signature. The caller is strongly encouraged to set the +// WithValidMethods option to validate the 'alg' claim in the token matches the +// expected algorithm. For more details about the importance of validating the +// 'alg' claim, see +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) +} + +// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). +// +// Note: If you provide a custom claim implementation that embeds one of the +// standard claims (such as RegisteredClaims), make sure that a) you either +// embed a non-pointer version of the claims or b) if you are using a pointer, +// allocate the proper memory for it before passing in the overall claims, +// otherwise you might run into a panic. +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/backend/vendor/github.com/golang-jwt/jwt/v5/parser_option.go new file mode 100644 index 0000000000..88a780fbd4 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/parser_option.go @@ -0,0 +1,128 @@ +package jwt + +import "time" + +// ParserOption is used to implement functional-style options that modify the +// behavior of the parser. To add new options, just create a function (ideally +// beginning with With or Without) that returns an anonymous function that takes +// a *Parser type as input and manipulates its configuration accordingly. +type ParserOption func(*Parser) + +// WithValidMethods is an option to supply algorithm methods that the parser +// will check. Only those methods will be considered valid. It is heavily +// encouraged to use this option in order to prevent attacks such as +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. +func WithValidMethods(methods []string) ParserOption { + return func(p *Parser) { + p.validMethods = methods + } +} + +// WithJSONNumber is an option to configure the underlying JSON parser with +// UseNumber. +func WithJSONNumber() ParserOption { + return func(p *Parser) { + p.useJSONNumber = true + } +} + +// WithoutClaimsValidation is an option to disable claims validation. This +// option should only be used if you exactly know what you are doing. +func WithoutClaimsValidation() ParserOption { + return func(p *Parser) { + p.skipClaimsValidation = true + } +} + +// WithLeeway returns the ParserOption for specifying the leeway window. +func WithLeeway(leeway time.Duration) ParserOption { + return func(p *Parser) { + p.validator.leeway = leeway + } +} + +// WithTimeFunc returns the ParserOption for specifying the time func. The +// primary use-case for this is testing. If you are looking for a way to account +// for clock-skew, WithLeeway should be used instead. +func WithTimeFunc(f func() time.Time) ParserOption { + return func(p *Parser) { + p.validator.timeFunc = f + } +} + +// WithIssuedAt returns the ParserOption to enable verification +// of issued-at. +func WithIssuedAt() ParserOption { + return func(p *Parser) { + p.validator.verifyIat = true + } +} + +// WithExpirationRequired returns the ParserOption to make exp claim required. +// By default exp claim is optional. +func WithExpirationRequired() ParserOption { + return func(p *Parser) { + p.validator.requireExp = true + } +} + +// WithAudience configures the validator to require the specified audience in +// the `aud` claim. Validation will fail if the audience is not listed in the +// token or the `aud` claim is missing. +// +// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an audience is expected. +func WithAudience(aud string) ParserOption { + return func(p *Parser) { + p.validator.expectedAud = aud + } +} + +// WithIssuer configures the validator to require the specified issuer in the +// `iss` claim. Validation will fail if a different issuer is specified in the +// token or the `iss` claim is missing. +// +// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an issuer is expected. +func WithIssuer(iss string) ParserOption { + return func(p *Parser) { + p.validator.expectedIss = iss + } +} + +// WithSubject configures the validator to require the specified subject in the +// `sub` claim. Validation will fail if a different subject is specified in the +// token or the `sub` claim is missing. +// +// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if a subject is expected. +func WithSubject(sub string) ParserOption { + return func(p *Parser) { + p.validator.expectedSub = sub + } +} + +// WithPaddingAllowed will enable the codec used for decoding JWTs to allow +// padding. Note that the JWS RFC7515 states that the tokens will utilize a +// Base64url encoding with no padding. Unfortunately, some implementations of +// JWT are producing non-standard tokens, and thus require support for decoding. +func WithPaddingAllowed() ParserOption { + return func(p *Parser) { + p.decodePaddingAllowed = true + } +} + +// WithStrictDecoding will switch the codec used for decoding JWTs into strict +// mode. In this mode, the decoder requires that trailing padding bits are zero, +// as described in RFC 4648 section 3.5. +func WithStrictDecoding() ParserOption { + return func(p *Parser) { + p.decodeStrict = true + } +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go b/backend/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go new file mode 100644 index 0000000000..77951a531d --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go @@ -0,0 +1,63 @@ +package jwt + +// RegisteredClaims are a structured version of the JWT Claims Set, +// restricted to Registered Claim Names, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +// +// This type can be used on its own, but then additional private and +// public claims embedded in the JWT will not be parsed. The typical use-case +// therefore is to embedded this in a user-defined claim type. +// +// See examples for how to use this with your own claim types. +type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` + + // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` + + // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` + + // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` + + // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` + + // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` + + // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` +} + +// GetExpirationTime implements the Claims interface. +func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { + return c.ExpiresAt, nil +} + +// GetNotBefore implements the Claims interface. +func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { + return c.NotBefore, nil +} + +// GetIssuedAt implements the Claims interface. +func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { + return c.IssuedAt, nil +} + +// GetAudience implements the Claims interface. +func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { + return c.Audience, nil +} + +// GetIssuer implements the Claims interface. +func (c RegisteredClaims) GetIssuer() (string, error) { + return c.Issuer, nil +} + +// GetSubject implements the Claims interface. +func (c RegisteredClaims) GetSubject() (string, error) { + return c.Subject, nil +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/rsa.go b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa.go similarity index 77% rename from backend/vendor/github.com/golang-jwt/jwt/rsa.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/rsa.go index e4caf1ca4a..83cbee6ae2 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/rsa.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa.go @@ -6,7 +6,7 @@ import ( "crypto/rsa" ) -// Implements the RSA family of signing methods signing methods +// SigningMethodRSA implements the RSA family of signing methods. // Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation type SigningMethodRSA struct { Name string @@ -44,22 +44,14 @@ func (m *SigningMethodRSA) Alg() string { return m.Name } -// Implements the Verify method from SigningMethod +// Verify implements token verification for the SigningMethod // For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSA) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey var ok bool if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType + return newError("RSA verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -73,20 +65,20 @@ func (m *SigningMethodRSA) Verify(signingString, signature string, key interface return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) } -// Implements the Sign method from SigningMethod +// Sign implements token signing for the SigningMethod // For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey var ok bool // Validate type of key if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey + return nil, newError("RSA sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -94,8 +86,8 @@ func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/backend/vendor/github.com/golang-jwt/jwt/rsa_pss.go b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go similarity index 83% rename from backend/vendor/github.com/golang-jwt/jwt/rsa_pss.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go index c014708648..28c386ec43 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/rsa_pss.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go @@ -1,3 +1,4 @@ +//go:build go1.4 // +build go1.4 package jwt @@ -8,7 +9,7 @@ import ( "crypto/rsa" ) -// Implements the RSAPSS family of signing methods signing methods +// SigningMethodRSAPSS implements the RSAPSS family of signing methods signing methods type SigningMethodRSAPSS struct { *SigningMethodRSA Options *rsa.PSSOptions @@ -79,23 +80,15 @@ func init() { }) } -// Implements the Verify method from SigningMethod +// Verify implements token verification for the SigningMethod. // For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - +func (m *SigningMethodRSAPSS) Verify(signingString string, sig []byte, key interface{}) error { var rsaKey *rsa.PublicKey switch k := key.(type) { case *rsa.PublicKey: rsaKey = k default: - return ErrInvalidKey + return newError("RSA-PSS verify expects *rsa.PublicKey", ErrInvalidKeyType) } // Create hasher @@ -113,21 +106,21 @@ func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interf return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, opts) } -// Implements the Sign method from SigningMethod +// Sign implements token signing for the SigningMethod. // For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) ([]byte, error) { var rsaKey *rsa.PrivateKey switch k := key.(type) { case *rsa.PrivateKey: rsaKey = k default: - return "", ErrInvalidKeyType + return nil, newError("RSA-PSS sign expects *rsa.PrivateKey", ErrInvalidKeyType) } // Create the hasher if !m.Hash.Available() { - return "", ErrHashUnavailable + return nil, ErrHashUnavailable } hasher := m.Hash.New() @@ -135,8 +128,8 @@ func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (strin // Sign the string and return the encoded bytes if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil + return sigBytes, nil } else { - return "", err + return nil, err } } diff --git a/backend/vendor/github.com/golang-jwt/jwt/rsa_utils.go b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go similarity index 69% rename from backend/vendor/github.com/golang-jwt/jwt/rsa_utils.go rename to backend/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go index 14c78c292a..b3aeebbe11 100644 --- a/backend/vendor/github.com/golang-jwt/jwt/rsa_utils.go +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go @@ -8,12 +8,12 @@ import ( ) var ( - ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be a PEM encoded PKCS1 or PKCS8 key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") + ErrKeyMustBePEMEncoded = errors.New("invalid key: Key must be a PEM encoded PKCS1 or PKCS8 key") + ErrNotRSAPrivateKey = errors.New("key is not a valid RSA private key") + ErrNotRSAPublicKey = errors.New("key is not a valid RSA public key") ) -// Parse PEM encoded PKCS1 or PKCS8 private key +// ParseRSAPrivateKeyFromPEM parses a PEM encoded PKCS1 or PKCS8 private key func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { var err error @@ -39,7 +39,11 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { return pkey, nil } -// Parse PEM encoded PKCS1 or PKCS8 private key protected with password +// ParseRSAPrivateKeyFromPEMWithPassword parses a PEM encoded PKCS1 or PKCS8 private key protected with password +// +// Deprecated: This function is deprecated and should not be used anymore. It uses the deprecated x509.DecryptPEMBlock +// function, which was deprecated since RFC 1423 is regarded insecure by design. Unfortunately, there is no alternative +// in the Go standard library for now. See https://github.com/golang/go/issues/8860. func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { var err error @@ -71,7 +75,7 @@ func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.Pr return pkey, nil } -// Parse PEM encoded PKCS1 or PKCS8 public key +// ParseRSAPublicKeyFromPEM parses a certificate or a PEM encoded PKCS1 or PKIX public key func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { var err error @@ -87,7 +91,9 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { if cert, err := x509.ParseCertificate(block.Bytes); err == nil { parsedKey = cert.PublicKey } else { - return nil, err + if parsedKey, err = x509.ParsePKCS1PublicKey(block.Bytes); err != nil { + return nil, err + } } } diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/signing_method.go b/backend/vendor/github.com/golang-jwt/jwt/v5/signing_method.go new file mode 100644 index 0000000000..0d73631c1b --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/signing_method.go @@ -0,0 +1,49 @@ +package jwt + +import ( + "sync" +) + +var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) + +// SigningMethod can be used add new methods for signing or verifying tokens. It +// takes a decoded signature as an input in the Verify function and produces a +// signature in Sign. The signature is then usually base64 encoded as part of a +// JWT. +type SigningMethod interface { + Verify(signingString string, sig []byte, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) ([]byte, error) // Returns signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') +} + +// RegisterSigningMethod registers the "alg" name and a factory function for signing method. +// This is typically done during init() in the method's implementation +func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + + signingMethods[alg] = f +} + +// GetSigningMethod retrieves a signing method from an "alg" string +func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + if methodF, ok := signingMethods[alg]; ok { + method = methodF() + } + return +} + +// GetAlgorithms returns a list of registered "alg" names +func GetAlgorithms() (algs []string) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + for alg := range signingMethods { + algs = append(algs, alg) + } + return +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf b/backend/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf new file mode 100644 index 0000000000..53745d51d7 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf @@ -0,0 +1 @@ +checks = ["all", "-ST1000", "-ST1003", "-ST1016", "-ST1023"] diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/token.go b/backend/vendor/github.com/golang-jwt/jwt/v5/token.go new file mode 100644 index 0000000000..352873a2d9 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/token.go @@ -0,0 +1,100 @@ +package jwt + +import ( + "crypto" + "encoding/base64" + "encoding/json" +) + +// Keyfunc will be used by the Parse methods as a callback function to supply +// the key for verification. The function receives the parsed, but unverified +// Token. This allows you to use properties in the Header of the token (such as +// `kid`) to identify which key to use. +// +// The returned interface{} may be a single key or a VerificationKeySet containing +// multiple keys. +type Keyfunc func(*Token) (interface{}, error) + +// VerificationKey represents a public or secret key for verifying a token's signature. +type VerificationKey interface { + crypto.PublicKey | []uint8 +} + +// VerificationKeySet is a set of public or secret keys. It is used by the parser to verify a token. +type VerificationKeySet struct { + Keys []VerificationKey +} + +// Token represents a JWT Token. Different fields will be used depending on +// whether you're creating or parsing/verifying a token. +type Token struct { + Raw string // Raw contains the raw token. Populated when you [Parse] a token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token in decoded form + Claims Claims // Claims is the second segment of the token in decoded form + Signature []byte // Signature is the third segment of the token in decoded form. Populated when you Parse a token + Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token +} + +// New creates a new [Token] with the specified signing method and an empty map +// of claims. Additional options can be specified, but are currently unused. +func New(method SigningMethod, opts ...TokenOption) *Token { + return NewWithClaims(method, MapClaims{}, opts...) +} + +// NewWithClaims creates a new [Token] with the specified signing method and +// claims. Additional options can be specified, but are currently unused. +func NewWithClaims(method SigningMethod, claims Claims, opts ...TokenOption) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// SignedString creates and returns a complete, signed JWT. The token is signed +// using the SigningMethod specified in the token. Please refer to +// https://golang-jwt.github.io/jwt/usage/signing_methods/#signing-methods-and-key-types +// for an overview of the different signing methods and their respective key +// types. +func (t *Token) SignedString(key interface{}) (string, error) { + sstr, err := t.SigningString() + if err != nil { + return "", err + } + + sig, err := t.Method.Sign(sstr, key) + if err != nil { + return "", err + } + + return sstr + "." + t.EncodeSegment(sig), nil +} + +// SigningString generates the signing string. This is the most expensive part +// of the whole deal. Unless you need this for something special, just go +// straight for the SignedString. +func (t *Token) SigningString() (string, error) { + h, err := json.Marshal(t.Header) + if err != nil { + return "", err + } + + c, err := json.Marshal(t.Claims) + if err != nil { + return "", err + } + + return t.EncodeSegment(h) + "." + t.EncodeSegment(c), nil +} + +// EncodeSegment encodes a JWT specific base64url encoding with padding +// stripped. In the future, this function might take into account a +// [TokenOption]. Therefore, this function exists as a method of [Token], rather +// than a global function. +func (*Token) EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/token_option.go b/backend/vendor/github.com/golang-jwt/jwt/v5/token_option.go new file mode 100644 index 0000000000..b4ae3badf8 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/token_option.go @@ -0,0 +1,5 @@ +package jwt + +// TokenOption is a reserved type, which provides some forward compatibility, +// if we ever want to introduce token creation-related options. +type TokenOption func(*Token) diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/types.go b/backend/vendor/github.com/golang-jwt/jwt/v5/types.go new file mode 100644 index 0000000000..b2655a9e6d --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/types.go @@ -0,0 +1,149 @@ +package jwt + +import ( + "encoding/json" + "fmt" + "math" + "strconv" + "time" +) + +// TimePrecision sets the precision of times and dates within this library. This +// has an influence on the precision of times when comparing expiry or other +// related time fields. Furthermore, it is also the precision of times when +// serializing. +// +// For backwards compatibility the default precision is set to seconds, so that +// no fractional timestamps are generated. +var TimePrecision = time.Second + +// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, +// especially its MarshalJSON function. +// +// If it is set to true (the default), it will always serialize the type as an +// array of strings, even if it just contains one element, defaulting to the +// behavior of the underlying []string. If it is set to false, it will serialize +// to a single string, if it contains one element. Otherwise, it will serialize +// to an array of strings. +var MarshalSingleStringAsArray = true + +// NumericDate represents a JSON numeric date value, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-2. +type NumericDate struct { + time.Time +} + +// NewNumericDate constructs a new *NumericDate from a standard library time.Time struct. +// It will truncate the timestamp according to the precision specified in TimePrecision. +func NewNumericDate(t time.Time) *NumericDate { + return &NumericDate{t.Truncate(TimePrecision)} +} + +// newNumericDateFromSeconds creates a new *NumericDate out of a float64 representing a +// UNIX epoch with the float fraction representing non-integer seconds. +func newNumericDateFromSeconds(f float64) *NumericDate { + round, frac := math.Modf(f) + return NewNumericDate(time.Unix(int64(round), int64(frac*1e9))) +} + +// MarshalJSON is an implementation of the json.RawMessage interface and serializes the UNIX epoch +// represented in NumericDate to a byte array, using the precision specified in TimePrecision. +func (date NumericDate) MarshalJSON() (b []byte, err error) { + var prec int + if TimePrecision < time.Second { + prec = int(math.Log10(float64(time.Second) / float64(TimePrecision))) + } + truncatedDate := date.Truncate(TimePrecision) + + // For very large timestamps, UnixNano would overflow an int64, but this + // function requires nanosecond level precision, so we have to use the + // following technique to get round the issue: + // + // 1. Take the normal unix timestamp to form the whole number part of the + // output, + // 2. Take the result of the Nanosecond function, which returns the offset + // within the second of the particular unix time instance, to form the + // decimal part of the output + // 3. Concatenate them to produce the final result + seconds := strconv.FormatInt(truncatedDate.Unix(), 10) + nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64) + + output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...) + + return output, nil +} + +// UnmarshalJSON is an implementation of the json.RawMessage interface and +// deserializes a [NumericDate] from a JSON representation, i.e. a +// [json.Number]. This number represents an UNIX epoch with either integer or +// non-integer seconds. +func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { + var ( + number json.Number + f float64 + ) + + if err = json.Unmarshal(b, &number); err != nil { + return fmt.Errorf("could not parse NumericData: %w", err) + } + + if f, err = number.Float64(); err != nil { + return fmt.Errorf("could not convert json number value to float: %w", err) + } + + n := newNumericDateFromSeconds(f) + *date = *n + + return nil +} + +// ClaimStrings is basically just a slice of strings, but it can be either +// serialized from a string array or just a string. This type is necessary, +// since the "aud" claim can either be a single string or an array. +type ClaimStrings []string + +func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { + var value interface{} + + if err = json.Unmarshal(data, &value); err != nil { + return err + } + + var aud []string + + switch v := value.(type) { + case string: + aud = append(aud, v) + case []string: + aud = ClaimStrings(v) + case []interface{}: + for _, vv := range v { + vs, ok := vv.(string) + if !ok { + return ErrInvalidType + } + aud = append(aud, vs) + } + case nil: + return nil + default: + return ErrInvalidType + } + + *s = aud + + return +} + +func (s ClaimStrings) MarshalJSON() (b []byte, err error) { + // This handles a special case in the JWT RFC. If the string array, e.g. + // used by the "aud" field, only contains one element, it MAY be serialized + // as a single string. This may or may not be desired based on the ecosystem + // of other JWT library used, so we make it configurable by the variable + // MarshalSingleStringAsArray. + if len(s) == 1 && !MarshalSingleStringAsArray { + return json.Marshal(s[0]) + } + + return json.Marshal([]string(s)) +} diff --git a/backend/vendor/github.com/golang-jwt/jwt/v5/validator.go b/backend/vendor/github.com/golang-jwt/jwt/v5/validator.go new file mode 100644 index 0000000000..008ecd8712 --- /dev/null +++ b/backend/vendor/github.com/golang-jwt/jwt/v5/validator.go @@ -0,0 +1,316 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// ClaimsValidator is an interface that can be implemented by custom claims who +// wish to execute any additional claims validation based on +// application-specific logic. The Validate function is then executed in +// addition to the regular claims validation and any error returned is appended +// to the final validation result. +// +// type MyCustomClaims struct { +// Foo string `json:"foo"` +// jwt.RegisteredClaims +// } +// +// func (m MyCustomClaims) Validate() error { +// if m.Foo != "bar" { +// return errors.New("must be foobar") +// } +// return nil +// } +type ClaimsValidator interface { + Claims + Validate() error +} + +// Validator is the core of the new Validation API. It is automatically used by +// a [Parser] during parsing and can be modified with various parser options. +// +// The [NewValidator] function should be used to create an instance of this +// struct. +type Validator struct { + // leeway is an optional leeway that can be provided to account for clock skew. + leeway time.Duration + + // timeFunc is used to supply the current time that is needed for + // validation. If unspecified, this defaults to time.Now. + timeFunc func() time.Time + + // requireExp specifies whether the exp claim is required + requireExp bool + + // verifyIat specifies whether the iat (Issued At) claim will be verified. + // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this + // only specifies the age of the token, but no validation check is + // necessary. However, if wanted, it can be checked if the iat is + // unrealistic, i.e., in the future. + verifyIat bool + + // expectedAud contains the audience this token expects. Supplying an empty + // string will disable aud checking. + expectedAud string + + // expectedIss contains the issuer this token expects. Supplying an empty + // string will disable iss checking. + expectedIss string + + // expectedSub contains the subject this token expects. Supplying an empty + // string will disable sub checking. + expectedSub string +} + +// NewValidator can be used to create a stand-alone validator with the supplied +// options. This validator can then be used to validate already parsed claims. +// +// Note: Under normal circumstances, explicitly creating a validator is not +// needed and can potentially be dangerous; instead functions of the [Parser] +// class should be used. +// +// The [Validator] is only checking the *validity* of the claims, such as its +// expiration time, but it does NOT perform *signature verification* of the +// token. +func NewValidator(opts ...ParserOption) *Validator { + p := NewParser(opts...) + return p.validator +} + +// Validate validates the given claims. It will also perform any custom +// validation if claims implements the [ClaimsValidator] interface. +// +// Note: It will NOT perform any *signature verification* on the token that +// contains the claims and expects that the [Claim] was already successfully +// verified. +func (v *Validator) Validate(claims Claims) error { + var ( + now time.Time + errs []error = make([]error, 0, 6) + err error + ) + + // Check, if we have a time func + if v.timeFunc != nil { + now = v.timeFunc() + } else { + now = time.Now() + } + + // We always need to check the expiration time, but usage of the claim + // itself is OPTIONAL by default. requireExp overrides this behavior + // and makes the exp claim mandatory. + if err = v.verifyExpiresAt(claims, now, v.requireExp); err != nil { + errs = append(errs, err) + } + + // We always need to check not-before, but usage of the claim itself is + // OPTIONAL. + if err = v.verifyNotBefore(claims, now, false); err != nil { + errs = append(errs, err) + } + + // Check issued-at if the option is enabled + if v.verifyIat { + if err = v.verifyIssuedAt(claims, now, false); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected audience, we also require the audience claim + if v.expectedAud != "" { + if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected issuer, we also require the issuer claim + if v.expectedIss != "" { + if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected subject, we also require the subject claim + if v.expectedSub != "" { + if err = v.verifySubject(claims, v.expectedSub, true); err != nil { + errs = append(errs, err) + } + } + + // Finally, we want to give the claim itself some possibility to do some + // additional custom validation based on a custom Validate function. + cvt, ok := claims.(ClaimsValidator) + if ok { + if err := cvt.Validate(); err != nil { + errs = append(errs, err) + } + } + + if len(errs) == 0 { + return nil + } + + return joinErrors(errs...) +} + +// verifyExpiresAt compares the exp claim in claims against cmp. This function +// will succeed if cmp < exp. Additional leeway is taken into account. +// +// If exp is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { + exp, err := claims.GetExpirationTime() + if err != nil { + return err + } + + if exp == nil { + return errorIfRequired(required, "exp") + } + + return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) +} + +// verifyIssuedAt compares the iat claim in claims against cmp. This function +// will succeed if cmp >= iat. Additional leeway is taken into account. +// +// If iat is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { + iat, err := claims.GetIssuedAt() + if err != nil { + return err + } + + if iat == nil { + return errorIfRequired(required, "iat") + } + + return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) +} + +// verifyNotBefore compares the nbf claim in claims against cmp. This function +// will return true if cmp >= nbf. Additional leeway is taken into account. +// +// If nbf is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { + nbf, err := claims.GetNotBefore() + if err != nil { + return err + } + + if nbf == nil { + return errorIfRequired(required, "nbf") + } + + return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) +} + +// verifyAudience compares the aud claim against cmp. +// +// If aud is not set or an empty list, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyAudience(claims Claims, cmp string, required bool) error { + aud, err := claims.GetAudience() + if err != nil { + return err + } + + if len(aud) == 0 { + return errorIfRequired(required, "aud") + } + + // use a var here to keep constant time compare when looping over a number of claims + result := false + + var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } + + // case where "" is sent in one or many aud claims + if stringClaims == "" { + return errorIfRequired(required, "aud") + } + + return errorIfFalse(result, ErrTokenInvalidAudience) +} + +// verifyIssuer compares the iss claim in claims against cmp. +// +// If iss is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifyIssuer(claims Claims, cmp string, required bool) error { + iss, err := claims.GetIssuer() + if err != nil { + return err + } + + if iss == "" { + return errorIfRequired(required, "iss") + } + + return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) +} + +// verifySubject compares the sub claim against cmp. +// +// If sub is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *Validator) verifySubject(claims Claims, cmp string, required bool) error { + sub, err := claims.GetSubject() + if err != nil { + return err + } + + if sub == "" { + return errorIfRequired(required, "sub") + } + + return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) +} + +// errorIfFalse returns the error specified in err, if the value is true. +// Otherwise, nil is returned. +func errorIfFalse(value bool, err error) error { + if value { + return nil + } else { + return err + } +} + +// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is +// true. Otherwise, nil is returned. +func errorIfRequired(required bool, claim string) error { + if required { + return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) + } else { + return nil + } +} diff --git a/backend/vendor/modules.txt b/backend/vendor/modules.txt index 94b4750f5a..93f581edac 100644 --- a/backend/vendor/modules.txt +++ b/backend/vendor/modules.txt @@ -65,15 +65,15 @@ github.com/go-chi/render github.com/go-oauth2/oauth2/v4 github.com/go-oauth2/oauth2/v4/errors github.com/go-oauth2/oauth2/v4/server -# github.com/go-pkgz/auth v1.24.3-0.20241007090635-78537e6f812d +# github.com/go-pkgz/auth/v2 v2.0.0-20241208183119-88b3a842be9f ## explicit; go 1.21 -github.com/go-pkgz/auth -github.com/go-pkgz/auth/avatar -github.com/go-pkgz/auth/logger -github.com/go-pkgz/auth/middleware -github.com/go-pkgz/auth/provider -github.com/go-pkgz/auth/provider/sender -github.com/go-pkgz/auth/token +github.com/go-pkgz/auth/v2 +github.com/go-pkgz/auth/v2/avatar +github.com/go-pkgz/auth/v2/logger +github.com/go-pkgz/auth/v2/middleware +github.com/go-pkgz/auth/v2/provider +github.com/go-pkgz/auth/v2/provider/sender +github.com/go-pkgz/auth/v2/token # github.com/go-pkgz/email v0.5.0 ## explicit; go 1.19 github.com/go-pkgz/email @@ -105,9 +105,9 @@ github.com/go-pkgz/rest/realip # github.com/go-pkgz/syncs v1.3.2 ## explicit; go 1.20 github.com/go-pkgz/syncs -# github.com/golang-jwt/jwt v3.2.2+incompatible -## explicit -github.com/golang-jwt/jwt +# github.com/golang-jwt/jwt/v5 v5.2.1 +## explicit; go 1.18 +github.com/golang-jwt/jwt/v5 # github.com/golang/snappy v0.0.4 ## explicit github.com/golang/snappy From f473105c52856c47662a4125670bb65796138b43 Mon Sep 17 00:00:00 2001 From: Dmitry Verkhoturov Date: Mon, 9 Dec 2024 01:33:41 +0000 Subject: [PATCH 4/5] add tests for jwt5 multiple auds and improve existing tests --- backend/app/cmd/server_test.go | 45 +++++++++++++++++++++++++++--- backend/app/rest/api/admin_test.go | 6 ++-- 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/backend/app/cmd/server_test.go b/backend/app/cmd/server_test.go index bc13ba9e83..176ba5837e 100644 --- a/backend/app/cmd/server_test.go +++ b/backend/app/cmd/server_test.go @@ -637,10 +637,10 @@ func TestServerAuthHooks(t *testing.T) { require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusCreated, resp.StatusCode, "non-blocked user able to post") - // add comment with no-aud claim - claimsNoAud := claims - claimsNoAud.Audience = jwt.ClaimStrings{""} - tkNoAud, err := tkService.Token(claimsNoAud) + // try to add comment with no-aud claim + badClaimsNoAud := claims + badClaimsNoAud.Audience = jwt.ClaimStrings{""} + tkNoAud, err := tkService.Token(badClaimsNoAud) require.NoError(t, err) t.Logf("no-aud claims: %s", tkNoAud) req, err = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/api/v1/comment", port), @@ -655,6 +655,43 @@ func TestServerAuthHooks(t *testing.T) { require.NoError(t, resp.Body.Close()) assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user without aud claim rejected, \n"+tkNoAud+"\n"+string(body)) + // try to add comment with multiple auds + badClaimsMultipleAud := claims + badClaimsMultipleAud.Audience = jwt.ClaimStrings{"remark", "second_aud"} + tkMultipleAuds, err := tkService.Token(badClaimsMultipleAud) + require.NoError(t, err) + t.Logf("multiple aud claims: %s", tkMultipleAuds) + req, err = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/api/v1/comment", port), + strings.NewReader(`{"text": "test 123", "locator":{"url": "https://radio-t.com/p/2018/12/29/podcast-631/", + "site": "remark"}}`)) + require.NoError(t, err) + req.Header.Set("X-JWT", tkMultipleAuds) + resp, err = client.Do(req) + require.NoError(t, err) + body, err = io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user with multiple auds claim rejected, \n"+tkMultipleAuds+"\n"+string(body)) + + // try to add comment without user set + badClaimsNoUser := claims + badClaimsNoUser.Audience = jwt.ClaimStrings{"remark"} + badClaimsNoUser.User = nil + tkNoUser, err := tkService.Token(badClaimsNoUser) + require.NoError(t, err) + t.Logf("no user claims: %s", tkNoUser) + req, err = http.NewRequest("POST", fmt.Sprintf("http://localhost:%d/api/v1/comment", port), + strings.NewReader(`{"text": "test 123", "locator":{"url": "https://radio-t.com/p/2018/12/29/podcast-631/", + "site": "remark"}}`)) + require.NoError(t, err) + req.Header.Set("X-JWT", tkNoUser) + resp, err = client.Do(req) + require.NoError(t, err) + body, err = io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode, "user without user information rejected, \n"+tkNoUser+"\n"+string(body)) + // block user github_dev as admin req, err = http.NewRequest(http.MethodPut, fmt.Sprintf("http://localhost:%d/api/v1/admin/user/github_dev?site=remark&block=1&ttl=10d", port), http.NoBody) diff --git a/backend/app/rest/api/admin_test.go b/backend/app/rest/api/admin_test.go index ecbe33dd94..b13dc7b001 100644 --- a/backend/app/rest/api/admin_test.go +++ b/backend/app/rest/api/admin_test.go @@ -835,7 +835,7 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) { // try with wrong audience badClaimsMultipleAudience := claims - badClaimsMultipleAudience.StandardClaims.Audience = "something else" + badClaimsMultipleAudience.RegisteredClaims.Audience = jwt.ClaimStrings{"remark42", "something else"} tkn, err = srv.Authenticator.TokenService().Token(badClaimsMultipleAudience) assert.NoError(t, err) req, err = http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/admin/deleteme?token=%s", ts.URL, tkn), http.NoBody) @@ -847,8 +847,8 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) { b, err = io.ReadAll(resp.Body) assert.NoError(t, err) assert.NoError(t, resp.Body.Close()) - assert.Contains(t, string(b), `site \"something else\" not found`) - badClaimsMultipleAudience.StandardClaims.Audience = "remark42" + assert.Contains(t, string(b), "can't process token, aud is not a single element") + badClaimsMultipleAudience.RegisteredClaims.Audience = jwt.ClaimStrings{"remark42"} } func TestAdmin_GetUserInfo(t *testing.T) { From e61a46efffc57a0c3d278cc131acb68e6f063760 Mon Sep 17 00:00:00 2001 From: Dmitry Verkhoturov Date: Tue, 10 Dec 2024 00:39:21 +0000 Subject: [PATCH 5/5] Improve error message for checking claims.Audience --- backend/app/cmd/server.go | 1 + backend/app/rest/api/admin.go | 3 ++- backend/app/rest/api/admin_test.go | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/backend/app/cmd/server.go b/backend/app/cmd/server.go index 42c9b3f38b..07dd2c3b28 100644 --- a/backend/app/cmd/server.go +++ b/backend/app/cmd/server.go @@ -1215,6 +1215,7 @@ func (s *ServerCommand) getAuthenticator(ds *service.DataStore, avas avatar.Stor if c.User == nil { return c } + // Audience is a slice but we set it to a single element, and situation when there is no audience or there are more than one is unexpected if len(c.Audience) != 1 { return c } diff --git a/backend/app/rest/api/admin.go b/backend/app/rest/api/admin.go index 34ab993395..9b6809a54f 100644 --- a/backend/app/rest/api/admin.go +++ b/backend/app/rest/api/admin.go @@ -107,8 +107,9 @@ func (a *admin) deleteMeRequestCtrl(w http.ResponseWriter, r *http.Request) { return } + // Audience is a slice but we set it to a single element, and situation when there is no audience or there are more than one is unexpected if len(claims.Audience) != 1 { - rest.SendErrorJSON(w, r, http.StatusBadRequest, fmt.Errorf("bad request"), "can't process token, aud is not a single element", rest.ErrActionRejected) + rest.SendErrorJSON(w, r, http.StatusBadRequest, fmt.Errorf("bad request"), "can't process token, claims.Audience expected to be a single element but it's not", rest.ErrActionRejected) return } diff --git a/backend/app/rest/api/admin_test.go b/backend/app/rest/api/admin_test.go index b13dc7b001..6afac8ccce 100644 --- a/backend/app/rest/api/admin_test.go +++ b/backend/app/rest/api/admin_test.go @@ -847,7 +847,7 @@ func TestAdmin_DeleteMeRequestFailed(t *testing.T) { b, err = io.ReadAll(resp.Body) assert.NoError(t, err) assert.NoError(t, resp.Body.Close()) - assert.Contains(t, string(b), "can't process token, aud is not a single element") + assert.Contains(t, string(b), "can't process token, claims.Audience expected to be a single element but it's not") badClaimsMultipleAudience.RegisteredClaims.Audience = jwt.ClaimStrings{"remark42"} }