-
Notifications
You must be signed in to change notification settings - Fork 192
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Load credentials from secrets for GCP KMS
Signed-off-by: Somtochi Onyekwere <[email protected]>
- Loading branch information
1 parent
1535282
commit cabfae0
Showing
14 changed files
with
1,011 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
// This Source Code Form is subject to the terms of the Mozilla Public | ||
// License, v. 2.0. If a copy of the MPL was not distributed with this | ||
// file, You can obtain one at https://mozilla.org/MPL/2.0/. | ||
|
||
package gcpkms | ||
|
||
import ( | ||
"context" | ||
"encoding/base64" | ||
"fmt" | ||
"regexp" | ||
"time" | ||
|
||
kms "cloud.google.com/go/kms/apiv1" | ||
"google.golang.org/api/option" | ||
kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" | ||
"google.golang.org/grpc" | ||
) | ||
|
||
var ( | ||
// gcpkmsTTL is the duration after which a MasterKey requiers rotation. | ||
gcpkmsTTL = time.Hour * 24 * 30 * 6 | ||
) | ||
|
||
// CredentialJSON is the service account keys used for aythentication towards a GCP KMS service. | ||
type CredentialJSON []byte | ||
|
||
// ApplyToMasterKey configures the credentialJSON on the provided key. | ||
func (c CredentialJSON) ApplyToMasterKey(key *MasterKey) { | ||
key.credentialJSON = []byte(c) | ||
} | ||
|
||
// MasterKey is a GCP KMS key used to encrypt and decrypt the SOPS | ||
// data key | ||
// Adapted from https://github.com/mozilla/sops/blob/v3.7.2/gcpkms/keysource.go | ||
// to be able to have fine-grain control over the credentials used to authenticate | ||
// to GCP KMS Service. | ||
type MasterKey struct { | ||
// ResourceID is the resource id used to refer to the gcp kms key. | ||
// It can be retrieved using the `gcloud` command. | ||
ResourceID string | ||
// EncryptedKey is the string returned after encrypting with GCP KMS | ||
EncryptedKey string | ||
CreationDate time.Time | ||
|
||
// credentialJSON are the service account keys used to authenticate | ||
// to Google Cloud | ||
credentialJSON []byte | ||
// custom grpc server that will be used for cloudkms service | ||
// for cloudkms service. This allows for mocking test. | ||
grpcClient *grpc.ClientConn | ||
} | ||
|
||
// MasterKeyFromResourceID creates a new MasterKey with the ResourceID set, | ||
func MasterKeyFromResourceID(resourceID string) *MasterKey { | ||
return &MasterKey{ | ||
ResourceID: resourceID, | ||
CreationDate: time.Now().UTC(), | ||
} | ||
} | ||
|
||
// Encrypt takes a sops data key, encrypts it with GCP KMS | ||
// and stores the result in the EncryptedKey field | ||
func (key *MasterKey) Encrypt(datakey []byte) error { | ||
cloudkmsService, err := key.createKMSService() | ||
if err != nil { | ||
return err | ||
} | ||
defer cloudkmsService.Close() | ||
|
||
req := &kmspb.EncryptRequest{ | ||
Name: key.ResourceID, | ||
Plaintext: datakey, | ||
} | ||
ctx := context.Background() | ||
resp, err := cloudkmsService.Encrypt(ctx, req) | ||
if err != nil { | ||
return fmt.Errorf("failed to encrypt sops data key with GCP KMS: %w", err) | ||
} | ||
key.EncryptedKey = base64.StdEncoding.EncodeToString(resp.Ciphertext) | ||
return nil | ||
} | ||
|
||
// SetEncryptedDataKey sets the encrypted data key for this master key. | ||
func (key *MasterKey) SetEncryptedDataKey(enc []byte) { | ||
key.EncryptedKey = string(enc) | ||
} | ||
|
||
// EncryptedDataKey returns the encrypted data key this master key holds. | ||
func (key *MasterKey) EncryptedDataKey() []byte { | ||
return []byte(key.EncryptedKey) | ||
} | ||
|
||
// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been | ||
// encrypted yet. | ||
func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { | ||
if key.EncryptedKey == "" { | ||
return key.Encrypt(dataKey) | ||
} | ||
return nil | ||
} | ||
|
||
// Decrypt decrypts the EncryptedKey field with GCP KMS and returns | ||
// the result. | ||
func (key *MasterKey) Decrypt() ([]byte, error) { | ||
cloudkmsService, err := key.createKMSService() | ||
if err != nil { | ||
return nil, err | ||
} | ||
defer cloudkmsService.Close() | ||
|
||
decodedCipher, err := base64.StdEncoding.DecodeString(string(key.EncryptedDataKey())) | ||
if err != nil { | ||
return nil, err | ||
} | ||
req := &kmspb.DecryptRequest{ | ||
Name: key.ResourceID, | ||
Ciphertext: decodedCipher, | ||
} | ||
ctx := context.Background() | ||
resp, err := cloudkmsService.Decrypt(ctx, req) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to decrypt sops data key with GCP KMS Key: %w", err) | ||
} | ||
|
||
return resp.Plaintext, nil | ||
} | ||
|
||
// NeedsRotation returns whether the data key needs to be rotated or not. | ||
func (key *MasterKey) NeedsRotation() bool { | ||
return time.Since(key.CreationDate) > (gcpkmsTTL) | ||
} | ||
|
||
// ToString converts the key to a string representation. | ||
func (key *MasterKey) ToString() string { | ||
return key.ResourceID | ||
} | ||
|
||
// ToMap converts the MasterKey to a map for serialization purposes. | ||
func (key MasterKey) ToMap() map[string]interface{} { | ||
out := make(map[string]interface{}) | ||
out["resource_id"] = key.ResourceID | ||
out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) | ||
out["enc"] = key.EncryptedKey | ||
return out | ||
} | ||
|
||
// createCloudKMSService create a GCP KMS client configured with the JSON credentials | ||
// stored in the credentialJSON field. | ||
func (key *MasterKey) createKMSService() (*kms.KeyManagementClient, error) { | ||
re := regexp.MustCompile(`^projects/[^/]+/locations/[^/]+/keyRings/[^/]+/cryptoKeys/[^/]+$`) | ||
matches := re.FindStringSubmatch(key.ResourceID) | ||
if matches == nil { | ||
return nil, fmt.Errorf("no valid resourceId found in %q", key.ResourceID) | ||
} | ||
|
||
ctx := context.Background() | ||
opts := []option.ClientOption{} | ||
|
||
if key.credentialJSON != nil { | ||
opts = append(opts, option.WithCredentialsJSON(key.credentialJSON)) | ||
} | ||
|
||
if key.grpcClient != nil { | ||
opts = append(opts, option.WithGRPCConn(key.grpcClient)) | ||
} | ||
|
||
client, err := kms.NewKeyManagementClient(ctx, opts...) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return client, nil | ||
} |
Oops, something went wrong.