From fb68309520d41a8cec4ca3c2ee800fe55e315909 Mon Sep 17 00:00:00 2001 From: Sanskarzz Date: Fri, 29 Mar 2024 12:31:50 +0530 Subject: [PATCH] added test case for jwt_decode(token,secert).payload to return the payload map Signed-off-by: Sanskarzz --- pkg/scratch/scratch.go | 20 ++++++++++++++++++++ pkg/scratch/scratch_test.go | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/pkg/scratch/scratch.go b/pkg/scratch/scratch.go index b131204..b50f2de 100644 --- a/pkg/scratch/scratch.go +++ b/pkg/scratch/scratch.go @@ -52,3 +52,23 @@ func GetFormJWTToken(arguments []any) (map[string]interface{}, error) { } return out.(map[string]interface{}), nil } + +func GetFormJWTTokenPayload(arguments []any) (map[string]interface{}, error) { + vm := interpreter.NewInterpreter(nil, nil) + parser := parsing.NewParser() + + // Construct JMESPath expression with arguments + arg1 := fmt.Sprintf("'%s'", arguments[0]) + arg2 := fmt.Sprintf("'%s'", arguments[1]) + statement := fmt.Sprintf("jwt_decode(%s, %s).payload", arg1, arg2) + + compiled, err := parser.Parse(statement) + if err != nil { + return nil, fmt.Errorf("error on compiling , %w", err) + } + out, err := vm.Execute(compiled, arguments, interpreter.WithFunctionCaller(Caller)) + if err != nil { + return nil, fmt.Errorf("error on execute , %w", err) + } + return out.(map[string]interface{}), nil +} diff --git a/pkg/scratch/scratch_test.go b/pkg/scratch/scratch_test.go index 6160cdc..f242c50 100644 --- a/pkg/scratch/scratch_test.go +++ b/pkg/scratch/scratch_test.go @@ -75,3 +75,38 @@ func TestGetFormJWTToken(t *testing.T) { }) } } + +func TestGetFormJWTTokenPayload(t *testing.T) { + type args struct { + arguments []any + } + tests := []struct { + name string + args args + want map[string]interface{} + wantErr bool + }{ + { + args: args{[]any{"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjIyNDEwODE1MzksIm5iZiI6MTUxNDg1MTEzOSwicm9sZSI6Imd1ZXN0Iiwic3ViIjoiWVd4cFkyVT0ifQ.ja1bgvIt47393ba_WbSBm35NrUhdxM4mOVQN8iXz8lk", "c2VjcmV0"}}, + want: map[string]interface{}{ + "exp": 2.241081539e+09, + "nbf": 1.514851139e+09, + "role": "guest", + "sub": "YWxpY2U=", + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := GetFormJWTTokenPayload(tt.args.arguments) + if (err != nil) != tt.wantErr { + t.Errorf("GetFormJWTTokenPayload() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetFormJWTTokenPayload() = %v, want %v", got, tt.want) + } + }) + } +}