credentials.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // Package credentials provides credential retrieval and management
  2. //
  3. // The Credentials is the primary method of getting access to and managing
  4. // credentials Values. Using dependency injection retrieval of the credential
  5. // values is handled by a object which satisfies the Provider interface.
  6. //
  7. // By default the Credentials.Get() will cache the successful result of a
  8. // Provider's Retrieve() until Provider.IsExpired() returns true. At which
  9. // point Credentials will call Provider's Retrieve() to get new credential Value.
  10. //
  11. // The Provider is responsible for determining when credentials Value have expired.
  12. // It is also important to note that Credentials will always call Retrieve the
  13. // first time Credentials.Get() is called.
  14. //
  15. // Example of using the environment variable credentials.
  16. //
  17. // creds := NewEnvCredentials()
  18. //
  19. // // Retrieve the credentials value
  20. // credValue, err := creds.Get()
  21. // if err != nil {
  22. // // handle error
  23. // }
  24. //
  25. // Example of forcing credentials to expire and be refreshed on the next Get().
  26. // This may be helpful to proactively expire credentials and refresh them sooner
  27. // than they would naturally expire on their own.
  28. //
  29. // creds := NewCredentials(&EC2RoleProvider{})
  30. // creds.Expire()
  31. // credsValue, err := creds.Get()
  32. // // New credentials will be retrieved instead of from cache.
  33. //
  34. //
  35. // Custom Provider
  36. //
  37. // Each Provider built into this package also provides a helper method to generate
  38. // a Credentials pointer setup with the provider. To use a custom Provider just
  39. // create a type which satisfies the Provider interface and pass it to the
  40. // NewCredentials method.
  41. //
  42. // type MyProvider struct{}
  43. // func (m *MyProvider) Retrieve() (Value, error) {...}
  44. // func (m *MyProvider) IsExpired() bool {...}
  45. //
  46. // creds := NewCredentials(&MyProvider{})
  47. // credValue, err := creds.Get()
  48. //
  49. package credentials
  50. import (
  51. "sync"
  52. "time"
  53. )
  54. // AnonymousCredentials is an empty Credential object that can be used as
  55. // dummy placeholder credentials for requests that do not need signed.
  56. //
  57. // This Credentials can be used to configure a service to not sign requests
  58. // when making service API calls. For example, when accessing public
  59. // s3 buckets.
  60. //
  61. // svc := s3.New(&aws.Config{Credentials: AnonymousCredentials})
  62. // // Access public S3 buckets.
  63. //
  64. // @readonly
  65. var AnonymousCredentials = NewStaticCredentials("", "", "")
  66. // A Value is the AWS credentials value for individual credential fields.
  67. type Value struct {
  68. // AWS Access key ID
  69. AccessKeyID string
  70. // AWS Secret Access Key
  71. SecretAccessKey string
  72. // AWS Session Token
  73. SessionToken string
  74. // Provider used to get credentials
  75. ProviderName string
  76. }
  77. // A Provider is the interface for any component which will provide credentials
  78. // Value. A provider is required to manage its own Expired state, and what to
  79. // be expired means.
  80. //
  81. // The Provider should not need to implement its own mutexes, because
  82. // that will be managed by Credentials.
  83. type Provider interface {
  84. // Refresh returns nil if it successfully retrieved the value.
  85. // Error is returned if the value were not obtainable, or empty.
  86. Retrieve() (Value, error)
  87. // IsExpired returns if the credentials are no longer valid, and need
  88. // to be retrieved.
  89. IsExpired() bool
  90. }
  91. // A Expiry provides shared expiration logic to be used by credentials
  92. // providers to implement expiry functionality.
  93. //
  94. // The best method to use this struct is as an anonymous field within the
  95. // provider's struct.
  96. //
  97. // Example:
  98. // type EC2RoleProvider struct {
  99. // Expiry
  100. // ...
  101. // }
  102. type Expiry struct {
  103. // The date/time when to expire on
  104. expiration time.Time
  105. // If set will be used by IsExpired to determine the current time.
  106. // Defaults to time.Now if CurrentTime is not set. Available for testing
  107. // to be able to mock out the current time.
  108. CurrentTime func() time.Time
  109. }
  110. // SetExpiration sets the expiration IsExpired will check when called.
  111. //
  112. // If window is greater than 0 the expiration time will be reduced by the
  113. // window value.
  114. //
  115. // Using a window is helpful to trigger credentials to expire sooner than
  116. // the expiration time given to ensure no requests are made with expired
  117. // tokens.
  118. func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) {
  119. e.expiration = expiration
  120. if window > 0 {
  121. e.expiration = e.expiration.Add(-window)
  122. }
  123. }
  124. // IsExpired returns if the credentials are expired.
  125. func (e *Expiry) IsExpired() bool {
  126. if e.CurrentTime == nil {
  127. e.CurrentTime = time.Now
  128. }
  129. return e.expiration.Before(e.CurrentTime())
  130. }
  131. // A Credentials provides synchronous safe retrieval of AWS credentials Value.
  132. // Credentials will cache the credentials value until they expire. Once the value
  133. // expires the next Get will attempt to retrieve valid credentials.
  134. //
  135. // Credentials is safe to use across multiple goroutines and will manage the
  136. // synchronous state so the Providers do not need to implement their own
  137. // synchronization.
  138. //
  139. // The first Credentials.Get() will always call Provider.Retrieve() to get the
  140. // first instance of the credentials Value. All calls to Get() after that
  141. // will return the cached credentials Value until IsExpired() returns true.
  142. type Credentials struct {
  143. creds Value
  144. forceRefresh bool
  145. m sync.Mutex
  146. provider Provider
  147. }
  148. // NewCredentials returns a pointer to a new Credentials with the provider set.
  149. func NewCredentials(provider Provider) *Credentials {
  150. return &Credentials{
  151. provider: provider,
  152. forceRefresh: true,
  153. }
  154. }
  155. // Get returns the credentials value, or error if the credentials Value failed
  156. // to be retrieved.
  157. //
  158. // Will return the cached credentials Value if it has not expired. If the
  159. // credentials Value has expired the Provider's Retrieve() will be called
  160. // to refresh the credentials.
  161. //
  162. // If Credentials.Expire() was called the credentials Value will be force
  163. // expired, and the next call to Get() will cause them to be refreshed.
  164. func (c *Credentials) Get() (Value, error) {
  165. c.m.Lock()
  166. defer c.m.Unlock()
  167. if c.isExpired() {
  168. creds, err := c.provider.Retrieve()
  169. if err != nil {
  170. return Value{}, err
  171. }
  172. c.creds = creds
  173. c.forceRefresh = false
  174. }
  175. return c.creds, nil
  176. }
  177. // Expire expires the credentials and forces them to be retrieved on the
  178. // next call to Get().
  179. //
  180. // This will override the Provider's expired state, and force Credentials
  181. // to call the Provider's Retrieve().
  182. func (c *Credentials) Expire() {
  183. c.m.Lock()
  184. defer c.m.Unlock()
  185. c.forceRefresh = true
  186. }
  187. // IsExpired returns if the credentials are no longer valid, and need
  188. // to be retrieved.
  189. //
  190. // If the Credentials were forced to be expired with Expire() this will
  191. // reflect that override.
  192. func (c *Credentials) IsExpired() bool {
  193. c.m.Lock()
  194. defer c.m.Unlock()
  195. return c.isExpired()
  196. }
  197. // isExpired helper method wrapping the definition of expired credentials.
  198. func (c *Credentials) isExpired() bool {
  199. return c.forceRefresh || c.provider.IsExpired()
  200. }