Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add caching to Jsonnet snippet during session JWT tokenization #3699

Merged
merged 2 commits into from
Jan 18, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions session/tokenizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ package session

import (
"context"
"crypto/sha256"
"encoding/json"
"time"

"go.opentelemetry.io/otel/trace"

"github.com/ory/kratos/x/events"

"github.com/dgraph-io/ristretto"
"github.com/gofrs/uuid"
"github.com/golang-jwt/jwt/v5"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"go.opentelemetry.io/otel/trace"

"github.com/ory/herodot"
"github.com/ory/kratos/driver/config"
"github.com/ory/kratos/x"
"github.com/ory/kratos/x/events"
"github.com/ory/x/fetcher"
"github.com/ory/x/jsonnetsecure"
"github.com/ory/x/jwksx"
Expand Down Expand Up @@ -51,6 +51,16 @@ func (s *Tokenizer) SetNowFunc(t func() time.Time) {
s.nowFunc = t
}

var cache, _ = ristretto.NewCache(&ristretto.Config{
NumCounters: 100000000,
MaxCost: 10000000,
BufferItems: 64,
IgnoreInternalCost: true,
Cost: func(value interface{}) int64 {
return 1
},
})

func (s *Tokenizer) TokenizeSession(ctx context.Context, template string, session *Session) (err error) {
ctx, span := s.r.Tracer(ctx).Tracer().Start(ctx, "sessions.ManagerHTTP.TokenizeSession")
defer otelx.End(span, &err)
Expand Down Expand Up @@ -100,9 +110,17 @@ func (s *Tokenizer) TokenizeSession(ctx context.Context, template string, sessio
}

if mapper := tpl.ClaimsMapperURL; len(mapper) > 0 {
jn, err := fetch.FetchContext(ctx, mapper)
if err != nil {
return err
var jsonnet string
cacheKey := sha256.Sum256([]byte(mapper))
if result, found := cache.Get(cacheKey[:]); found {
jsonnet = result.(string)
} else {
jn, err := fetch.FetchContext(ctx, mapper)
if err != nil {
return err
}
jsonnet = jn.String()
cache.SetWithTTL(cacheKey[:], jsonnet, 1, time.Hour)
}

sessionRaw, err := json.Marshal(session)
Expand All @@ -118,7 +136,7 @@ func (s *Tokenizer) TokenizeSession(ctx context.Context, template string, sessio
vm.ExtCode("session", string(sessionRaw))
vm.ExtCode("claims", string(claimsRaw))

evaluated, err := vm.EvaluateAnonymousSnippet(tpl.ClaimsMapperURL, jn.String())
evaluated, err := vm.EvaluateAnonymousSnippet(tpl.ClaimsMapperURL, jsonnet)
if err != nil {
return errors.WithStack(herodot.ErrBadRequest.WithWrap(err).WithDebug(err.Error()).WithReasonf("Unable to execute tokenizer JsonNet."))
}
Expand Down
Loading