Skip to content

Commit

Permalink
🐛 hashicorp#30: add cache to crypto key request
Browse files Browse the repository at this point in the history
This operation is restricted by GCP quotas to 300 rpm.
  • Loading branch information
yesid-bocanegra committed Aug 23, 2023
1 parent cd5a2cd commit 0032794
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions path_decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@ import (
"context"
"encoding/base64"
"fmt"
"time"

"github.com/hashicorp/errwrap"
"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/logical"
"github.com/patrickmn/go-cache"

kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1"
)

var keysCache = cache.New(24*time.Hour, 10*time.Minute)

func (b *backend) pathDecrypt() *framework.Path {
return &framework.Path{
Pattern: "decrypt/" + framework.GenericNameRegex("key"),
Expand Down Expand Up @@ -119,11 +123,19 @@ func (b *backend) pathDecryptWrite(ctx context.Context, req *logical.Request, d

// Lookup the key so we can determine the type of decryption (symmetric or
// asymmetric).
ck, err := kmsClient.GetCryptoKey(ctx, &kmspb.GetCryptoKeyRequest{
Name: k.CryptoKeyID,
})
if err != nil {
return nil, errwrap.Wrapf("failed to get underlying crypto key: {{err}}", err)
var ck *kmspb.CryptoKey
cachedCk, found := keysCache.Get(k.CryptoKeyID)
if !found {
fetchedCk, err := kmsClient.GetCryptoKey(ctx, &kmspb.GetCryptoKeyRequest{
Name: k.CryptoKeyID,
})
if err != nil {
return nil, errwrap.Wrapf("failed to get underlying crypto key: {{err}}", err)
}
_ = keysCache.Add(k.CryptoKeyID, fetchedCk, cache.DefaultExpiration)
ck = fetchedCk
} else {
ck = cachedCk.(*kmspb.CryptoKey)
}

var plaintext string
Expand Down

0 comments on commit 0032794

Please sign in to comment.