aws-sdk-ruby: Aws::CloudWatch::Client doesn't automatically refresh credentials
Describe the bug
We use the sidekiq-cloudwatchmetrics gem to send Sidekiq-related metrics to CloudWatch. Occasionally, we encounter the following error:
Aws::CloudWatch::Errors::ExpiredToken: The security token included in the request is expired
Upon investigation, we found that the gem initializes an Aws::CloudWatch::Client, which uses Aws::InstanceProfileCredentials. These credentials are supposed to auto-refresh before expiration. However, the error indicates that the token is not being refreshed in time, causing the metrics to fail. Once the error starts, it repeats, and the metrics fail to recover.
Regression Issue
- Select this option if this issue appears to be a regression.
Expected Behavior
The Aws::InstanceProfileCredentials should automatically refresh the security token before expiration (approximately 5 minutes before expiry) and ensure that the put_metric_data API call succeeds without errors. Metrics should continue to be sent to CloudWatch without interruption.
Current Behavior
The Aws::CloudWatch::Client raises Aws::CloudWatch::Errors::ExpiredToken errors when attempting to send metrics.
Once this error occurs:
- The metrics stop being sent to CloudWatch.
- The error persists until the process is restarted or manually handled.
- The auto-refresh mechanism in
Aws::InstanceProfileCredentialsdoes not appear to trigger correctly in this context.
Reproduction Steps
Configure the sidekiq-cloudwatchmetrics gem in a Sidekiq setup that uses an IAM role (e.g., on EC2 or ECS).
You can find the configuration I used here:
Allow the process to run for an extended period, relying on auto-refreshable credentials from Aws::InstanceProfileCredentials.
Observe that after some time, the following error may appear:
Aws::CloudWatch::Errors::ExpiredToken: The security token included in the request is expired
Possible Solution
No response
Additional Information/Context
Here are some useful links for more context regarding my problem:
- The issue I opened in the
sidekiq-cloudwatchmetricsrepo https://github.com/sj26/sidekiq-cloudwatchmetrics/issues/48 - The PR I opened to fix the problem in the
sidekiq-cloudwatchmetricsrepo https://github.com/sj26/sidekiq-cloudwatchmetrics/pull/49/files
Gem name (‘aws-sdk’, ‘aws-sdk-resources’ or service gems like ‘aws-sdk-s3’) and its version
aws-sdk-cloudwatch
Environment details (Version of Ruby, OS environment)
Ruby - 3.2.5, OS - Debian GNU/Linux 12 (bookworm), Docker image - ruby:3.2.5-slim, sidekiq-cloudwatchmetrics - 2.6.0
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 1
- Comments: 69 (32 by maintainers)
The PR is mostly code complete - if you are brave, you can try checking it out and running it in a pre-prod environment. Otherwise, when there is a new release (no ETA but “soon”), please pull the changes and see if you observe this behavior. It will try to hit a new IMDS endpoint (with -extended in the suffix) which will probably fail right now and then fallback to the old endpoint. In general, the code was simplified, and uses the EC2Metadata class to facilitate token state and getting metadata, which has better error handling. I’m optimistic that maybe it fixed this case. I am still not sure of the root cause.
@Roy-Gal-Git asked me to share here that I also have seen this issue. In fact, we have been noticing the broader issue of tokens not being refreshed on time for over a year now in many parts of our Ruby system. This doesn’t happen on our Go projects. It’s not just CloudWatch either. We saw it on DynamoDB, SES, and I believe even SQS. It happens every few weeks at seemingly random. System time seems correct when it happens (no NTP issues that I could find).
We don’t have any unique configuration for the AWS client (at least not on purpose). Just the basic client.
I should also mention this happens across multiple EC2 instances. They’re part of ASG with max life cycle of a few weeks. This issue hasn’t been instance specific for us.
The only other thing is your retry limit, which I think I discussed before. It defaults to 1 and based on logging I think you are using the default right? Can you try setting a higher retry limit and potentially also set a backoff function if the default is not enough? I am thinking that if you have more retries with staggering requests between the two processes that the service will not brown out.
You are correct and I did not see that. I’m sorry, this is what I deserve for trying reading GitHub on Saturday after the 4th.
Not that I can immediately think of - this issue only seems to happen for this sidekiq feature.
I have not looked at this since. @jterapin is going to be working on the IMDS refactor and new feature in the next few weeks. I’m hoping that you can trial run those changes before we ship them. I’m still not confident in the root cause.
That’s interesting. MissingCredentialsError is thrown in the SDK when the sigv4 gem doesn’t have credentials - either the class was not provided or the credentials don’t have access key/secret access key. Did it raise with
'unable to sign request without credentials set'?Based on that logging, I would agree, it looks like IMDS is timing out (that appears to be an http open timeout)? Some things to try, set
http_open_timeoutto a larger number, and setretriesto a larger number (both default to 1).I think printing the stack trace would also be helpful so we can see the exact failure block - I’m going to assume this is happening in
open_connectionbecause it hasn’t even checked the token or fetched profile name. It looks to be using the generic rescue here which returns those empty credentials. It should be hitting this path here because the empty hash wouldn’t have credentials, so it would be using the previously fetched credentials even if they are expired (this is by design).In general, we have planned work very soon to improve this because we are being asked to support a new feature for IMDS, and drop the v1 fallback mechanism. That might help clean up the code a bit to where this problem goes away; i’m optimistic, but we should still try to figure out the root cause. Even in the case of credentials not fetched because of the open timeout, this case should be handled.
@alextwoods @mullermp
I was wrong when I said we don’t use those services.
The instance is using Amazon Time Sync Service (169.254.169.123) with Chrony. The system time is accurate, with an offset of only a few nanoseconds, and chronyc tracking confirms synchronization is stable. Time drift is not an issue.
Your previous code had expired credentials (a valid ruby object with just invalid credentials) but that new error indicates your entire credentials object has been blown away. Here is where that is raised: https://github.com/aws/aws-sdk-ruby/blob/version-3/gems%2Faws-sdk-core%2Flib%2Faws-sdk-core%2Fplugins%2Fsign.rb. I do think it’s still something with your setup or environment - no SDK code will remove credentials from configuration that I’m aware of.
@mullermp @alextwoods I have 2 small updates:
Aws::Errors::MissingCredentialsError: unable to sign request without credentials setBacktrace:And
Aws::Sigv4::Errors::MissingCredentialsError: missing credentials, provide credentials with one of the following options: - :access_key_id and :secret_access_key - :credentials - :credentials_providerBacktrace:Do you think that the 3 errors are related in any kind of way?
You can pass an instance of a logger (or technically anything that responds to
<<) as thehttp_debug_output, eg:But again as a general warning - this will log the actual requests and responses which include credentials.