github.com/dolthub/dolt/go@v0.40.5-0.20240520175717-68db7794bea6/libraries/utils/awsrefreshcreds/creds.go (about)

     1  // Copyright 2023 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Refreshing credentials will periodically refresh credentials from the
    16  // underlying credential provider. This can be used in places where temporary
    17  // credentials are placed into files, for example, and we need profile
    18  // credentials periodically refreshed, for example.
    19  
    20  package awsrefreshcreds
    21  
    22  import (
    23  	"time"
    24  
    25  	"github.com/aws/aws-sdk-go/aws/credentials"
    26  )
    27  
    28  var now func() time.Time = time.Now
    29  
    30  type RefreshingCredentialsProvider struct {
    31  	provider credentials.Provider
    32  
    33  	refreshedAt     time.Time
    34  	refreshInterval time.Duration
    35  }
    36  
    37  func NewRefreshingCredentialsProvider(provider credentials.Provider, interval time.Duration) *RefreshingCredentialsProvider {
    38  	return &RefreshingCredentialsProvider{
    39  		provider:        provider,
    40  		refreshInterval: interval,
    41  	}
    42  }
    43  
    44  func (p *RefreshingCredentialsProvider) Retrieve() (credentials.Value, error) {
    45  	v, err := p.provider.Retrieve()
    46  	if err == nil {
    47  		p.refreshedAt = now()
    48  	}
    49  	return v, err
    50  }
    51  
    52  func (p *RefreshingCredentialsProvider) IsExpired() bool {
    53  	if now().Sub(p.refreshedAt) > p.refreshInterval {
    54  		return true
    55  	}
    56  	return p.provider.IsExpired()
    57  }