10 min read
|
Published
|
Updated

API Key Rotation: Create, Set, Test, Finish

How to rotate API keys without downtime: the create, set, test, finish pattern, rotation intervals from NIST, secret managers and Chaingateway specifics.

Chapters
C
Chaingateway Team
Blockchain Experts

Reviewed by Maurice Sobiera

Isometric illustration of rotating API credentials

API key rotation means replacing an active key with a new one on a schedule or after an exposure, then retiring the old key. The reliable pattern has four steps: create, set, test, finish. A short overlap lets both keys work, so requests in flight do not fail. NIST and OWASP both advise automating it.

Why should I rotate API keys?

Rotation shortens the time in which a leaked key is useful to an attacker. Every API key is a standing liability. A key can leak through a committed .env file, a compromised CI runner or a former employee’s laptop. The longer the key stays valid, the longer the leak stays exploitable.

OWASP lists this risk as NHI7, Long-Lived Secrets, in its Non-Human Identities Top 10. It describes API keys and tokens with expiration dates far in the future, or none at all. It calls such secrets extremely common, because rotation is hard and ephemeral alternatives are not always available.

Rotation matters most for these credentials:

  • Keys with broad scopes, such as admin, billing or write access to production data.
  • Credentials shared across several services or teams.
  • Anything embedded in client-side code, mobile apps or third-party integrations.
  • Tokens that have touched a public repository, even briefly.

Where you can, replace the static key with a short-lived token from OAuth or a workload identity system. A credential that expires on its own needs no rotation job.

How often should I rotate API keys?

NIST sets one concrete number, and it applies to signing keys. NIST IR 8587 says that for high-impact systems, signing keys should have a maximum active usage period of no more than 90 days. For moderate and low impact systems, a longer period may be appropriate but should be less than one year. The report also says to document the cryptoperiods and to employ automated rotation.

NIST does not give intervals for ordinary API keys. The values below are our suggestions, derived from the risk-based approach in the report. They are not a NIST requirement.

CredentialSuggested maximum ageReason
Signing keys of high-impact systems90 days (NIST)Largest blast radius
Service-to-service API keys30 to 90 daysDepends on scope
CI/CD tokens30 daysOften carry deploy access
User-facing API keys90 days, and immediately after suspected exposureMany copies exist

Bar chart of suggested cryptoperiods: signing keys up to 90 days, service-to-service keys 30 to 90 days, CI/CD tokens up to 30 days, user-facing API keys 90 days

The rule behind the table is simple: the more damage a leaked credential could do, the shorter its usable period should be. A manual 30-day cycle is realistic for a handful of keys. With dozens of services it needs automation. NIST makes the same point. Shorter cryptoperiods push organizations to automate rotation and to practise rollover regularly.

Where should I store API keys?

Store keys in a secret manager that versions secrets, runs rotation hooks, scopes access and logs every read. Spreadsheets and shared .env files can do none of this. Check four capabilities before you choose:

  • Versioning, so the current and the previous secret can exist at the same time.
  • Rotation hooks that run your rotation function on a schedule or an event.
  • Access scoping, so the rotation agent cannot read every secret.
  • Audit logs that record who accessed or rotated which secret.

AWS Secrets Manager supports scheduled rotation through a rotation function. HashiCorp Vault can issue dynamic secrets that expire on their own. Cloud-native key management services tied to IAM roles fill the same role.

Where the architecture allows it, skip static keys. OWASP recommends dynamic secrets where possible, because they reduce the surface for credential reuse. Temporary credentials from AWS STS or managed identities on Azure and Google Cloud expire after minutes or hours, so nothing long-lived is left to rotate.

What are the create, set, test, finish steps?

The four steps are the pattern that the OWASP cheat sheet describes for serverless rotation functions. They apply to any secret manager or custom script.

  1. Create: generate a new secret version without touching the one in use.
  2. Set: push the new credential to the dependent service or configuration store.
  3. Test: run an integration check that proves the new secret authenticates.
  4. Finish: promote the new secret to active, and revoke or schedule deletion of the old one.

The step that teams skip is the overlap between “set” and “finish”. NIST describes it as overlapping acceptance of old and new keys. Rotation should schedule key rollover in advance of expiration, so that recipients accept both versions for a while. The right length of the overlap depends on your system. It must be longer than your longest in-flight request and longer than the time your clients need to pick up the new value, including cache lifetimes. Choose a number, then test it in staging.

TriggerBest fitPermission model
ScheduledPredictable cadence, such as 30 or 90 daysRotation role scoped to one secret path
Event-drivenCompromise detected, employee offboardingElevated but time-boxed, revoked after the run
ManualOne-off audits, new service onboardingHuman approval plus MFA

The rotation agent should hold the narrowest permission set possible: write access to one secret and nothing broader.

What should my rotation checklist include?

Run through four points before you automate anything.

  1. Back up the current secret and test the rollback, so that it is not just theory.
  2. Build an integration test that validates the new credential against a real endpoint.
  3. Create a rotation role scoped to exactly one secret.
  4. Log every rotation event to your audit trail.

Watch for three recurring failure points. Applications cache credentials in memory and do not see the new key until a restart. Providers rate-limit the key-creation endpoint if you rotate many secrets in one batch. Stale clients keep using a revoked key after the overlap has ended.

Log who or what triggered each rotation, a masked version of the old and new key, the mode (scheduled, manual or emergency) and the outcome. Watch for a sudden spike in requests from one key, calls from IP addresses or regions that the key never used before, and requests that use a key which should already have expired. Run repository scans for hardcoded keys and keep an inventory, because a key outside the inventory never gets rotated.

How do I rotate Chaingateway credentials?

A Chaingateway integration has three kinds of secrets, and each rotates differently.

The API token authenticates your requests as a bearer token. You create tokens in the account panel under API Tokens, and you give each one a name. Use one name per environment, such as development, staging and production. To rotate, create a new token, deploy it through your secret manager, check that requests succeed and then retire the old one. To limit what a leaked token can do, enable the IP whitelist (described below) so that only your server addresses can use it.

The webhook secret, called the personal secret, signs every webhook through the X-Signature header. The webhook security documentation says that a new secret takes effect immediately on webhook notifications. You cannot run two secrets on the sender side, so the overlap must be on your receiver. Verify against the new secret and the old one for a short time, then drop the old one.

import { createHmac, timingSafeEqual } from "node:crypto";
// Accept the new secret and, during rotation only, the previous one
const secrets = [process.env.WEBHOOK_SECRET, process.env.WEBHOOK_SECRET_PREVIOUS].filter(Boolean);
function signatureValid(txid, received) {
return secrets.some((secret) => {
const expected = createHmac("sha256", secret).update(txid).digest("base64");
return (
expected.length === received.length &&
timingSafeEqual(Buffer.from(expected), Buffer.from(received))
);
});
}

Notifications that your server rejected during the switch appear in the list of failed notifications. Chaingateway does not retry them automatically. Read the list with GET /api/v2/{chain}/webhooks/notifications/failed and resend each entry with POST /api/v2/{chain}/webhooks/notifications/{id}/retry. The webhook delivery guide covers this in more detail.

Wallet passwords protect addresses that you created with a password. You can change one with POST /api/v2/ethereum/addresses/{address}, which takes old_password and new_password. The same route exists for the other chains. Chaingateway does not store passwords, so keep the new one in your secret manager before you change it. A lost password cannot be restored.

What does the Chaingateway IP whitelist do?

The IP whitelist is an account setting that limits your API key to the server addresses you list. It was released on 21 June 2021. You turn it on in the settings of the account panel, then enter the allowed addresses. A request from any other address is refused, even if the key is correct, so a leaked key is useless from a machine you did not list.

Add your own server address when you enable it, or your own requests are refused too. List the public address that your server presents to the internet. Private ranges such as 10.0.0.0/8 and 192.168.0.0/16 are defined in RFC 1918 and never reach the API as the source of a request. Behind a NAT gateway, list the gateway address. Every machine behind it is then allowed, not only one.

The whitelist covers requests that you send to the API. It does not apply to webhooks, which go from Chaingateway to your endpoint. Verify webhooks with the signature, as described above.

The whitelist and rotation limit different things. The whitelist limits where a stolen key works. Rotation limits how long it works. Use both. When your servers move to new addresses, update the list before the move, so that your own traffic is not refused.

When do static API keys stop making sense?

Static keys are acceptable for low-risk internal tools. Once you expose an API to external partners or handle financial data, move toward OIDC or JWT-based authentication with short expiry times. Start with one low-traffic service. Confirm that your rotation automation holds under real traffic, then expand. A rotation policy that is enforced, not just suggested, is one of the most effective operational changes a security team can make.

Screenshot of the Chaingateway homepage with the headline about a unified blockchain API for crypto payments and webhooks and a button to start a 7-day free trial

Chaingateway covers Ethereum, Bitcoin, Tron, Solana, Polygon, BNB Smart Chain and Arbitrum with one REST API and one authentication layer, so you do not manage a separate credential lifecycle per chain. The webhooks feature covers deposit notifications. Plans start at €49 per month on the pricing page, and the 7-day free trial needs no card.

Sources

Created with BabyLoveGrowth to build backlinks

Frequently asked questions

Rotating an API key means generating a new credential to replace the active one, then retiring the old one when every dependent system has switched. Done properly, it runs as an automated create, set, test, finish cycle with a short overlap in which both keys work.

It depends on the risk. NIST IR 8587 says signing keys of high-impact systems should not stay in active use longer than 90 days. For ordinary API keys it gives no number, so choose an interval from the key’s scope. Shorter is better for CI/CD tokens and for anything with broad access.

Rotation limits the damage from a leaked or stolen credential, because it shortens the time in which the key is valid. OWASP lists long-lived secrets as NHI7 in its Non-Human Identities Top 10.

Automate the process with a secret manager, follow the create, set, test, finish pattern and keep a transition window in which the old and new key both work. This avoids the downtime of switching every dependent service at once.

Yes. Chaingateway signs webhooks with HMAC-SHA256 in the X-Signature header, so you can verify authenticity. If you change the personal secret, the new secret applies at once, so your receiver should accept both secrets for a short time.

How we write these articles

Ready to build this yourself? Get your API key — 7-day trial, no card required — or see the Blockchain API for the full endpoint reference.

C
Chaingateway Team
Blockchain Experts

The Chaingateway team is dedicated to simplifying blockchain integration for developers worldwide.