diff --git a/changelog/unreleased/jwt-token-hash.md b/changelog/unreleased/jwt-token-hash.md index b0bba6379e0..be5a1d3c9ab 100644 --- a/changelog/unreleased/jwt-token-hash.md +++ b/changelog/unreleased/jwt-token-hash.md @@ -4,7 +4,7 @@ We encode the complete CS3APIs user object along with the scopes the user has access to in the JWT token. In case the list of scopes is long or the user belongs to a lot of groups, the token size got pretty big previously, and for use-cases where we needed to pass it as a URI parameter, led to server limits -on the size of the URI being hit. Now we cache the token return its hash, which -makes the size of the token constant. +on the size of the URI being hit. Now we cache the token and return its hash, +which makes its size constant. https://github.com/cs3org/reva/pull/1935 diff --git a/pkg/token/manager/jwt/jwt.go b/pkg/token/manager/jwt/jwt.go index 0a264666c71..8593f5049a6 100644 --- a/pkg/token/manager/jwt/jwt.go +++ b/pkg/token/manager/jwt/jwt.go @@ -20,7 +20,8 @@ package jwt import ( "context" - "crypto/sha1" + "crypto/sha256" + "encoding/hex" "time" "github.com/bluele/gcache" @@ -37,8 +38,11 @@ import ( const defaultExpiration int64 = 86400 // 1 day +var tokenCache gcache.Cache + func init() { registry.Register("jwt", New) + tokenCache = gcache.New(1000000).LFU().Build() } type config struct { @@ -47,8 +51,7 @@ type config struct { } type manager struct { - conf *config - tokenCache gcache.Cache + conf *config } // claims are custom claims for the JWT token. @@ -84,11 +87,7 @@ func New(value map[string]interface{}) (token.Manager, error) { return nil, errors.New("jwt: secret for signing payloads is not defined in config") } - m := &manager{ - conf: c, - tokenCache: gcache.New(1000000).LFU().Build(), - } - return m, nil + return &manager{conf: c}, nil } func (m *manager) MintToken(ctx context.Context, u *user.User, scope map[string]*auth.Scope) (string, error) { @@ -136,15 +135,17 @@ func (m *manager) DismantleToken(ctx context.Context, tkn string) (*user.User, m } func (m *manager) cacheAndReturnHash(token string) (string, error) { - h := sha1.New() - h.Write([]byte(token)) - hash := string(h.Sum(nil)) - err := m.tokenCache.SetWithExpire(hash, token, time.Second*time.Duration(m.conf.Expires)) + h := sha256.New() + if _, err := h.Write([]byte(token)); err != nil { + return "", err + } + hash := hex.EncodeToString(h.Sum(nil)) + err := tokenCache.SetWithExpire(hash, token, time.Second*time.Duration(m.conf.Expires)) return hash, err } func (m *manager) getCachedToken(hashedToken string) (string, error) { - if tknIf, err := m.tokenCache.Get(hashedToken); err == nil { + if tknIf, err := tokenCache.Get(hashedToken); err == nil { return tknIf.(string), nil } return "", errtypes.InvalidCredentials("invalid token")