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: API Server panics when bearer token with invalid JWT format is passed #421

Merged
merged 1 commit into from
Mar 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
1 change: 1 addition & 0 deletions cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ func determineAuth(ctx context.Context) (context.Context, error) {
ctxzap.AddFields(ctx,
zap.String("grpc.user", "unknown"),
)
return ctx, nil
}

if claims, ok := token.Claims.(jwt.MapClaims); ok {
Expand Down
68 changes: 68 additions & 0 deletions cmd/api/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"bytes"
"context"
"github.com/golang-jwt/jwt/v4"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc/metadata"
"io"
"strings"
"testing"
)

func Test_determineAuth(t *testing.T) {
validToken, _ := jwt.NewWithClaims(jwt.SigningMethodHS256, &jwt.RegisteredClaims{
Subject: "sayan",
Issuer: "redhat",
}).SignedString([]byte("secret"))

invalidToken := "invalid-token-format"

tests := []struct {
name string
md metadata.MD
want string
}{
{
name: "missing token",
md: metadata.MD{},
want: "\"grpc.user\":\"unknown\"",
},
{
name: "invalid token",
md: metadata.Pairs("authorization", "Bearer "+invalidToken),
want: "\"grpc.user\":\"unknown\"",
},
{
name: "valid token",
md: metadata.Pairs("authorization", "Bearer "+validToken),
want: "\"grpc.user\":\"sayan\",\"grpc.issuer\":\"redhat\"",
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var b bytes.Buffer
ctx := contextWithLogger(&b)
_, err := determineAuth(metadata.NewIncomingContext(ctx, tc.md))
l := ctxzap.Extract(ctx)
l.Info(tc.name)
if err != nil {
t.Fatalf("No error expected, but received error: %v", err)
}
if !strings.Contains(b.String(), tc.want) {
t.Fatalf("Log doesn't contain the string: %s", tc.want)
}
})
}
}

func contextWithLogger(w io.Writer) context.Context {
encoder := zapcore.NewJSONEncoder(zap.NewDevelopmentConfig().EncoderConfig)
writer := zapcore.AddSync(w)
logger := zap.New(zapcore.NewCore(encoder, writer, zapcore.DebugLevel))
return ctxzap.ToContext(context.Background(), logger)
}