Skip to content

Commit

Permalink
fix(oss): add refresh sts token mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayushi Sharma committed Dec 10, 2024
1 parent 25f49c7 commit 9854fb7
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions plugins/providers/oss/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"slices"
"strings"
"sync"
"time"

openapi "github.com/alibabacloud-go/darabonba-openapi/client"
openapiv2 "github.com/alibabacloud-go/darabonba-openapi/v2/client"
Expand All @@ -20,6 +21,8 @@ import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var assumeRoleDuration int64 = 1

//go:generate mockery --name=encryptor --exported --with-expecter
type encryptor interface {
domain.Crypto
Expand All @@ -43,16 +46,18 @@ type provider struct {
typeName string
encryptor encryptor

ossClients map[string]*oss.Client
ossClients map[string]*oss.Client
lastOSSClientCreatedTime map[string]time.Time

mu sync.Mutex
}

func NewProvider(typeName string, encryptor encryptor) *provider {
return &provider{
typeName: typeName,
encryptor: encryptor,
ossClients: make(map[string]*oss.Client),
typeName: typeName,
encryptor: encryptor,
ossClients: make(map[string]*oss.Client),
lastOSSClientCreatedTime: make(map[string]time.Time),
}
}

Expand Down Expand Up @@ -126,7 +131,7 @@ func (p *provider) GrantAccess(ctx context.Context, pc *domain.ProviderConfig, g
}

if len(g.Permissions) == 0 {
return fmt.Errorf("no permissions present for the requested role in provider config")
return fmt.Errorf("no permissions in grant")
}

ramRole, err := getRAMRole(g)
Expand Down Expand Up @@ -372,7 +377,10 @@ func getClientConfig(providerURN, accountID, accountSecret, regionID, assumeAsRA
if err != nil {
return nil, fmt.Errorf("failed to initialize STS client: %w", err)
}

duration := assumeRoleDuration * int64(time.Hour.Seconds())
res, err := stsClient.AssumeRole(&sts.AssumeRoleRequest{
DurationSeconds: &duration,
RoleArn: &assumeAsRAMRole,
RoleSessionName: &providerURN,
})
Expand Down Expand Up @@ -402,8 +410,13 @@ func (p *provider) getCreds(pc *domain.ProviderConfig) (*Credentials, error) {
}

func (p *provider) getOSSClient(pc *domain.ProviderConfig, ramRole string) (*oss.Client, error) {
if client, ok := p.ossClients[ramRole]; ok {
return client, nil
p.mu.Lock()
existingClient, ok := p.ossClients[ramRole]
clientCreatedTime := p.lastOSSClientCreatedTime[ramRole]
p.mu.Unlock()

if ok && time.Since(clientCreatedTime) < time.Duration(assumeRoleDuration)*time.Hour {
return existingClient, nil
}

creds, err := p.getCreds(pc)
Expand All @@ -429,6 +442,7 @@ func (p *provider) getOSSClient(pc *domain.ProviderConfig, ramRole string) (*oss

p.mu.Lock()
p.ossClients[ramRole] = client
p.lastOSSClientCreatedTime[ramRole] = time.Now()
p.mu.Unlock()
return client, nil
}
Expand Down

0 comments on commit 9854fb7

Please sign in to comment.