api_client.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package imds
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. "github.com/aws/aws-sdk-go-v2/aws"
  11. "github.com/aws/aws-sdk-go-v2/aws/retry"
  12. awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
  13. internalconfig "github.com/aws/aws-sdk-go-v2/feature/ec2/imds/internal/config"
  14. "github.com/aws/smithy-go"
  15. "github.com/aws/smithy-go/logging"
  16. "github.com/aws/smithy-go/middleware"
  17. smithyhttp "github.com/aws/smithy-go/transport/http"
  18. )
  19. // ServiceID provides the unique name of this API client
  20. const ServiceID = "ec2imds"
  21. // Client provides the API client for interacting with the Amazon EC2 Instance
  22. // Metadata Service API.
  23. type Client struct {
  24. options Options
  25. }
  26. // ClientEnableState provides an enumeration if the client is enabled,
  27. // disabled, or default behavior.
  28. type ClientEnableState = internalconfig.ClientEnableState
  29. // Enumeration values for ClientEnableState
  30. const (
  31. ClientDefaultEnableState ClientEnableState = internalconfig.ClientDefaultEnableState // default behavior
  32. ClientDisabled ClientEnableState = internalconfig.ClientDisabled // client disabled
  33. ClientEnabled ClientEnableState = internalconfig.ClientEnabled // client enabled
  34. )
  35. // EndpointModeState is an enum configuration variable describing the client endpoint mode.
  36. // Not configurable directly, but used when using the NewFromConfig.
  37. type EndpointModeState = internalconfig.EndpointModeState
  38. // Enumeration values for EndpointModeState
  39. const (
  40. EndpointModeStateUnset EndpointModeState = internalconfig.EndpointModeStateUnset
  41. EndpointModeStateIPv4 EndpointModeState = internalconfig.EndpointModeStateIPv4
  42. EndpointModeStateIPv6 EndpointModeState = internalconfig.EndpointModeStateIPv6
  43. )
  44. const (
  45. disableClientEnvVar = "AWS_EC2_METADATA_DISABLED"
  46. // Client endpoint options
  47. endpointEnvVar = "AWS_EC2_METADATA_SERVICE_ENDPOINT"
  48. defaultIPv4Endpoint = "http://169.254.169.254"
  49. defaultIPv6Endpoint = "http://[fd00:ec2::254]"
  50. )
  51. // New returns an initialized Client based on the functional options. Provide
  52. // additional functional options to further configure the behavior of the client,
  53. // such as changing the client's endpoint or adding custom middleware behavior.
  54. func New(options Options, optFns ...func(*Options)) *Client {
  55. options = options.Copy()
  56. for _, fn := range optFns {
  57. fn(&options)
  58. }
  59. options.HTTPClient = resolveHTTPClient(options.HTTPClient)
  60. if options.Retryer == nil {
  61. options.Retryer = retry.NewStandard()
  62. }
  63. options.Retryer = retry.AddWithMaxBackoffDelay(options.Retryer, 1*time.Second)
  64. if options.ClientEnableState == ClientDefaultEnableState {
  65. if v := os.Getenv(disableClientEnvVar); strings.EqualFold(v, "true") {
  66. options.ClientEnableState = ClientDisabled
  67. }
  68. }
  69. if len(options.Endpoint) == 0 {
  70. if v := os.Getenv(endpointEnvVar); len(v) != 0 {
  71. options.Endpoint = v
  72. }
  73. }
  74. client := &Client{
  75. options: options,
  76. }
  77. if client.options.tokenProvider == nil && !client.options.disableAPIToken {
  78. client.options.tokenProvider = newTokenProvider(client, defaultTokenTTL)
  79. }
  80. return client
  81. }
  82. // NewFromConfig returns an initialized Client based the AWS SDK config, and
  83. // functional options. Provide additional functional options to further
  84. // configure the behavior of the client, such as changing the client's endpoint
  85. // or adding custom middleware behavior.
  86. func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client {
  87. opts := Options{
  88. APIOptions: append([]func(*middleware.Stack) error{}, cfg.APIOptions...),
  89. HTTPClient: cfg.HTTPClient,
  90. ClientLogMode: cfg.ClientLogMode,
  91. Logger: cfg.Logger,
  92. }
  93. if cfg.Retryer != nil {
  94. opts.Retryer = cfg.Retryer()
  95. }
  96. resolveClientEnableState(cfg, &opts)
  97. resolveEndpointConfig(cfg, &opts)
  98. resolveEndpointModeConfig(cfg, &opts)
  99. return New(opts, optFns...)
  100. }
  101. // Options provides the fields for configuring the API client's behavior.
  102. type Options struct {
  103. // Set of options to modify how an operation is invoked. These apply to all
  104. // operations invoked for this client. Use functional options on operation
  105. // call to modify this list for per operation behavior.
  106. APIOptions []func(*middleware.Stack) error
  107. // The endpoint the client will use to retrieve EC2 instance metadata.
  108. //
  109. // Specifies the EC2 Instance Metadata Service endpoint to use. If specified it overrides EndpointMode.
  110. //
  111. // If unset, and the environment variable AWS_EC2_METADATA_SERVICE_ENDPOINT
  112. // has a value the client will use the value of the environment variable as
  113. // the endpoint for operation calls.
  114. //
  115. // AWS_EC2_METADATA_SERVICE_ENDPOINT=http://[::1]
  116. Endpoint string
  117. // The endpoint selection mode the client will use if no explicit endpoint is provided using the Endpoint field.
  118. //
  119. // Setting EndpointMode to EndpointModeStateIPv4 will configure the client to use the default EC2 IPv4 endpoint.
  120. // Setting EndpointMode to EndpointModeStateIPv6 will configure the client to use the default EC2 IPv6 endpoint.
  121. //
  122. // By default if EndpointMode is not set (EndpointModeStateUnset) than the default endpoint selection mode EndpointModeStateIPv4.
  123. EndpointMode EndpointModeState
  124. // The HTTP client to invoke API calls with. Defaults to client's default
  125. // HTTP implementation if nil.
  126. HTTPClient HTTPClient
  127. // Retryer guides how HTTP requests should be retried in case of recoverable
  128. // failures. When nil the API client will use a default retryer.
  129. Retryer aws.Retryer
  130. // Changes if the EC2 Instance Metadata client is enabled or not. Client
  131. // will default to enabled if not set to ClientDisabled. When the client is
  132. // disabled it will return an error for all operation calls.
  133. //
  134. // If ClientEnableState value is ClientDefaultEnableState (default value),
  135. // and the environment variable "AWS_EC2_METADATA_DISABLED" is set to
  136. // "true", the client will be disabled.
  137. //
  138. // AWS_EC2_METADATA_DISABLED=true
  139. ClientEnableState ClientEnableState
  140. // Configures the events that will be sent to the configured logger.
  141. ClientLogMode aws.ClientLogMode
  142. // The logger writer interface to write logging messages to.
  143. Logger logging.Logger
  144. // provides the caching of API tokens used for operation calls. If unset,
  145. // the API token will not be retrieved for the operation.
  146. tokenProvider *tokenProvider
  147. // option to disable the API token provider for testing.
  148. disableAPIToken bool
  149. }
  150. // HTTPClient provides the interface for a client making HTTP requests with the
  151. // API.
  152. type HTTPClient interface {
  153. Do(*http.Request) (*http.Response, error)
  154. }
  155. // Copy creates a copy of the API options.
  156. func (o Options) Copy() Options {
  157. to := o
  158. to.APIOptions = append([]func(*middleware.Stack) error{}, o.APIOptions...)
  159. return to
  160. }
  161. // WithAPIOptions wraps the API middleware functions, as a functional option
  162. // for the API Client Options. Use this helper to add additional functional
  163. // options to the API client, or operation calls.
  164. func WithAPIOptions(optFns ...func(*middleware.Stack) error) func(*Options) {
  165. return func(o *Options) {
  166. o.APIOptions = append(o.APIOptions, optFns...)
  167. }
  168. }
  169. func (c *Client) invokeOperation(
  170. ctx context.Context, opID string, params interface{}, optFns []func(*Options),
  171. stackFns ...func(*middleware.Stack, Options) error,
  172. ) (
  173. result interface{}, metadata middleware.Metadata, err error,
  174. ) {
  175. stack := middleware.NewStack(opID, smithyhttp.NewStackRequest)
  176. options := c.options.Copy()
  177. for _, fn := range optFns {
  178. fn(&options)
  179. }
  180. if options.ClientEnableState == ClientDisabled {
  181. return nil, metadata, &smithy.OperationError{
  182. ServiceID: ServiceID,
  183. OperationName: opID,
  184. Err: fmt.Errorf(
  185. "access disabled to EC2 IMDS via client option, or %q environment variable",
  186. disableClientEnvVar),
  187. }
  188. }
  189. for _, fn := range stackFns {
  190. if err := fn(stack, options); err != nil {
  191. return nil, metadata, err
  192. }
  193. }
  194. for _, fn := range options.APIOptions {
  195. if err := fn(stack); err != nil {
  196. return nil, metadata, err
  197. }
  198. }
  199. handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack)
  200. result, metadata, err = handler.Handle(ctx, params)
  201. if err != nil {
  202. return nil, metadata, &smithy.OperationError{
  203. ServiceID: ServiceID,
  204. OperationName: opID,
  205. Err: err,
  206. }
  207. }
  208. return result, metadata, err
  209. }
  210. const (
  211. // HTTP client constants
  212. defaultDialerTimeout = 250 * time.Millisecond
  213. defaultResponseHeaderTimeout = 500 * time.Millisecond
  214. )
  215. func resolveHTTPClient(client HTTPClient) HTTPClient {
  216. if client == nil {
  217. client = awshttp.NewBuildableClient()
  218. }
  219. if c, ok := client.(*awshttp.BuildableClient); ok {
  220. client = c.
  221. WithDialerOptions(func(d *net.Dialer) {
  222. // Use a custom Dial timeout for the EC2 Metadata service to account
  223. // for the possibility the application might not be running in an
  224. // environment with the service present. The client should fail fast in
  225. // this case.
  226. d.Timeout = defaultDialerTimeout
  227. }).
  228. WithTransportOptions(func(tr *http.Transport) {
  229. // Use a custom Transport timeout for the EC2 Metadata service to
  230. // account for the possibility that the application might be running in
  231. // a container, and EC2Metadata service drops the connection after a
  232. // single IP Hop. The client should fail fast in this case.
  233. tr.ResponseHeaderTimeout = defaultResponseHeaderTimeout
  234. })
  235. }
  236. return client
  237. }
  238. func resolveClientEnableState(cfg aws.Config, options *Options) error {
  239. if options.ClientEnableState != ClientDefaultEnableState {
  240. return nil
  241. }
  242. value, found, err := internalconfig.ResolveClientEnableState(cfg.ConfigSources)
  243. if err != nil || !found {
  244. return err
  245. }
  246. options.ClientEnableState = value
  247. return nil
  248. }
  249. func resolveEndpointModeConfig(cfg aws.Config, options *Options) error {
  250. if options.EndpointMode != EndpointModeStateUnset {
  251. return nil
  252. }
  253. value, found, err := internalconfig.ResolveEndpointModeConfig(cfg.ConfigSources)
  254. if err != nil || !found {
  255. return err
  256. }
  257. options.EndpointMode = value
  258. return nil
  259. }
  260. func resolveEndpointConfig(cfg aws.Config, options *Options) error {
  261. if len(options.Endpoint) != 0 {
  262. return nil
  263. }
  264. value, found, err := internalconfig.ResolveEndpointConfig(cfg.ConfigSources)
  265. if err != nil || !found {
  266. return err
  267. }
  268. options.Endpoint = value
  269. return nil
  270. }