iam_aws.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. * Minio Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2017 Minio, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package credentials
  18. import (
  19. "bufio"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "net/http"
  24. "net/url"
  25. "os"
  26. "path"
  27. "time"
  28. )
  29. // DefaultExpiryWindow - Default expiry window.
  30. // ExpiryWindow will allow the credentials to trigger refreshing
  31. // prior to the credentials actually expiring. This is beneficial
  32. // so race conditions with expiring credentials do not cause
  33. // request to fail unexpectedly due to ExpiredTokenException exceptions.
  34. const DefaultExpiryWindow = time.Second * 10 // 10 secs
  35. // A IAM retrieves credentials from the EC2 service, and keeps track if
  36. // those credentials are expired.
  37. type IAM struct {
  38. Expiry
  39. // Required http Client to use when connecting to IAM metadata service.
  40. Client *http.Client
  41. // Custom endpoint to fetch IAM role credentials.
  42. endpoint string
  43. }
  44. // IAM Roles for Amazon EC2
  45. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  46. const (
  47. defaultIAMRoleEndpoint = "http://169.254.169.254"
  48. defaultECSRoleEndpoint = "http://169.254.170.2"
  49. defaultIAMSecurityCredsPath = "/latest/meta-data/iam/security-credentials"
  50. )
  51. // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
  52. func getEndpoint(endpoint string) (string, bool) {
  53. if endpoint != "" {
  54. return endpoint, os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI") != ""
  55. }
  56. if ecsURI := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"); ecsURI != "" {
  57. return fmt.Sprintf("%s%s", defaultECSRoleEndpoint, ecsURI), true
  58. }
  59. return defaultIAMRoleEndpoint, false
  60. }
  61. // NewIAM returns a pointer to a new Credentials object wrapping the IAM.
  62. func NewIAM(endpoint string) *Credentials {
  63. p := &IAM{
  64. Client: &http.Client{
  65. Transport: http.DefaultTransport,
  66. },
  67. endpoint: endpoint,
  68. }
  69. return New(p)
  70. }
  71. // Retrieve retrieves credentials from the EC2 service.
  72. // Error will be returned if the request fails, or unable to extract
  73. // the desired
  74. func (m *IAM) Retrieve() (Value, error) {
  75. endpoint, isEcsTask := getEndpoint(m.endpoint)
  76. var roleCreds ec2RoleCredRespBody
  77. var err error
  78. if isEcsTask {
  79. roleCreds, err = getEcsTaskCredentials(m.Client, endpoint)
  80. } else {
  81. roleCreds, err = getCredentials(m.Client, endpoint)
  82. }
  83. if err != nil {
  84. return Value{}, err
  85. }
  86. // Expiry window is set to 10secs.
  87. m.SetExpiration(roleCreds.Expiration, DefaultExpiryWindow)
  88. return Value{
  89. AccessKeyID: roleCreds.AccessKeyID,
  90. SecretAccessKey: roleCreds.SecretAccessKey,
  91. SessionToken: roleCreds.Token,
  92. SignerType: SignatureV4,
  93. }, nil
  94. }
  95. // A ec2RoleCredRespBody provides the shape for unmarshaling credential
  96. // request responses.
  97. type ec2RoleCredRespBody struct {
  98. // Success State
  99. Expiration time.Time
  100. AccessKeyID string
  101. SecretAccessKey string
  102. Token string
  103. // Error state
  104. Code string
  105. Message string
  106. // Unused params.
  107. LastUpdated time.Time
  108. Type string
  109. }
  110. // Get the final IAM role URL where the request will
  111. // be sent to fetch the rolling access credentials.
  112. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  113. func getIAMRoleURL(endpoint string) (*url.URL, error) {
  114. u, err := url.Parse(endpoint)
  115. if err != nil {
  116. return nil, err
  117. }
  118. u.Path = defaultIAMSecurityCredsPath
  119. return u, nil
  120. }
  121. // listRoleNames lists of credential role names associated
  122. // with the current EC2 service. If there are no credentials,
  123. // or there is an error making or receiving the request.
  124. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  125. func listRoleNames(client *http.Client, u *url.URL) ([]string, error) {
  126. req, err := http.NewRequest("GET", u.String(), nil)
  127. if err != nil {
  128. return nil, err
  129. }
  130. resp, err := client.Do(req)
  131. if err != nil {
  132. return nil, err
  133. }
  134. defer resp.Body.Close()
  135. if resp.StatusCode != http.StatusOK {
  136. return nil, errors.New(resp.Status)
  137. }
  138. credsList := []string{}
  139. s := bufio.NewScanner(resp.Body)
  140. for s.Scan() {
  141. credsList = append(credsList, s.Text())
  142. }
  143. if err := s.Err(); err != nil {
  144. return nil, err
  145. }
  146. return credsList, nil
  147. }
  148. func getEcsTaskCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
  149. req, err := http.NewRequest("GET", endpoint, nil)
  150. if err != nil {
  151. return ec2RoleCredRespBody{}, err
  152. }
  153. resp, err := client.Do(req)
  154. if err != nil {
  155. return ec2RoleCredRespBody{}, err
  156. }
  157. defer resp.Body.Close()
  158. if resp.StatusCode != http.StatusOK {
  159. return ec2RoleCredRespBody{}, errors.New(resp.Status)
  160. }
  161. respCreds := ec2RoleCredRespBody{}
  162. if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
  163. return ec2RoleCredRespBody{}, err
  164. }
  165. return respCreds, nil
  166. }
  167. // getCredentials - obtains the credentials from the IAM role name associated with
  168. // the current EC2 service.
  169. //
  170. // If the credentials cannot be found, or there is an error
  171. // reading the response an error will be returned.
  172. func getCredentials(client *http.Client, endpoint string) (ec2RoleCredRespBody, error) {
  173. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  174. u, err := getIAMRoleURL(endpoint)
  175. if err != nil {
  176. return ec2RoleCredRespBody{}, err
  177. }
  178. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  179. roleNames, err := listRoleNames(client, u)
  180. if err != nil {
  181. return ec2RoleCredRespBody{}, err
  182. }
  183. if len(roleNames) == 0 {
  184. return ec2RoleCredRespBody{}, errors.New("No IAM roles attached to this EC2 service")
  185. }
  186. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  187. // - An instance profile can contain only one IAM role. This limit cannot be increased.
  188. roleName := roleNames[0]
  189. // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
  190. // The following command retrieves the security credentials for an
  191. // IAM role named `s3access`.
  192. //
  193. // $ curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access
  194. //
  195. u.Path = path.Join(u.Path, roleName)
  196. req, err := http.NewRequest("GET", u.String(), nil)
  197. if err != nil {
  198. return ec2RoleCredRespBody{}, err
  199. }
  200. resp, err := client.Do(req)
  201. if err != nil {
  202. return ec2RoleCredRespBody{}, err
  203. }
  204. defer resp.Body.Close()
  205. if resp.StatusCode != http.StatusOK {
  206. return ec2RoleCredRespBody{}, errors.New(resp.Status)
  207. }
  208. respCreds := ec2RoleCredRespBody{}
  209. if err := json.NewDecoder(resp.Body).Decode(&respCreds); err != nil {
  210. return ec2RoleCredRespBody{}, err
  211. }
  212. if respCreds.Code != "Success" {
  213. // If an error code was returned something failed requesting the role.
  214. return ec2RoleCredRespBody{}, errors.New(respCreds.Message)
  215. }
  216. return respCreds, nil
  217. }