@@ -12,6 +12,7 @@ import (
1212 kms "cloud.google.com/go/kms/apiv1"
1313 "cloud.google.com/go/kms/apiv1/kmspb"
1414 "github.com/sirupsen/logrus"
15+ "golang.org/x/oauth2"
1516 "google.golang.org/api/option"
1617 "google.golang.org/grpc"
1718
@@ -50,6 +51,11 @@ type MasterKey struct {
5051 // for NeedsRotation.
5152 CreationDate time.Time
5253
54+ // tokenSource contains the oauth2.TokenSource used by the GCP client.
55+ // It can be injected by a (local) keyservice.KeyServiceServer using
56+ // TokenSource.ApplyToMasterKey.
57+ // If nil, the remaining authentication methods are attempted.
58+ tokenSource oauth2.TokenSource
5359 // credentialJSON is the Service Account credentials JSON used for
5460 // authenticating towards the GCP KMS service.
5561 credentialJSON []byte
@@ -82,6 +88,22 @@ func MasterKeysFromResourceIDString(resourceID string) []*MasterKey {
8288 return keys
8389}
8490
91+ // TokenSource is an oauth2.TokenSource used for authenticating towards the
92+ // GCP KMS service.
93+ type TokenSource struct {
94+ source oauth2.TokenSource
95+ }
96+
97+ // NewTokenSource creates a new TokenSource from the provided oauth2.TokenSource.
98+ func NewTokenSource (source oauth2.TokenSource ) TokenSource {
99+ return TokenSource {source : source }
100+ }
101+
102+ // ApplyToMasterKey configures the TokenSource on the provided key.
103+ func (t TokenSource ) ApplyToMasterKey (key * MasterKey ) {
104+ key .tokenSource = t .source
105+ }
106+
85107// CredentialJSON is the Service Account credentials JSON used for authenticating
86108// towards the GCP KMS service.
87109type CredentialJSON []byte
@@ -203,8 +225,8 @@ func (key *MasterKey) TypeToIdentifier() string {
203225 return KeyTypeIdentifier
204226}
205227
206- // newKMSClient returns a GCP KMS client configured with the credentialJSON
207- // and/or grpcConn, falling back to environmental defaults.
228+ // newKMSClient returns a GCP KMS client configured with the tokenSource
229+ // or credentialJSON, and/or grpcConn, falling back to environmental defaults.
208230// It returns an error if the ResourceID is invalid, or if the setup of the
209231// client fails.
210232func (key * MasterKey ) newKMSClient () (* kms.KeyManagementClient , error ) {
@@ -216,6 +238,8 @@ func (key *MasterKey) newKMSClient() (*kms.KeyManagementClient, error) {
216238
217239 var opts []option.ClientOption
218240 switch {
241+ case key .tokenSource != nil :
242+ opts = append (opts , option .WithTokenSource (key .tokenSource ))
219243 case key .credentialJSON != nil :
220244 opts = append (opts , option .WithCredentialsJSON (key .credentialJSON ))
221245 default :
0 commit comments