Skip to content

Commit

Permalink
support gcp credentials as env var
Browse files Browse the repository at this point in the history
  • Loading branch information
joshkaplinsky committed Oct 27, 2021
1 parent 6130ffe commit ea8b3bb
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions gcpkms/keysource.go
Expand Up @@ -3,16 +3,17 @@ package gcpkms //import "go.mozilla.org/sops/v3/gcpkms"
import (
"encoding/base64"
"fmt"
"google.golang.org/api/option"
"io/ioutil"
"os"
"regexp"
"strings"
"time"

"go.mozilla.org/sops/v3/logging"

"golang.org/x/net/context"
"golang.org/x/oauth2/google"

"github.com/sirupsen/logrus"
"golang.org/x/net/context"
cloudkms "google.golang.org/api/cloudkms/v1"
)

Expand Down Expand Up @@ -131,12 +132,13 @@ func (key MasterKey) createCloudKMSService() (*cloudkms.Service, error) {
}

ctx := context.Background()
client, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)

creds, err := getDefaultApplicationCredentials()
if err != nil {
return nil, err
}

cloudkmsService, err := cloudkms.New(client)
cloudkmsService, err := cloudkms.NewService(ctx, option.WithCredentialsJSON(creds))
if err != nil {
return nil, err
}
Expand All @@ -151,3 +153,19 @@ func (key MasterKey) ToMap() map[string]interface{} {
out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339)
return out
}

// getDefaultApplicationCredentials allows for passing GCP Service Account
// Credentials as either a path to a file, or directly as an environment variable
// in JSON format.
func getDefaultApplicationCredentials() (token []byte, err error) {
var defaultCredentials = os.Getenv("GOOGLE_APPLICATION_CREDENTIALS")

if _, err := os.Stat(defaultCredentials); err == nil {
if token, err = ioutil.ReadFile(defaultCredentials); err != nil {
return nil, err
}
} else {
token = []byte(defaultCredentials)
}
return
}

0 comments on commit ea8b3bb

Please sign in to comment.