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 cache architecture #82

Merged
merged 5 commits into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ See [Godoc](https://pkg.go.dev/github.com/dwango/yashiro).
go get github.com/dwango/yashiro
```

### Authorization

AWS

```json
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:GetParameter",
"secretsmanager:GetSecretValue"
],
"Resource": ["*"],
},
]
}
```

## CLI Tool

### Installation
Expand Down
3 changes: 3 additions & 0 deletions alias.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,7 @@ type Config = config.Config
var (
// NewEngine returns a new Engine.
NewEngine = engine.New

// IgnoreNotFound is an option to ignore missing external store values.
IgnoreNotFound = engine.IgnoreNotFound
)
10 changes: 9 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"log"
"os"
"time"

awsconfig "github.com/aws/aws-sdk-go-v2/config"
"github.com/dwango/yashiro"
Expand All @@ -36,6 +37,13 @@ func Example() {

refName := "example"
cfg := &config.Config{
Global: config.GlobalConfig{
EnableCache: true, // enable cache
Cache: config.CacheConfig{
Type: config.CacheTypeMemory,
ExpireDuration: config.Duration(30 * time.Minute),
},
},
Aws: &config.AwsConfig{
ParameterStoreValues: []config.AwsParameterStoreValueConfig{
{
Expand All @@ -50,7 +58,7 @@ func Example() {
},
}

eng, err := yashiro.NewEngine(cfg)
eng, err := yashiro.NewEngine(cfg, yashiro.IgnoreNotFound(true)) // ignore not found value
if err != nil {
log.Fatalf("failed to create engine: %s", err)
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/aws/aws-sdk-go-v2/config v1.27.16
github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.29.1
github.com/aws/aws-sdk-go-v2/service/ssm v1.50.4
github.com/aws/aws-sdk-go-v2/service/sts v1.28.10
github.com/spf13/cobra v1.8.0
golang.org/x/crypto v0.3.0
sigs.k8s.io/yaml v1.4.0
Expand All @@ -25,7 +26,6 @@ require (
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.9 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.20.9 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.24.3 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.28.10 // indirect
github.com/aws/smithy-go v1.20.2 // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/huandu/xstrings v1.3.3 // indirect
Expand Down
158 changes: 139 additions & 19 deletions internal/client/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,39 +21,53 @@ import (
"errors"
"fmt"

kms "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
kmsTypes "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types"
"github.com/aws/aws-sdk-go-v2/aws"
secs "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
secsTypes "github.com/aws/aws-sdk-go-v2/service/secretsmanager/types"
"github.com/aws/aws-sdk-go-v2/service/ssm"
ssmTypes "github.com/aws/aws-sdk-go-v2/service/ssm/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
"github.com/dwango/yashiro/internal/client/cache"
"github.com/dwango/yashiro/internal/values"
"github.com/dwango/yashiro/pkg/config"
)

type ssmClient interface {
GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error)
}

type kmsClient interface {
GetSecretValue(ctx context.Context, params *kms.GetSecretValueInput, optFns ...func(*kms.Options)) (*kms.GetSecretValueOutput, error)
}

type awsClient struct {
ssmClient ssmClient
kmsClient kmsClient
secsClient secsClient
parameterStoreValue []config.AwsParameterStoreValueConfig
secretsManagerValue []config.ValueConfig
}

func newAwsClient(cfg *config.AwsConfig) (Client, error) {
if cfg.SdkConfig == nil {
func newAwsClient(cfg *config.Config) (Client, error) {
if cfg.Aws.SdkConfig == nil {
return nil, fmt.Errorf("require aws sdk config")
}

var cc cache.Cache
if cfg.Global.EnableCache {
// get AWS account ID
accountID, err := getAwsAccountId(cfg.Aws.SdkConfig)
if err != nil {
return nil, err
}
cc, err = cache.New(cfg.Global.Cache, cache.WithCacheKeys("aws", cfg.Aws.SdkConfig.Region, accountID))
if err != nil {
return nil, err
}
}

return &awsClient{
ssmClient: ssm.NewFromConfig(*cfg.SdkConfig),
kmsClient: kms.NewFromConfig(*cfg.SdkConfig),
parameterStoreValue: cfg.ParameterStoreValues,
secretsManagerValue: cfg.SecretsManagerValues,
ssmClient: &ssmClientWithCache{
client: ssm.NewFromConfig(*cfg.Aws.SdkConfig),
cache: cc,
},
secsClient: &secsClientWithCache{
client: secs.NewFromConfig(*cfg.Aws.SdkConfig),
cache: cc,
},
parameterStoreValue: cfg.Aws.ParameterStoreValues,
secretsManagerValue: cfg.Aws.SecretsManagerValues,
}, nil
}

Expand All @@ -80,12 +94,12 @@ func (c awsClient) GetValues(ctx context.Context, ignoreNotFound bool) (values.V
}

for _, v := range c.secretsManagerValue {
output, err := c.kmsClient.GetSecretValue(ctx, &kms.GetSecretValueInput{
output, err := c.secsClient.GetSecretValue(ctx, &secs.GetSecretValueInput{
SecretId: &v.Name,
})

if err != nil {
var notFoundErr *kmsTypes.ResourceNotFoundException
var notFoundErr *secsTypes.ResourceNotFoundException
if ignoreNotFound && errors.As(err, &notFoundErr) {
continue
}
Expand All @@ -99,3 +113,109 @@ func (c awsClient) GetValues(ctx context.Context, ignoreNotFound bool) (values.V

return values, nil
}

type ssmClient interface {
GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error)
}

type ssmClientWithCache struct {
client ssmClient
cache cache.Cache
}

func (c ssmClientWithCache) GetParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) {
if c.cache == nil {
return c.getParameter(ctx, params, optFns...)
}

key := *params.Name // Name is required, so do not check nil
isSensitive := params.WithDecryption != nil && *params.WithDecryption

// Load from cache.
value, expired, err := c.cache.Load(ctx, key, isSensitive)
if err != nil {
return nil, err
}

// If a cache value is expired or not found, get a value from the external store.
if value == nil || expired {
output, err := c.getParameter(ctx, params, optFns...)
if err != nil {
return nil, err
}

// Create or update cache.
if err := c.cache.Save(ctx, key, output.Parameter.Value, isSensitive); err != nil {
return nil, err
}

return output, nil
}

return &ssm.GetParameterOutput{Parameter: &ssmTypes.Parameter{Value: value}}, nil
}

func (c ssmClientWithCache) getParameter(ctx context.Context, params *ssm.GetParameterInput, optFns ...func(*ssm.Options)) (*ssm.GetParameterOutput, error) {
output, err := c.client.GetParameter(ctx, params, optFns...)
if err != nil {
return nil, err
}
return output, nil
}

type secsClient interface {
GetSecretValue(ctx context.Context, params *secs.GetSecretValueInput, optFns ...func(*secs.Options)) (*secs.GetSecretValueOutput, error)
}

type secsClientWithCache struct {
client secsClient
cache cache.Cache
}

func (c secsClientWithCache) GetSecretValue(ctx context.Context, params *secs.GetSecretValueInput, optFns ...func(*secs.Options)) (*secs.GetSecretValueOutput, error) {
if c.cache == nil {
return c.getSecretValue(ctx, params, optFns...)
}

key := *params.SecretId // SecretId is required, so do not check nil

// Load from cache. Secret is always sensitive.
value, expired, err := c.cache.Load(ctx, key, true)
if err != nil {
return nil, err
}

// If a cache value is expired or not found, get a value from the external store.
if value == nil || expired {
output, err := c.getSecretValue(ctx, params, optFns...)
if err != nil {
return nil, err
}

// Create or update cache.
if err := c.cache.Save(ctx, key, output.SecretString, true); err != nil {
return nil, err
}

return output, nil
}

return &secs.GetSecretValueOutput{SecretString: value}, nil
}

func (c secsClientWithCache) getSecretValue(ctx context.Context, params *secs.GetSecretValueInput, optFns ...func(*secs.Options)) (*secs.GetSecretValueOutput, error) {
output, err := c.client.GetSecretValue(ctx, params, optFns...)
if err != nil {
return nil, err
}
return output, nil
}

func getAwsAccountId(sdkConfig *aws.Config) (string, error) {
stsClient := sts.NewFromConfig(*sdkConfig)
output, err := stsClient.GetCallerIdentity(context.Background(), &sts.GetCallerIdentityInput{})
if err != nil {
return "", err
}
return *output.Account, nil
}
Loading
Loading