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(VER-5669): add SignerProvider to jwt package #3

Merged
merged 1 commit into from
Feb 14, 2024
Merged
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
28 changes: 23 additions & 5 deletions jwt/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package jwt

import (
"context"
"crypto/rsa"
"encoding/json"
"fmt"
"io"
Expand Down Expand Up @@ -48,6 +49,11 @@ type Config struct {
//
PrivateKey []byte

// SignerProvider is a function that is used to create a Signer from the
// PrivateKeyID which is then used to sign JWT payloads. This takes
// precedence over default signer using the PrivateKey.
SignerProvider func(privateKeyID string) (Signer, error)

// PrivateKeyID contains an optional hint indicating which key is being
// used.
PrivateKeyID string
Expand Down Expand Up @@ -101,10 +107,6 @@ type jwtSource struct {
}

func (js jwtSource) Token() (*oauth2.Token, error) {
pk, err := internal.ParseKey(js.conf.PrivateKey)
if err != nil {
return nil, err
}
hc := oauth2.NewClient(js.ctx, nil)
claimSet := &jws.ClaimSet{
Iss: js.conf.Email,
Expand All @@ -126,7 +128,23 @@ func (js jwtSource) Token() (*oauth2.Token, error) {
}
h := *defaultHeader
h.KeyID = js.conf.PrivateKeyID
payload, err := jws.Encode(&h, claimSet, pk)
var err error
vikrampar marked this conversation as resolved.
Show resolved Hide resolved
payload := ""
if js.conf.SignerProvider == nil {
var pk *rsa.PrivateKey
pk, err = internal.ParseKey(js.conf.PrivateKey)
if err != nil {
return nil, err
}
payload, err = jws.Encode(&h, claimSet, pk)
} else {
var signer jws.Signer
signer, err = js.conf.SignerProvider(h.KeyID)
if err != nil {
return nil, err
}
payload, err = jws.EncodeWithSigner(&h, claimSet, signer)
}
if err != nil {
return nil, err
}
Expand Down