Skip to content

Commit

Permalink
Add helper methods to internal package.
Browse files Browse the repository at this point in the history
- methods ,such as creating AWS config.
- methods ,such as wrapping error.
  • Loading branch information
gjbae1212 committed Aug 30, 2021
1 parent 011fbb3 commit 8ce526a
Show file tree
Hide file tree
Showing 6 changed files with 229 additions and 0 deletions.
65 changes: 65 additions & 0 deletions internal/aws.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package internal

import (
"context"

"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
"github.com/aws/aws-sdk-go-v2/service/sts"
)

// NewConfig creates a config for accessing AWS with passing credential parameters.
func NewConfig(ctx context.Context, key, secret, session, region, roleArn string) (aws.Config, error) {
var (
opts []func(*config.LoadOptions) error
cfg aws.Config
err error
)
if ctx == nil {
return aws.Config{}, WrapError(ErrInvalidParams)
}

if region != "" {
opts = append(opts, config.WithRegion(region))
}

// if parameters for credentials doesn't pass it.
if key == "" || secret == "" {
cfg, err = config.LoadDefaultConfig(ctx, opts...)
} else {
opts = append(opts, config.WithCredentialsProvider(
credentials.NewStaticCredentialsProvider(key, secret, session)))
cfg, err = config.LoadDefaultConfig(ctx, opts...)
}
if err != nil {
return aws.Config{}, WrapError(err)
}

// https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/credentials/stscreds
if roleArn != "" {
sts := sts.NewFromConfig(cfg)
cfg.Credentials = aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(sts, roleArn))
}

return cfg, nil
}

// NewSharedConfig creates a config for accessing AWS that is based on shared files, such as credentials file.
func NewSharedConfig(ctx context.Context, profile string, sharedConfigFiles, sharedCredentialsFiles []string) (aws.Config, error) {
if ctx == nil {
return aws.Config{}, WrapError(ErrInvalidParams)
}

cfg, err := config.LoadDefaultConfig(ctx,
config.WithSharedConfigProfile(profile),
config.WithSharedConfigFiles(sharedConfigFiles),
config.WithSharedCredentialsFiles(sharedCredentialsFiles),
)
if err != nil {
return aws.Config{}, WrapError(err)
}

return cfg, nil
}
56 changes: 56 additions & 0 deletions internal/aws_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package internal

import (
"context"
"testing"

"github.com/aws/aws-sdk-go-v2/config"
"github.com/stretchr/testify/assert"
)

func TestNewConfig(t *testing.T) {
assert := assert.New(t)

tests := map[string]struct {
ctx context.Context
key string
secret string
token string
region string
roleArn string
isErr bool
}{
"fail": {isErr: true},
"success": {ctx: context.Background(), key: mockAwsKey, secret: mockAwsSecret, region: mockRegion, isErr: false},
}

for _, t := range tests {
_, err := NewConfig(t.ctx, t.key, t.secret, t.token, t.region, t.roleArn)
assert.Equal(t.isErr, err != nil)
}
}

func TestNewSharedConfig(t *testing.T) {
assert := assert.New(t)

tests := map[string]struct {
ctx context.Context
profile string
sharedCredentials []string
sharedConfigs []string
isErr bool
}{
"fail": {isErr: true},
"success": {
ctx: context.Background(),
profile: mockProfile,
sharedConfigs: []string{config.DefaultSharedConfigFilename()},
sharedCredentials: []string{config.DefaultSharedCredentialsFilename()},
isErr: false},
}

for _, t := range tests {
_, err := NewSharedConfig(t.ctx, t.profile, t.sharedConfigs, t.sharedCredentials)
assert.Equal(t.isErr, err != nil)
}
}
34 changes: 34 additions & 0 deletions internal/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package internal

import (
"errors"
"fmt"
"runtime"
"strings"

"github.com/gjbae1212/go-wraperror"
)

var (
// ErrInvalidParams is an error type to use when passed arguments are invalid.
ErrInvalidParams = errors.New("[err] invalid params")
// ErrUnknown is an error type to use when error reason doesn't know.
ErrUnknown = errors.New("[err] unknown")
)

// WrapError wraps error.
func WrapError(err error) error {
if err != nil {
// Get program counter and line number
pc, _, line, _ := runtime.Caller(1)
// Get function name from program counter
fn := runtime.FuncForPC(pc).Name()
// Refine function name
details := strings.Split(fn, "/")
fn = details[len(details)-1]
// Build chain
chainErr := wraperror.Error(err)
return chainErr.Wrap(fmt.Errorf("[err][%s:%d]", fn, line))
}
return nil
}
28 changes: 28 additions & 0 deletions internal/error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package internal

import (
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/assert"
)

func TestWrapError(t *testing.T) {
assert := assert.New(t)

tests := map[string]struct {
err error
}{
"error": {err: fmt.Errorf("[err] obj error")},
}

for _, t := range tests {
err := WrapError(t.err)
switch t.err.(type) {
case error:
assert.True(errors.Is(err, t.err.(error)))
}
fmt.Println(err)
}
}
1 change: 1 addition & 0 deletions internal/internal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package internal
45 changes: 45 additions & 0 deletions internal/internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package internal

import (
"context"
"os"
"path/filepath"
"testing"

"github.com/aws/aws-sdk-go-v2/config"
)

var (
mockProfile string
mockAwsKey string
mockAwsSecret string
mockRegion string
)

func TestMain(m *testing.M) {
if os.Getenv("CIRCLECI") != "" {
os.Exit(0)
}

mockProfile = "default"
filename := filepath.Join(os.Getenv("HOME"), ".aws/credentials")
if _, err := os.Stat(filename); os.IsNotExist(err) {
os.Exit(0)
} else {
cfg, err := NewSharedConfig(context.Background(), mockProfile,
[]string{config.DefaultSharedConfigFilename()},
[]string{config.DefaultSharedCredentialsFilename()},
)
if err != nil {
os.Exit(0)
}
cred, err := cfg.Credentials.Retrieve(context.Background())
if err != nil {
panic(err)
}
mockAwsKey = cred.AccessKeyID
mockAwsSecret = cred.SecretAccessKey
mockRegion = cfg.Region
os.Exit(m.Run())
}
}

0 comments on commit 8ce526a

Please sign in to comment.