From a190363ee1f1e5b518f70803ae345bf510d8e11e Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 23 Nov 2026 13:05:48 -0500 Subject: [PATCH 01/17] feat(toolkit-lib): respect AWS_MAX_ATTEMPTS and AWS_RETRY_MODE environment variables We pass an explicit retryStrategy to every SDK client, which makes the SDK ignore the standard AWS_MAX_ATTEMPTS and AWS_RETRY_MODE environment variables. Resolve them ourselves and fall back to the existing per-client defaults. The backoff schedule stays ours in both standard and adaptive mode. --- .../lib/api/aws-auth/private/index.ts | 1 + .../toolkit-lib/lib/api/aws-auth/retry.ts | 97 ++++++++++++++++ .../toolkit-lib/lib/api/aws-auth/sdk.ts | 40 +------ .../test/api/aws-auth/sdk-retry.test.ts | 104 +++++++++++++++++- 4 files changed, 206 insertions(+), 36 deletions(-) create mode 100644 packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/private/index.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/private/index.ts index c00611d39..0f36fd8d2 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/private/index.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/private/index.ts @@ -1,6 +1,7 @@ export * from '../sdk'; export * from '../sdk-provider'; export * from '../sdk-logger'; +export * from '../retry'; // temporary testing exports export { AccountAccessKeyCache } from '../account-cache'; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts new file mode 100644 index 000000000..dace938d5 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -0,0 +1,97 @@ +import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; +import { ToolkitError } from '../../toolkit/toolkit-error'; + +/** + * Standard AWS environment variable that sets the total number of attempts (initial call plus retries) + */ +export const AWS_MAX_ATTEMPTS_ENV = 'AWS_MAX_ATTEMPTS'; + +/** + * Standard AWS environment variable that selects the retry mode + */ +export const AWS_RETRY_MODE_ENV = 'AWS_RETRY_MODE'; + +/** + * The retry strategies the CLI can hand to an SDK client + */ +export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; + +/** + * Build the retry strategy for an SDK client + * + * Passing an explicit `retryStrategy` to an SDK client makes the SDK ignore the standard + * `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables, so we resolve them here + * and fall back to `defaultMaxAttempts` when the user has not set one. The backoff schedule + * is not user-configurable: there is no standard variable for it, and we tune it per client. + * + * `legacy` is accepted for compatibility with other AWS tools and treated as `standard`. + * + * @param defaultMaxAttempts - total number of attempts, including the initial call, if `AWS_MAX_ATTEMPTS` is not set + * @param backoffMs - delay in milliseconds before the given attempt + */ +export function sdkRetryStrategy(defaultMaxAttempts: number, backoffMs: (attempt: number) => number): SdkRetryStrategy { + const maxAttempts = maxAttemptsFromEnv() ?? defaultMaxAttempts; + const retryMode = process.env[AWS_RETRY_MODE_ENV]?.trim() || 'standard'; + + switch (retryMode.toLowerCase()) { + case 'standard': + case 'legacy': + // Standard mode with our own backoff schedule + return new ConfiguredRetryStrategy(maxAttempts, backoffMs); + case 'adaptive': + return new AdaptiveRetryStrategy(maxAttempts, { + maxAttempts, + backoff: { + // The SDK passes the number of completed attempts; our schedule is keyed on the next one, + // which matches how `ConfiguredRetryStrategy` calls its backoff function. + computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), + // The delay base is baked into our backoff function + setDelayBase: () => undefined, + }, + }); + default: + throw new ToolkitError('InvalidRetryConfiguration', `${AWS_RETRY_MODE_ENV} must be one of 'standard', 'adaptive' or 'legacy', got '${retryMode}'`); + } +} + +function maxAttemptsFromEnv(): number | undefined { + const raw = process.env[AWS_MAX_ATTEMPTS_ENV]?.trim(); + if (!raw) { + return undefined; + } + const value = Number(raw); + if (!Number.isInteger(value) || value < 1) { + throw new ToolkitError('InvalidRetryConfiguration', `${AWS_MAX_ATTEMPTS_ENV} must be a positive integer, got '${raw}'`); + } + return value; +} + +/** + * Build a jittered exponential-backoff delay function whose result is capped at a maximum. + * + * An uncapped exponential backoff (`base * 2^attempt`) grows without bound as the + * number of retries increases. For the retry counts we use on the CloudFormation + * client in particular, that means the SDK can spend *tens of minutes* silently + * sleeping between retries when the service returns a retryable error such as + * `InternalFailure`. To the user that looks like the CLI has hung. Capping each + * individual delay at ~15s bounds the total retry time to a few minutes at worst, + * while still giving the SDK plenty of opportunity to ride out transient server + * problems or throttling. + * + * The delay is jittered because `ConfiguredRetryStrategy` replaces the SDK's own + * jittered backoff with whatever function it is handed. Without jitter, requests + * that were throttled at the same moment retry at the same moments, and a herd of + * pollers stays a herd instead of dispersing over the retry window. We use equal + * jitter - a random point in `[floor(delay/2), delay - 1]` - rather than the SDK's + * full jitter, so that the worst case stays under the capped delay above and the + * wait before a retry never collapses to nearly zero. + * + * @param baseMs - base delay in milliseconds (used in `baseMs * 2^attempt`) + * @param capMs - maximum delay in milliseconds; any computed delay larger than this is clamped + */ +export function cappedExponentialBackoff(baseMs: number, capMs: number): (attempt: number) => number { + return (attempt: number) => { + const delay = Math.min(baseMs * (2 ** attempt), capMs); + return Math.floor(delay / 2 + Math.random() * (delay / 2)); + }; +} diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 4f9ace14d..7058f467c 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -416,11 +416,11 @@ import { import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts'; import { Upload } from '@aws-sdk/lib-storage'; import { getEndpointFromInstructions } from '@smithy/middleware-endpoint'; -import { ConfiguredRetryStrategy } from '@smithy/util-retry'; import type { WaiterResult } from '@smithy/util-waiter'; import { AccountAccessKeyCache } from './account-cache'; import type { RequestHandlerSettings } from './base-credentials'; import { cachedAsync } from './cached'; +import { cappedExponentialBackoff, sdkRetryStrategy, type SdkRetryStrategy } from './retry'; import type { ISdkLogger } from './sdk-logger'; import type { Account } from './sdk-provider'; import { traceMemberMethods } from './tracing'; @@ -488,7 +488,7 @@ export interface ConfigurationOptions { region: string; credentials: SDKv3CompatibleCredentialProvider; requestHandler: RequestHandlerSettings; - retryStrategy: ConfiguredRetryStrategy; + retryStrategy: SdkRetryStrategy; customUserAgent: Array<[name: string, value?: string]>; logger?: ISdkLogger; s3DisableBodySigning?: boolean; @@ -708,7 +708,7 @@ export class SDK { /** * STS is used to check credential validity, don't do too many retries. */ - private readonly stsRetryStrategy = new ConfiguredRetryStrategy(3, (attempt) => 100 * (2 ** attempt)); + private readonly stsRetryStrategy = sdkRetryStrategy(3, (attempt) => 100 * (2 ** attempt)); /** * Whether we have proof that the credentials have not expired @@ -738,7 +738,7 @@ export class SDK { region, credentials: credProvider, requestHandler, - retryStrategy: new ConfiguredRetryStrategy(7, cappedExponentialBackoff(300, 15_000)), + retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(300, 15_000)), logger: logger ? makeSdkLoggerSafeByBindingThis(logger) : undefined, }; this.customUserAgent = defaultCliUserAgent(); @@ -869,7 +869,7 @@ export class SDK { public cloudFormation(): ICloudFormationClient { const client = new CloudFormationClient({ ...this.config, - retryStrategy: new ConfiguredRetryStrategy(7, cappedExponentialBackoff(1000, 15_000)), + retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(1000, 15_000)), }); return { continueUpdateRollback: async ( @@ -1356,33 +1356,3 @@ function makeSdkLoggerSafeByBindingThis(logger: ISdkLogger): ISdkLogger { error: logger.error.bind(logger), }; } - -/** - * Build a jittered exponential-backoff delay function whose result is capped at a maximum. - * - * An uncapped exponential backoff (`base * 2^attempt`) grows without bound as the - * number of retries increases. For the retry counts we use on the CloudFormation - * client in particular (11 attempts), that means the SDK can spend *tens of - * minutes* silently sleeping between retries when the service returns a - * retryable error such as `InternalFailure`. To the user that looks like the - * CLI has hung. Capping each individual delay at ~15s bounds the total retry - * time to a few minutes at worst, while still giving the SDK plenty of - * opportunity to ride out transient server problems or throttling. - * - * The delay is jittered because `ConfiguredRetryStrategy` replaces the SDK's own - * jittered backoff with whatever function it is handed. Without jitter, requests - * that were throttled at the same moment retry at the same moments, and a herd of - * pollers stays a herd instead of dispersing over the retry window. We use equal - * jitter - a random point in `[floor(delay/2), delay - 1]` - rather than the SDK's - * full jitter, so that the worst case stays under the capped delay above and the - * wait before a retry never collapses to nearly zero. - * - * @param baseMs - base delay in milliseconds (used in `baseMs * 2^attempt`) - * @param capMs - maximum delay in milliseconds; any computed delay larger than this is clamped - */ -export function cappedExponentialBackoff(baseMs: number, capMs: number): (attempt: number) => number { - return (attempt: number) => { - const delay = Math.min(baseMs * (2 ** attempt), capMs); - return Math.floor(delay / 2 + Math.random() * (delay / 2)); - }; -} diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 9f3be6363..bcf408735 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -1,4 +1,5 @@ -import { cappedExponentialBackoff } from '../../../lib/api/aws-auth/private'; +import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; +import { cappedExponentialBackoff, sdkRetryStrategy } from '../../../lib/api/aws-auth/private'; /** * The top of the jitter window is the delay the schedule asks for, so mocking @@ -98,3 +99,104 @@ describe(cappedExponentialBackoff, () => { expect(backoff(2)).toBe(400); }); }); + +describe(sdkRetryStrategy, () => { + /** + * A zero-delay backoff, so retries in these tests don't actually sleep + */ + let backoffMs: jest.Mock; + const originalEnv = { AWS_MAX_ATTEMPTS: process.env.AWS_MAX_ATTEMPTS, AWS_RETRY_MODE: process.env.AWS_RETRY_MODE }; + + beforeEach(() => { + backoffMs = jest.fn().mockReturnValue(0); + delete process.env.AWS_MAX_ATTEMPTS; + delete process.env.AWS_RETRY_MODE; + }); + + afterEach(() => { + for (const [key, value] of Object.entries(originalEnv)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + }); + + /** + * Ask the strategy for a retry after one failed attempt + */ + async function retryOnce(strategy: ConfiguredRetryStrategy | AdaptiveRetryStrategy) { + const token = await strategy.acquireInitialRetryToken('scope'); + return strategy.refreshRetryTokenForRetry(token as any, { errorType: 'TRANSIENT' } as any); + } + + test('uses the defaults when no environment variables are set', async () => { + const strategy = sdkRetryStrategy(7, backoffMs); + + expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); + await expect(strategy.maxAttemptsProvider()).resolves.toBe(7); + await retryOnce(strategy); + expect(backoffMs).toHaveBeenCalledWith(1); + }); + + test('treats empty environment variables as unset', async () => { + process.env.AWS_MAX_ATTEMPTS = ''; + process.env.AWS_RETRY_MODE = ' '; + const strategy = sdkRetryStrategy(7, backoffMs); + + expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); + await expect(strategy.maxAttemptsProvider()).resolves.toBe(7); + }); + + test('AWS_MAX_ATTEMPTS overrides the default number of attempts and keeps our backoff', async () => { + process.env.AWS_MAX_ATTEMPTS = '2'; + const strategy = sdkRetryStrategy(7, backoffMs); + + await expect(strategy.maxAttemptsProvider()).resolves.toBe(2); + await retryOnce(strategy); + expect(backoffMs).toHaveBeenCalled(); + }); + + test('AWS_MAX_ATTEMPTS=1 disables retries', async () => { + process.env.AWS_MAX_ATTEMPTS = '1'; + const strategy = sdkRetryStrategy(7, backoffMs); + + await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); + }); + + test.each(['0', '-1', '1.5', 'abc'])('rejects invalid AWS_MAX_ATTEMPTS %p', (value) => { + process.env.AWS_MAX_ATTEMPTS = value; + expect(() => sdkRetryStrategy(7, backoffMs)).toThrow(/AWS_MAX_ATTEMPTS must be a positive integer/); + }); + + test.each(['standard', 'legacy', 'STANDARD'])('AWS_RETRY_MODE=%s uses the standard strategy', (mode) => { + process.env.AWS_RETRY_MODE = mode; + expect(sdkRetryStrategy(7, backoffMs)).toBeInstanceOf(ConfiguredRetryStrategy); + }); + + test('AWS_RETRY_MODE=adaptive uses the adaptive strategy with our attempts and backoff', async () => { + process.env.AWS_RETRY_MODE = 'adaptive'; + const strategy = sdkRetryStrategy(5, backoffMs); + + expect(strategy).toBeInstanceOf(AdaptiveRetryStrategy); + await expect(strategy.maxAttemptsProvider()).resolves.toBe(5); + await retryOnce(strategy); + // Same attempt numbering as ConfiguredRetryStrategy + expect(backoffMs).toHaveBeenCalledWith(1); + }); + + test('AWS_RETRY_MODE=adaptive honours AWS_MAX_ATTEMPTS', async () => { + process.env.AWS_RETRY_MODE = 'adaptive'; + process.env.AWS_MAX_ATTEMPTS = '1'; + const strategy = sdkRetryStrategy(7, backoffMs); + + await expect(strategy.maxAttemptsProvider()).resolves.toBe(1); + await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); + }); + + test('rejects an unknown AWS_RETRY_MODE', () => { + process.env.AWS_RETRY_MODE = 'aggressive'; + expect(() => sdkRetryStrategy(7, backoffMs)).toThrow(/AWS_RETRY_MODE must be one of/); + }); +}); From 91032f53bd6db91699d7e9ff7d6a1a4edf5575ad Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Tue, 24 Nov 2026 10:37:47 -0500 Subject: [PATCH 02/17] feat(toolkit-lib): read SDK retry settings from the active profile In addition to the AWS_MAX_ATTEMPTS and AWS_RETRY_MODE environment variables, read max_attempts and retry_mode from the active profile in the shared config files, the way the AWS CLI does. Environment variables take precedence, and ~/.aws/config takes precedence over ~/.aws/credentials. Unlike region, there is no fallback to the default profile. BaseCredentials.awsCliCompatible() resolves the settings using the same profile as credentials and region, and returns them in a new optional SdkBaseConfig.retry field. SdkProvider passes them to every SDK. Custom and none() base credentials fall back to the environment variables only. --- .../lib/api/aws-auth/awscli-compatible.ts | 17 +- .../lib/api/aws-auth/base-credentials.ts | 32 ++- .../toolkit-lib/lib/api/aws-auth/retry.ts | 131 +++++++++--- .../lib/api/aws-auth/sdk-provider.ts | 16 +- .../toolkit-lib/lib/api/aws-auth/sdk.ts | 10 +- .../toolkit-lib/lib/toolkit/toolkit.ts | 1 + .../api/aws-auth/awscli-compatible.test.ts | 43 ++++ .../test/api/aws-auth/sdk-provider.test.ts | 33 +++ .../test/api/aws-auth/sdk-retry.test.ts | 195 +++++++++++++----- 9 files changed, 385 insertions(+), 93 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index f4901b6c1..7714ed55a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -4,9 +4,10 @@ import type { SDKv3CompatibleCredentialProvider } from '@aws-cdk/cli-plugin-cont import { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers'; import { MetadataService } from '@aws-sdk/ec2-metadata-service'; import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; -import type { RequestHandlerSettings } from './base-credentials'; +import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; import { isEc2Instance } from './ec2-detection'; import { makeCachingProvider } from './provider-caching'; +import { retrySettingsFromEnvAndProfile } from './retry'; import type { ISdkLogger } from './sdk-logger'; import { AuthenticationError } from '../../toolkit/toolkit-error'; import { IO, type IoHelper } from '../io/private'; @@ -36,13 +37,14 @@ export class AwsCliCompatible { public async baseConfig( profile?: string, region?: string, - ): Promise<{ credentialProvider: SDKv3CompatibleCredentialProvider; defaultRegion: string }> { + ): Promise<{ credentialProvider: SDKv3CompatibleCredentialProvider; defaultRegion: string; retry: SdkRetrySettings }> { const credentialProvider = await this.credentialChainBuilder({ profile, logger: this.logger, }); const defaultRegion = region ?? await this.region(profile); - return { credentialProvider, defaultRegion }; + const retry = await retrySettingsFromEnvAndProfile(resolveProfile(profile)); + return { credentialProvider, defaultRegion, retry }; } /** @@ -156,7 +158,7 @@ export class AwsCliCompatible { */ public async region(maybeProfile?: string): Promise { const defaultRegion = 'us-east-1'; - const profile = maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default'; + const profile = resolveProfile(maybeProfile); const region = process.env.AWS_REGION || @@ -297,3 +299,10 @@ export function sdkRequestHandler(agent?: Agent): RequestHandlerSettings { httpAgent: agent, }; } + +/** + * The profile the AWS CLI would use: the given one, then the environment, then `default` + */ +function resolveProfile(maybeProfile?: string): string { + return maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default'; +} diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts index e12247419..fc099e5c5 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts @@ -45,6 +45,34 @@ export interface SdkBaseConfig { * The default region to use for SDK calls. */ readonly defaultRegion?: string; + + /** + * Retry settings configured by the user, overriding the toolkit's per-client defaults + * + * The backoff schedule between attempts is not configurable. + * + * @default - only the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables apply + */ + readonly retry?: SdkRetrySettings; +} + +/** + * Retry settings for SDK calls + */ +export interface SdkRetrySettings { + /** + * Total number of attempts, including the initial call + * + * @default - a per-client default chosen by the toolkit + */ + readonly maxAttempts?: number; + + /** + * The retry mode + * + * @default 'standard' + */ + readonly mode?: 'standard' | 'adaptive'; } export interface SdkBaseClientConfig { @@ -83,9 +111,9 @@ export class BaseCredentials { } /** - * Obtain base credentials and base region the same way the AWS CLI would + * Obtain base credentials, base region and retry settings the same way the AWS CLI would * - * Credentials and region will be read from the environment first, falling back + * Credentials, region and retry settings will be read from the environment first, falling back * to INI files or other sources if available. * * The profile name is configurable. diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index dace938d5..3883c4ad9 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -1,4 +1,6 @@ +import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; +import type { SdkRetrySettings } from './base-credentials'; import { ToolkitError } from '../../toolkit/toolkit-error'; /** @@ -11,6 +13,16 @@ export const AWS_MAX_ATTEMPTS_ENV = 'AWS_MAX_ATTEMPTS'; */ export const AWS_RETRY_MODE_ENV = 'AWS_RETRY_MODE'; +/** + * Shared config file key equivalent to `AWS_MAX_ATTEMPTS` + */ +const MAX_ATTEMPTS_CONFIG_KEY = 'max_attempts'; + +/** + * Shared config file key equivalent to `AWS_RETRY_MODE` + */ +const RETRY_MODE_CONFIG_KEY = 'retry_mode'; + /** * The retry strategies the CLI can hand to an SDK client */ @@ -19,53 +31,106 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; /** * Build the retry strategy for an SDK client * - * Passing an explicit `retryStrategy` to an SDK client makes the SDK ignore the standard - * `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables, so we resolve them here - * and fall back to `defaultMaxAttempts` when the user has not set one. The backoff schedule - * is not user-configurable: there is no standard variable for it, and we tune it per client. - * - * `legacy` is accepted for compatibility with other AWS tools and treated as `standard`. + * Passing an explicit `retryStrategy` to an SDK client makes the SDK ignore the user's retry + * configuration, so we apply the user's settings here and fall back to `defaultMaxAttempts` + * when they have not set one. The backoff schedule is not user-configurable: there is no + * standard setting for it, and we tune it per client. * - * @param defaultMaxAttempts - total number of attempts, including the initial call, if `AWS_MAX_ATTEMPTS` is not set + * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt + * @param settings - the user's retry settings, see `retrySettingsFromEnv` and `retrySettingsFromEnvAndProfile` */ -export function sdkRetryStrategy(defaultMaxAttempts: number, backoffMs: (attempt: number) => number): SdkRetryStrategy { - const maxAttempts = maxAttemptsFromEnv() ?? defaultMaxAttempts; - const retryMode = process.env[AWS_RETRY_MODE_ENV]?.trim() || 'standard'; +export function sdkRetryStrategy( + defaultMaxAttempts: number, + backoffMs: (attempt: number) => number, + settings: SdkRetrySettings, +): SdkRetryStrategy { + const maxAttempts = settings.maxAttempts ?? defaultMaxAttempts; - switch (retryMode.toLowerCase()) { - case 'standard': - case 'legacy': - // Standard mode with our own backoff schedule - return new ConfiguredRetryStrategy(maxAttempts, backoffMs); - case 'adaptive': - return new AdaptiveRetryStrategy(maxAttempts, { - maxAttempts, - backoff: { - // The SDK passes the number of completed attempts; our schedule is keyed on the next one, - // which matches how `ConfiguredRetryStrategy` calls its backoff function. - computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), - // The delay base is baked into our backoff function - setDelayBase: () => undefined, - }, - }); - default: - throw new ToolkitError('InvalidRetryConfiguration', `${AWS_RETRY_MODE_ENV} must be one of 'standard', 'adaptive' or 'legacy', got '${retryMode}'`); + if (settings.mode === 'adaptive') { + return new AdaptiveRetryStrategy(maxAttempts, { + maxAttempts, + backoff: { + // The SDK passes the number of completed attempts; our schedule is keyed on the next one, + // which matches how `ConfiguredRetryStrategy` calls its backoff function. + computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), + // The delay base is baked into our backoff function + setDelayBase: () => undefined, + }, + }); } + + // Standard mode with our own backoff schedule + return new ConfiguredRetryStrategy(maxAttempts, backoffMs); +} + +/** + * Read the user's retry settings from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables + */ +export function retrySettingsFromEnv(): SdkRetrySettings { + return { + maxAttempts: parseMaxAttempts(process.env[AWS_MAX_ATTEMPTS_ENV], AWS_MAX_ATTEMPTS_ENV), + mode: parseRetryMode(process.env[AWS_RETRY_MODE_ENV], AWS_RETRY_MODE_ENV), + }; +} + +/** + * Read the user's retry settings the way the AWS CLI does + * + * Each setting is taken from its environment variable first, then from the given profile in the + * shared config files. Like the SDK, a value in `~/.aws/config` takes precedence over one in + * `~/.aws/credentials`, and there is no fallback to the `default` profile. + */ +export async function retrySettingsFromEnvAndProfile(profile: string): Promise { + const fromEnv = retrySettingsFromEnv(); + const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true }); + const fromProfile = (key: string): string | undefined => + sharedFiles.configFile?.[profile]?.[key] ?? sharedFiles.credentialsFile?.[profile]?.[key]; + + return { + maxAttempts: fromEnv.maxAttempts + ?? parseMaxAttempts(fromProfile(MAX_ATTEMPTS_CONFIG_KEY), `'${MAX_ATTEMPTS_CONFIG_KEY}' in profile '${profile}'`), + mode: fromEnv.mode + ?? parseRetryMode(fromProfile(RETRY_MODE_CONFIG_KEY), `'${RETRY_MODE_CONFIG_KEY}' in profile '${profile}'`), + }; } -function maxAttemptsFromEnv(): number | undefined { - const raw = process.env[AWS_MAX_ATTEMPTS_ENV]?.trim(); - if (!raw) { +/** + * @param source - where the value came from, for the error message + */ +function parseMaxAttempts(raw: string | undefined, source: string): number | undefined { + const trimmed = raw?.trim(); + if (!trimmed) { return undefined; } - const value = Number(raw); + const value = Number(trimmed); if (!Number.isInteger(value) || value < 1) { - throw new ToolkitError('InvalidRetryConfiguration', `${AWS_MAX_ATTEMPTS_ENV} must be a positive integer, got '${raw}'`); + throw new ToolkitError('InvalidRetryConfiguration', `${source} must be a positive integer, got '${trimmed}'`); } return value; } +/** + * `legacy` is accepted for compatibility with other AWS tools and treated as `standard`. + * + * @param source - where the value came from, for the error message + */ +function parseRetryMode(raw: string | undefined, source: string): SdkRetrySettings['mode'] { + const trimmed = raw?.trim(); + if (!trimmed) { + return undefined; + } + switch (trimmed.toLowerCase()) { + case 'standard': + case 'legacy': + return 'standard'; + case 'adaptive': + return 'adaptive'; + default: + throw new ToolkitError('InvalidRetryConfiguration', `${source} must be one of 'standard', 'adaptive' or 'legacy', got '${trimmed}'`); + } +} + /** * Build a jittered exponential-backoff delay function whose result is capped at a maximum. * diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts index 16333f0ad..f4793e789 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts @@ -6,10 +6,11 @@ import type { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema'; import type { AssumeRoleCommandInput } from '@aws-sdk/client-sts'; import { fromTemporaryCredentials } from '@aws-sdk/credential-providers'; import { AwsCliCompatible } from './awscli-compatible'; -import type { RequestHandlerSettings } from './base-credentials'; +import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; import { cached } from './cached'; import { CredentialPlugins } from './credential-plugins'; import { makeCachingProvider } from './provider-caching'; +import { retrySettingsFromEnv } from './retry'; import { SDK } from './sdk'; import type { UserAgentMetadata } from './sdk'; import type { ISdkLogger } from './sdk-logger'; @@ -51,6 +52,13 @@ export interface SdkProviderOptions { * @default - no additional tokens */ readonly userAgentMetadata?: UserAgentMetadata[]; + + /** + * Retry settings configured by the user + * + * @default - read from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables + */ + readonly retry?: SdkRetrySettings; } const CACHED_ACCOUNT = Symbol('cached_account'); @@ -121,7 +129,7 @@ export class SdkProvider { public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions, profile?: string, region?: string) { callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger); const config = await new AwsCliCompatible(options.ioHelper, options.requestHandler ?? {}, options.logger).baseConfig(profile, region); - return new SdkProvider(config.credentialProvider, config.defaultRegion, options); + return new SdkProvider(config.credentialProvider, config.defaultRegion, { ...options, retry: options.retry ?? config.retry }); } public readonly defaultRegion: string; @@ -131,6 +139,7 @@ export class SdkProvider { private readonly ioHelper: IoHelper; private readonly logger?: ISdkLogger; private readonly userAgentMetadata: UserAgentMetadata[]; + private readonly retrySettings: SdkRetrySettings; public constructor( defaultCredentialProvider: SDKv3CompatibleCredentialProvider, @@ -143,6 +152,7 @@ export class SdkProvider { this.ioHelper = options.ioHelper; this.logger = options.logger; this.userAgentMetadata = options.userAgentMetadata ?? []; + this.retrySettings = options.retry ?? retrySettingsFromEnv(); this.plugins = new CredentialPlugins(options.pluginHost ?? new PluginHost(), this.ioHelper); } @@ -415,7 +425,7 @@ export class SdkProvider { credProvider: SDKv3CompatibleCredentialProvider, region: string, ) { - const sdk = new SDK(credProvider, region, this.requestHandler, this.ioHelper, this.logger); + const sdk = new SDK(credProvider, region, this.requestHandler, this.ioHelper, this.logger, this.retrySettings); for (const metadata of this.userAgentMetadata) { sdk.appendCustomUserAgent(metadata); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 7058f467c..838014935 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -418,7 +418,7 @@ import { Upload } from '@aws-sdk/lib-storage'; import { getEndpointFromInstructions } from '@smithy/middleware-endpoint'; import type { WaiterResult } from '@smithy/util-waiter'; import { AccountAccessKeyCache } from './account-cache'; -import type { RequestHandlerSettings } from './base-credentials'; +import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; import { cachedAsync } from './cached'; import { cappedExponentialBackoff, sdkRetryStrategy, type SdkRetryStrategy } from './retry'; import type { ISdkLogger } from './sdk-logger'; @@ -708,7 +708,7 @@ export class SDK { /** * STS is used to check credential validity, don't do too many retries. */ - private readonly stsRetryStrategy = sdkRetryStrategy(3, (attempt) => 100 * (2 ** attempt)); + private readonly stsRetryStrategy: SdkRetryStrategy; /** * Whether we have proof that the credentials have not expired @@ -730,6 +730,7 @@ export class SDK { requestHandler: RequestHandlerSettings, ioHelper: IoHelper, logger?: ISdkLogger, + private readonly retrySettings: SdkRetrySettings = {}, ) { const debugFn = async (msg: string) => ioHelper.defaults.debug(msg); this.accountCache = new AccountAccessKeyCache(AccountAccessKeyCache.DEFAULT_PATH, debugFn); @@ -738,9 +739,10 @@ export class SDK { region, credentials: credProvider, requestHandler, - retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(300, 15_000)), + retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(300, 15_000), retrySettings), logger: logger ? makeSdkLoggerSafeByBindingThis(logger) : undefined, }; + this.stsRetryStrategy = sdkRetryStrategy(3, (attempt) => 100 * (2 ** attempt), retrySettings); this.customUserAgent = defaultCliUserAgent(); this.currentRegion = region; } @@ -869,7 +871,7 @@ export class SDK { public cloudFormation(): ICloudFormationClient { const client = new CloudFormationClient({ ...this.config, - retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(1000, 15_000)), + retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(1000, 15_000), this.retrySettings), }); return { continueUpdateRollback: async ( diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 104cc7ec1..7f49ee9d6 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -254,6 +254,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { logger: new IoHostSdkLogger(ioHelper), pluginHost: this.pluginHost, requestHandler: clientConfig.requestHandler, + retry: config.retry, }); } diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts index 3987aa075..7b4f1906d 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts @@ -323,6 +323,49 @@ describe('AwsCliCompatible.baseConfig region override', () => { }); }); +describe('AwsCliCompatible.baseConfig retry settings', () => { + let workdir: string; + const originalProfile = process.env.AWS_PROFILE; + + beforeEach(() => { + workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'awscli-compatible.test')); + const configPath = path.join(workdir, 'config'); + fs.writeFileSync(configPath, '[default]\nmax_attempts = 2\n[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + process.env.AWS_CONFIG_FILE = configPath; + process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; + process.env.AWS_REGION = 'us-east-1'; + delete process.env.AWS_PROFILE; + delete process.env.AWS_DEFAULT_PROFILE; + delete process.env.AWS_MAX_ATTEMPTS; + delete process.env.AWS_RETRY_MODE; + }); + + afterEach(() => { + fs.removeSync(workdir); + if (originalProfile === undefined) { + delete process.env.AWS_PROFILE; + } else { + process.env.AWS_PROFILE = originalProfile; + } + }); + + test('reads retry settings from the given profile', async () => { + const config = await new AwsCliCompatible(ioHelper, {}).baseConfig('ci'); + expect(config.retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); + + test('reads retry settings from AWS_PROFILE when no profile is given', async () => { + process.env.AWS_PROFILE = 'ci'; + const config = await new AwsCliCompatible(ioHelper, {}).baseConfig(); + expect(config.retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); + + test('reads retry settings from the default profile otherwise', async () => { + const config = await new AwsCliCompatible(ioHelper, {}).baseConfig(); + expect(config.retry).toEqual({ maxAttempts: 2, mode: undefined }); + }); +}); + describe('Session token', () => { beforeEach(() => { process.env.AWS_ACCESS_KEY_ID = 'foo'; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts index 9568bb641..792afaac4 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts @@ -780,6 +780,39 @@ test('SDKs created by the provider get the userAgentMetadata', () => { expect((sdk as any).userAgentMetadata).toEqual(new Map([['agent', 'kiro'], ['ci', 'github-actions']])); }); +test('SDKs created by the provider use the retry settings', async () => { + // GIVEN + const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper, retry: { maxAttempts: 2, mode: 'adaptive' } }); + + // WHEN + const sdk = provider._makeSdk(jest.fn(), 'rgn'); + + // THEN + expect(sdkConfig(sdk).retryStrategy.mode).toBe('adaptive'); + await expect(sdkConfig(sdk).retryStrategy.maxAttemptsProvider()).resolves.toBe(2); +}); + +test('the provider reads retry settings from the environment if none are given', async () => { + // GIVEN + const original = process.env.AWS_MAX_ATTEMPTS; + process.env.AWS_MAX_ATTEMPTS = '2'; + try { + const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper }); + + // WHEN + const sdk = provider._makeSdk(jest.fn(), 'rgn'); + + // THEN + await expect(sdkConfig(sdk).retryStrategy.maxAttemptsProvider()).resolves.toBe(2); + } finally { + if (original === undefined) { + delete process.env.AWS_MAX_ATTEMPTS; + } else { + process.env.AWS_MAX_ATTEMPTS = original; + } + } +}); + /** * Use object hackery to get the credentials out of the SDK object */ diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index bcf408735..4a2010646 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -1,5 +1,13 @@ +import * as os from 'os'; +import * as path from 'path'; import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; -import { cappedExponentialBackoff, sdkRetryStrategy } from '../../../lib/api/aws-auth/private'; +import * as fs from 'fs-extra'; +import { + cappedExponentialBackoff, + retrySettingsFromEnv, + retrySettingsFromEnvAndProfile, + sdkRetryStrategy, +} from '../../../lib/api/aws-auth/private'; /** * The top of the jitter window is the delay the schedule asks for, so mocking @@ -16,10 +24,29 @@ function scheduled(attempt: number, baseMs = 1000, capMs = 15_000) { return Math.min(baseMs * (2 ** attempt), capMs); } +const ENV_VARS = ['AWS_MAX_ATTEMPTS', 'AWS_RETRY_MODE', 'AWS_CONFIG_FILE', 'AWS_SHARED_CREDENTIALS_FILE']; +const originalEnv = Object.fromEntries(ENV_VARS.map((key) => [key, process.env[key]])); + +beforeEach(() => { + delete process.env.AWS_MAX_ATTEMPTS; + delete process.env.AWS_RETRY_MODE; + // make sure we don't read the developer's own config files + process.env.AWS_CONFIG_FILE = '/dev/null'; + process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; +}); + afterEach(() => { // `clearMocks` does not restore a spy's implementation, and two tests below rely // on real randomness. jest.restoreAllMocks(); + + for (const [key, value] of Object.entries(originalEnv)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } }); describe(cappedExponentialBackoff, () => { @@ -105,22 +132,9 @@ describe(sdkRetryStrategy, () => { * A zero-delay backoff, so retries in these tests don't actually sleep */ let backoffMs: jest.Mock; - const originalEnv = { AWS_MAX_ATTEMPTS: process.env.AWS_MAX_ATTEMPTS, AWS_RETRY_MODE: process.env.AWS_RETRY_MODE }; beforeEach(() => { backoffMs = jest.fn().mockReturnValue(0); - delete process.env.AWS_MAX_ATTEMPTS; - delete process.env.AWS_RETRY_MODE; - }); - - afterEach(() => { - for (const [key, value] of Object.entries(originalEnv)) { - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } }); /** @@ -131,8 +145,8 @@ describe(sdkRetryStrategy, () => { return strategy.refreshRetryTokenForRetry(token as any, { errorType: 'TRANSIENT' } as any); } - test('uses the defaults when no environment variables are set', async () => { - const strategy = sdkRetryStrategy(7, backoffMs); + test('uses the defaults when the user has not configured retries', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, {}); expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); await expect(strategy.maxAttemptsProvider()).resolves.toBe(7); @@ -140,44 +154,26 @@ describe(sdkRetryStrategy, () => { expect(backoffMs).toHaveBeenCalledWith(1); }); - test('treats empty environment variables as unset', async () => { - process.env.AWS_MAX_ATTEMPTS = ''; - process.env.AWS_RETRY_MODE = ' '; - const strategy = sdkRetryStrategy(7, backoffMs); - - expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); - await expect(strategy.maxAttemptsProvider()).resolves.toBe(7); - }); - - test('AWS_MAX_ATTEMPTS overrides the default number of attempts and keeps our backoff', async () => { - process.env.AWS_MAX_ATTEMPTS = '2'; - const strategy = sdkRetryStrategy(7, backoffMs); + test('maxAttempts overrides the default number of attempts and keeps our backoff', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 2 }); await expect(strategy.maxAttemptsProvider()).resolves.toBe(2); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalled(); }); - test('AWS_MAX_ATTEMPTS=1 disables retries', async () => { - process.env.AWS_MAX_ATTEMPTS = '1'; - const strategy = sdkRetryStrategy(7, backoffMs); + test('maxAttempts of 1 disables retries', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 1 }); await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); }); - test.each(['0', '-1', '1.5', 'abc'])('rejects invalid AWS_MAX_ATTEMPTS %p', (value) => { - process.env.AWS_MAX_ATTEMPTS = value; - expect(() => sdkRetryStrategy(7, backoffMs)).toThrow(/AWS_MAX_ATTEMPTS must be a positive integer/); + test('standard mode uses the standard strategy', () => { + expect(sdkRetryStrategy(7, backoffMs, { mode: 'standard' })).toBeInstanceOf(ConfiguredRetryStrategy); }); - test.each(['standard', 'legacy', 'STANDARD'])('AWS_RETRY_MODE=%s uses the standard strategy', (mode) => { - process.env.AWS_RETRY_MODE = mode; - expect(sdkRetryStrategy(7, backoffMs)).toBeInstanceOf(ConfiguredRetryStrategy); - }); - - test('AWS_RETRY_MODE=adaptive uses the adaptive strategy with our attempts and backoff', async () => { - process.env.AWS_RETRY_MODE = 'adaptive'; - const strategy = sdkRetryStrategy(5, backoffMs); + test('adaptive mode uses the adaptive strategy with our attempts and backoff', async () => { + const strategy = sdkRetryStrategy(5, backoffMs, { mode: 'adaptive' }); expect(strategy).toBeInstanceOf(AdaptiveRetryStrategy); await expect(strategy.maxAttemptsProvider()).resolves.toBe(5); @@ -186,17 +182,122 @@ describe(sdkRetryStrategy, () => { expect(backoffMs).toHaveBeenCalledWith(1); }); - test('AWS_RETRY_MODE=adaptive honours AWS_MAX_ATTEMPTS', async () => { - process.env.AWS_RETRY_MODE = 'adaptive'; - process.env.AWS_MAX_ATTEMPTS = '1'; - const strategy = sdkRetryStrategy(7, backoffMs); + test('adaptive mode honours maxAttempts', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, { mode: 'adaptive', maxAttempts: 1 }); await expect(strategy.maxAttemptsProvider()).resolves.toBe(1); await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); }); +}); + +describe(retrySettingsFromEnv, () => { + test('returns nothing when no environment variables are set', () => { + expect(retrySettingsFromEnv()).toEqual({ maxAttempts: undefined, mode: undefined }); + }); + + test('treats empty environment variables as unset', () => { + process.env.AWS_MAX_ATTEMPTS = ''; + process.env.AWS_RETRY_MODE = ' '; + + expect(retrySettingsFromEnv()).toEqual({ maxAttempts: undefined, mode: undefined }); + }); + + test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', () => { + process.env.AWS_MAX_ATTEMPTS = '2'; + process.env.AWS_RETRY_MODE = 'adaptive'; + + expect(retrySettingsFromEnv()).toEqual({ maxAttempts: 2, mode: 'adaptive' }); + }); + + test.each(['0', '-1', '1.5', 'abc'])('rejects invalid AWS_MAX_ATTEMPTS %p', (value) => { + process.env.AWS_MAX_ATTEMPTS = value; + + expect(() => retrySettingsFromEnv()).toThrow(/AWS_MAX_ATTEMPTS must be a positive integer/); + }); + + test.each(['standard', 'legacy', 'STANDARD'])('AWS_RETRY_MODE=%s means standard mode', (mode) => { + process.env.AWS_RETRY_MODE = mode; + + expect(retrySettingsFromEnv().mode).toBe('standard'); + }); test('rejects an unknown AWS_RETRY_MODE', () => { process.env.AWS_RETRY_MODE = 'aggressive'; - expect(() => sdkRetryStrategy(7, backoffMs)).toThrow(/AWS_RETRY_MODE must be one of/); + + expect(() => retrySettingsFromEnv()).toThrow(/AWS_RETRY_MODE must be one of/); + }); +}); + +describe(retrySettingsFromEnvAndProfile, () => { + let workdir: string; + + beforeEach(() => { + workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-retry.test')); + }); + + afterEach(() => { + fs.removeSync(workdir); + }); + + function writeConfigFile(contents: string) { + const configPath = path.join(workdir, 'config'); + fs.writeFileSync(configPath, contents); + process.env.AWS_CONFIG_FILE = configPath; + } + + function writeCredentialsFile(contents: string) { + const credentialsPath = path.join(workdir, 'credentials'); + fs.writeFileSync(credentialsPath, contents); + process.env.AWS_SHARED_CREDENTIALS_FILE = credentialsPath; + } + + test('reads settings from the profile in the config file', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); + + test('reads settings from the default profile', async () => { + writeConfigFile('[default]\nmax_attempts = 4\n'); + + await expect(retrySettingsFromEnvAndProfile('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); + }); + + test('reads settings from the credentials file', async () => { + writeCredentialsFile('[ci]\nmax_attempts = 4\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); + }); + + test('the config file takes precedence over the credentials file', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\n'); + writeCredentialsFile('[ci]\nmax_attempts = 9\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); + }); + + test('does not fall back to the default profile', async () => { + writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + }); + + test('environment variables take precedence over the profile, per setting', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + process.env.AWS_MAX_ATTEMPTS = '2'; + + await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + }); + + test('rejects an invalid max_attempts and names the profile', async () => { + writeConfigFile('[profile ci]\nmax_attempts = lots\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).rejects.toThrow("'max_attempts' in profile 'ci' must be a positive integer, got 'lots'"); + }); + + test('rejects an invalid retry_mode and names the profile', async () => { + writeConfigFile('[profile ci]\nretry_mode = aggressive\n'); + + await expect(retrySettingsFromEnvAndProfile('ci')).rejects.toThrow(/'retry_mode' in profile 'ci' must be one of/); }); }); From 12b581cb50b93f382e6025b77668fd16f19ee36f Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Fri, 27 Nov 2026 19:55:37 -0500 Subject: [PATCH 03/17] refactor(toolkit-lib): parse retry settings like the SDK and read them from the config file only Parse max_attempts / AWS_MAX_ATTEMPTS with parseInt and only reject values that are not a number, and treat any retry mode other than 'adaptive' as standard, matching the JavaScript SDK. Previously we rejected values the SDK accepts, such as '1.5', '0' or 'legacy'. Read retry_mode and max_attempts from ~/.aws/config only. The credentials file may only hold credentials, and the retry settings are documented for the config file only. This supersedes the config-over-credentials precedence described in the previous commit. Split the profile lookup into retrySettingsFromConfig(), and rename retrySettingsFromEnvAndProfile() to retrySettings(). --- .../lib/api/aws-auth/awscli-compatible.ts | 4 +- .../toolkit-lib/lib/api/aws-auth/retry.ts | 73 ++++++++------ .../test/api/aws-auth/sdk-retry.test.ts | 99 ++++++++++--------- 3 files changed, 95 insertions(+), 81 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index 7714ed55a..6397201fd 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -7,7 +7,7 @@ import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; import { isEc2Instance } from './ec2-detection'; import { makeCachingProvider } from './provider-caching'; -import { retrySettingsFromEnvAndProfile } from './retry'; +import { retrySettings } from './retry'; import type { ISdkLogger } from './sdk-logger'; import { AuthenticationError } from '../../toolkit/toolkit-error'; import { IO, type IoHelper } from '../io/private'; @@ -43,7 +43,7 @@ export class AwsCliCompatible { logger: this.logger, }); const defaultRegion = region ?? await this.region(profile); - const retry = await retrySettingsFromEnvAndProfile(resolveProfile(profile)); + const retry = await retrySettings(resolveProfile(profile)); return { credentialProvider, defaultRegion, retry }; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 3883c4ad9..85b2af90f 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -38,7 +38,7 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; * * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt - * @param settings - the user's retry settings, see `retrySettingsFromEnv` and `retrySettingsFromEnvAndProfile` + * @param settings - the user's retry settings, see `retrySettingsFromEnv` and `retrySettings` */ export function sdkRetryStrategy( defaultMaxAttempts: number, @@ -70,65 +70,74 @@ export function sdkRetryStrategy( export function retrySettingsFromEnv(): SdkRetrySettings { return { maxAttempts: parseMaxAttempts(process.env[AWS_MAX_ATTEMPTS_ENV], AWS_MAX_ATTEMPTS_ENV), - mode: parseRetryMode(process.env[AWS_RETRY_MODE_ENV], AWS_RETRY_MODE_ENV), + mode: parseRetryMode(process.env[AWS_RETRY_MODE_ENV]), }; } /** * Read the user's retry settings the way the AWS CLI does * - * Each setting is taken from its environment variable first, then from the given profile in the - * shared config files. Like the SDK, a value in `~/.aws/config` takes precedence over one in - * `~/.aws/credentials`, and there is no fallback to the `default` profile. + * Each setting is taken from its environment variable first, then from the given profile + * in the shared config files. */ -export async function retrySettingsFromEnvAndProfile(profile: string): Promise { +export async function retrySettings(profile: string): Promise { const fromEnv = retrySettingsFromEnv(); - const sharedFiles = await loadSharedConfigFiles({ ignoreCache: true }); - const fromProfile = (key: string): string | undefined => - sharedFiles.configFile?.[profile]?.[key] ?? sharedFiles.credentialsFile?.[profile]?.[key]; + const fromConfig = await retrySettingsFromConfig(profile); + return { + maxAttempts: fromEnv.maxAttempts ?? fromConfig.maxAttempts, + mode: fromEnv.mode ?? fromConfig.mode, + }; +} + +/** + * Read the user's retry settings from the given profile in the shared config file + * + * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the + * retry settings are documented for the config file only. There is no fallback to the + * `default` profile. + * + * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html + */ +export async function retrySettingsFromConfig(profile: string): Promise { + const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); + const fromProfile = (key: string): string | undefined => configFile?.[profile]?.[key]; return { - maxAttempts: fromEnv.maxAttempts - ?? parseMaxAttempts(fromProfile(MAX_ATTEMPTS_CONFIG_KEY), `'${MAX_ATTEMPTS_CONFIG_KEY}' in profile '${profile}'`), - mode: fromEnv.mode - ?? parseRetryMode(fromProfile(RETRY_MODE_CONFIG_KEY), `'${RETRY_MODE_CONFIG_KEY}' in profile '${profile}'`), + maxAttempts: parseMaxAttempts(fromProfile(MAX_ATTEMPTS_CONFIG_KEY), `'${MAX_ATTEMPTS_CONFIG_KEY}' in profile '${profile}'`), + mode: parseRetryMode(fromProfile(RETRY_MODE_CONFIG_KEY)), }; } /** + * Parse a max attempts value the way the SDK does + * + * The value goes through `parseInt`, so `1.5` means 1. Values below 2 disable retries. + * Only a value that is not a number at all is an error. + * * @param source - where the value came from, for the error message */ function parseMaxAttempts(raw: string | undefined, source: string): number | undefined { - const trimmed = raw?.trim(); - if (!trimmed) { + if (!raw) { return undefined; } - const value = Number(trimmed); - if (!Number.isInteger(value) || value < 1) { - throw new ToolkitError('InvalidRetryConfiguration', `${source} must be a positive integer, got '${trimmed}'`); + const value = parseInt(raw); + if (Number.isNaN(value)) { + throw new ToolkitError('InvalidRetryConfiguration', `${source} must be a number, got '${raw}'`); } return value; } /** - * `legacy` is accepted for compatibility with other AWS tools and treated as `standard`. + * Parse a retry mode value the way the SDK does * - * @param source - where the value came from, for the error message + * Only `adaptive` (case-sensitive) selects adaptive mode; any other value, including + * `legacy` and unknown modes, means standard mode. */ -function parseRetryMode(raw: string | undefined, source: string): SdkRetrySettings['mode'] { - const trimmed = raw?.trim(); - if (!trimmed) { +function parseRetryMode(raw: string | undefined): SdkRetrySettings['mode'] { + if (!raw) { return undefined; } - switch (trimmed.toLowerCase()) { - case 'standard': - case 'legacy': - return 'standard'; - case 'adaptive': - return 'adaptive'; - default: - throw new ToolkitError('InvalidRetryConfiguration', `${source} must be one of 'standard', 'adaptive' or 'legacy', got '${trimmed}'`); - } + return raw === 'adaptive' ? 'adaptive' : 'standard'; } /** diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 4a2010646..527ff9bcd 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -4,8 +4,9 @@ import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-ret import * as fs from 'fs-extra'; import { cappedExponentialBackoff, + retrySettings, + retrySettingsFromConfig, retrySettingsFromEnv, - retrySettingsFromEnvAndProfile, sdkRetryStrategy, } from '../../../lib/api/aws-auth/private'; @@ -162,8 +163,8 @@ describe(sdkRetryStrategy, () => { expect(backoffMs).toHaveBeenCalled(); }); - test('maxAttempts of 1 disables retries', async () => { - const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 1 }); + test.each([1, 0, -1])('maxAttempts of %p disables retries', async (maxAttempts) => { + const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts }); await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); }); @@ -197,7 +198,7 @@ describe(retrySettingsFromEnv, () => { test('treats empty environment variables as unset', () => { process.env.AWS_MAX_ATTEMPTS = ''; - process.env.AWS_RETRY_MODE = ' '; + process.env.AWS_RETRY_MODE = ''; expect(retrySettingsFromEnv()).toEqual({ maxAttempts: undefined, mode: undefined }); }); @@ -209,26 +210,31 @@ describe(retrySettingsFromEnv, () => { expect(retrySettingsFromEnv()).toEqual({ maxAttempts: 2, mode: 'adaptive' }); }); - test.each(['0', '-1', '1.5', 'abc'])('rejects invalid AWS_MAX_ATTEMPTS %p', (value) => { + test.each([ + ['1.5', 1], + ['3abc', 3], + ['0', 0], + ['-1', -1], + ])('parses AWS_MAX_ATTEMPTS=%p like the SDK, as %p', (value, expected) => { process.env.AWS_MAX_ATTEMPTS = value; - expect(() => retrySettingsFromEnv()).toThrow(/AWS_MAX_ATTEMPTS must be a positive integer/); + expect(retrySettingsFromEnv().maxAttempts).toBe(expected); }); - test.each(['standard', 'legacy', 'STANDARD'])('AWS_RETRY_MODE=%s means standard mode', (mode) => { - process.env.AWS_RETRY_MODE = mode; + test.each(['abc', ' '])('rejects AWS_MAX_ATTEMPTS that is not a number: %p', (value) => { + process.env.AWS_MAX_ATTEMPTS = value; - expect(retrySettingsFromEnv().mode).toBe('standard'); + expect(() => retrySettingsFromEnv()).toThrow(`AWS_MAX_ATTEMPTS must be a number, got '${value}'`); }); - test('rejects an unknown AWS_RETRY_MODE', () => { - process.env.AWS_RETRY_MODE = 'aggressive'; + test.each(['standard', 'legacy', 'ADAPTIVE', 'aggressive'])('AWS_RETRY_MODE=%s means standard mode', (mode) => { + process.env.AWS_RETRY_MODE = mode; - expect(() => retrySettingsFromEnv()).toThrow(/AWS_RETRY_MODE must be one of/); + expect(retrySettingsFromEnv().mode).toBe('standard'); }); }); -describe(retrySettingsFromEnvAndProfile, () => { +describe('reading shared config files', () => { let workdir: string; beforeEach(() => { @@ -251,53 +257,52 @@ describe(retrySettingsFromEnvAndProfile, () => { process.env.AWS_SHARED_CREDENTIALS_FILE = credentialsPath; } - test('reads settings from the profile in the config file', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - - await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); - }); - - test('reads settings from the default profile', async () => { - writeConfigFile('[default]\nmax_attempts = 4\n'); + describe(retrySettingsFromConfig, () => { + test('reads settings from the profile in the config file', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettingsFromEnvAndProfile('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); - }); + await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); - test('reads settings from the credentials file', async () => { - writeCredentialsFile('[ci]\nmax_attempts = 4\n'); + test('reads settings from the default profile', async () => { + writeConfigFile('[default]\nmax_attempts = 4\n'); - await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); - }); + await expect(retrySettingsFromConfig('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); + }); - test('the config file takes precedence over the credentials file', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\n'); - writeCredentialsFile('[ci]\nmax_attempts = 9\n'); + test('ignores settings in the credentials file', async () => { + writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); - }); + await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + }); - test('does not fall back to the default profile', async () => { - writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); + test('does not fall back to the default profile', async () => { + writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); - await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); + await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + }); - test('environment variables take precedence over the profile, per setting', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - process.env.AWS_MAX_ATTEMPTS = '2'; + test('rejects a max_attempts that is not a number and names the profile', async () => { + writeConfigFile('[profile ci]\nmax_attempts = lots\n'); - await expect(retrySettingsFromEnvAndProfile('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + await expect(retrySettingsFromConfig('ci')).rejects.toThrow("'max_attempts' in profile 'ci' must be a number, got 'lots'"); + }); }); - test('rejects an invalid max_attempts and names the profile', async () => { - writeConfigFile('[profile ci]\nmax_attempts = lots\n'); + describe(retrySettings, () => { + test('environment variables take precedence over the profile, per setting', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + process.env.AWS_MAX_ATTEMPTS = '2'; - await expect(retrySettingsFromEnvAndProfile('ci')).rejects.toThrow("'max_attempts' in profile 'ci' must be a positive integer, got 'lots'"); - }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + }); - test('rejects an invalid retry_mode and names the profile', async () => { - writeConfigFile('[profile ci]\nretry_mode = aggressive\n'); + test('an unknown AWS_RETRY_MODE still takes precedence over the profile', async () => { + // Like the SDK: the environment variable is set, so the profile is not consulted + writeConfigFile('[profile ci]\nretry_mode = adaptive\n'); + process.env.AWS_RETRY_MODE = 'aggressive'; - await expect(retrySettingsFromEnvAndProfile('ci')).rejects.toThrow(/'retry_mode' in profile 'ci' must be one of/); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: 'standard' }); + }); }); }); From a1ca59112161d1fbeafd1d2f4ec42314e0f4dc92 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Fri, 27 Nov 2026 20:16:57 -0500 Subject: [PATCH 04/17] refactor(toolkit-lib): validate retry settings when building the retry strategy Pass the retry mode through as is and reject unknown values in sdkRetryStrategy(), accepting only 'standard' and 'adaptive' like the AWS CLI v2 does. This supersedes the previous commit, which silently treated any mode other than 'adaptive' as standard like the JavaScript SDK. Parse max attempts with parseInt and reject NaN in sdkRetryStrategy() as well. An explicit retryStrategy bypasses the SDK's own validation, and a NaN max attempts would otherwise silently disable retries. SdkRetrySettings.mode is now a string. Error messages no longer say where a value came from, matching the AWS CLI. --- .../lib/api/aws-auth/base-credentials.ts | 8 +- .../toolkit-lib/lib/api/aws-auth/retry.ts | 104 ++++++------------ .../test/api/aws-auth/sdk-retry.test.ts | 22 ++-- 3 files changed, 55 insertions(+), 79 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts index fc099e5c5..09e568dea 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts @@ -63,16 +63,20 @@ export interface SdkRetrySettings { /** * Total number of attempts, including the initial call * + * Values below 2 disable retries. `NaN` is rejected when SDK clients are created. + * * @default - a per-client default chosen by the toolkit */ readonly maxAttempts?: number; /** - * The retry mode + * The retry mode, `standard` or `adaptive` + * + * Other values are rejected when SDK clients are created. * * @default 'standard' */ - readonly mode?: 'standard' | 'adaptive'; + readonly mode?: string; } export interface SdkBaseClientConfig { diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 85b2af90f..b0218617f 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -3,26 +3,6 @@ import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-ret import type { SdkRetrySettings } from './base-credentials'; import { ToolkitError } from '../../toolkit/toolkit-error'; -/** - * Standard AWS environment variable that sets the total number of attempts (initial call plus retries) - */ -export const AWS_MAX_ATTEMPTS_ENV = 'AWS_MAX_ATTEMPTS'; - -/** - * Standard AWS environment variable that selects the retry mode - */ -export const AWS_RETRY_MODE_ENV = 'AWS_RETRY_MODE'; - -/** - * Shared config file key equivalent to `AWS_MAX_ATTEMPTS` - */ -const MAX_ATTEMPTS_CONFIG_KEY = 'max_attempts'; - -/** - * Shared config file key equivalent to `AWS_RETRY_MODE` - */ -const RETRY_MODE_CONFIG_KEY = 'retry_mode'; - /** * The retry strategies the CLI can hand to an SDK client */ @@ -45,32 +25,47 @@ export function sdkRetryStrategy( backoffMs: (attempt: number) => number, settings: SdkRetrySettings, ): SdkRetryStrategy { + if (Number.isNaN(settings.maxAttempts)) { + throw new ToolkitError('InvalidRetryConfiguration', 'invalid value provided for max attempts, must be a whole number'); + } const maxAttempts = settings.maxAttempts ?? defaultMaxAttempts; - if (settings.mode === 'adaptive') { - return new AdaptiveRetryStrategy(maxAttempts, { - maxAttempts, - backoff: { - // The SDK passes the number of completed attempts; our schedule is keyed on the next one, - // which matches how `ConfiguredRetryStrategy` calls its backoff function. - computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), - // The delay base is baked into our backoff function - setDelayBase: () => undefined, - }, - }); + switch (settings.mode) { + case undefined: + case 'standard': + // Standard mode with our own backoff schedule + return new ConfiguredRetryStrategy(maxAttempts, backoffMs); + case 'adaptive': + return new AdaptiveRetryStrategy(maxAttempts, { + maxAttempts, + backoff: { + // The SDK passes the number of completed attempts; our schedule is keyed on the next one, + // which matches how `ConfiguredRetryStrategy` calls its backoff function. + computeNextBackoffDelay: (completedAttempts: number) => backoffMs(completedAttempts + 1), + // The delay base is baked into our backoff function + setDelayBase: () => undefined, + }, + }); + default: + // Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't + // exactly 'adaptive', typos included: + // https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114 + // We reject unknown modes like the AWS CLI v2 does, which also rejects 'legacy'. + throw new ToolkitError( + 'InvalidRetryConfiguration', + `invalid value provided for retry mode: '${settings.mode}', must be one of 'standard' or 'adaptive'`, + ); } - - // Standard mode with our own backoff schedule - return new ConfiguredRetryStrategy(maxAttempts, backoffMs); } /** * Read the user's retry settings from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables */ export function retrySettingsFromEnv(): SdkRetrySettings { + const maxAttempts = process.env.AWS_MAX_ATTEMPTS; return { - maxAttempts: parseMaxAttempts(process.env[AWS_MAX_ATTEMPTS_ENV], AWS_MAX_ATTEMPTS_ENV), - mode: parseRetryMode(process.env[AWS_RETRY_MODE_ENV]), + maxAttempts: maxAttempts ? parseInt(maxAttempts) : undefined, + mode: process.env.AWS_RETRY_MODE || undefined, }; } @@ -101,45 +96,14 @@ export async function retrySettings(profile: string): Promise export async function retrySettingsFromConfig(profile: string): Promise { const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); const fromProfile = (key: string): string | undefined => configFile?.[profile]?.[key]; + const maxAttempts = fromProfile('max_attempts'); return { - maxAttempts: parseMaxAttempts(fromProfile(MAX_ATTEMPTS_CONFIG_KEY), `'${MAX_ATTEMPTS_CONFIG_KEY}' in profile '${profile}'`), - mode: parseRetryMode(fromProfile(RETRY_MODE_CONFIG_KEY)), + maxAttempts: maxAttempts ? parseInt(maxAttempts) : undefined, + mode: fromProfile('retry_mode') || undefined, }; } -/** - * Parse a max attempts value the way the SDK does - * - * The value goes through `parseInt`, so `1.5` means 1. Values below 2 disable retries. - * Only a value that is not a number at all is an error. - * - * @param source - where the value came from, for the error message - */ -function parseMaxAttempts(raw: string | undefined, source: string): number | undefined { - if (!raw) { - return undefined; - } - const value = parseInt(raw); - if (Number.isNaN(value)) { - throw new ToolkitError('InvalidRetryConfiguration', `${source} must be a number, got '${raw}'`); - } - return value; -} - -/** - * Parse a retry mode value the way the SDK does - * - * Only `adaptive` (case-sensitive) selects adaptive mode; any other value, including - * `legacy` and unknown modes, means standard mode. - */ -function parseRetryMode(raw: string | undefined): SdkRetrySettings['mode'] { - if (!raw) { - return undefined; - } - return raw === 'adaptive' ? 'adaptive' : 'standard'; -} - /** * Build a jittered exponential-backoff delay function whose result is capped at a maximum. * diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 527ff9bcd..7c41d9c3d 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -173,6 +173,14 @@ describe(sdkRetryStrategy, () => { expect(sdkRetryStrategy(7, backoffMs, { mode: 'standard' })).toBeInstanceOf(ConfiguredRetryStrategy); }); + test('rejects a max attempts that is not a number', () => { + expect(() => sdkRetryStrategy(7, backoffMs, { maxAttempts: NaN })).toThrow('invalid value provided for max attempts, must be a whole number'); + }); + + test.each(['legacy', 'ADAPTIVE', 'aggressive', ''])('rejects unknown mode %p', (mode) => { + expect(() => sdkRetryStrategy(7, backoffMs, { mode })).toThrow(`invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`); + }); + test('adaptive mode uses the adaptive strategy with our attempts and backoff', async () => { const strategy = sdkRetryStrategy(5, backoffMs, { mode: 'adaptive' }); @@ -221,16 +229,16 @@ describe(retrySettingsFromEnv, () => { expect(retrySettingsFromEnv().maxAttempts).toBe(expected); }); - test.each(['abc', ' '])('rejects AWS_MAX_ATTEMPTS that is not a number: %p', (value) => { + test.each(['abc', ' '])('AWS_MAX_ATTEMPTS that is not a number gives NaN: %p', (value) => { process.env.AWS_MAX_ATTEMPTS = value; - expect(() => retrySettingsFromEnv()).toThrow(`AWS_MAX_ATTEMPTS must be a number, got '${value}'`); + expect(retrySettingsFromEnv().maxAttempts).toBeNaN(); }); - test.each(['standard', 'legacy', 'ADAPTIVE', 'aggressive'])('AWS_RETRY_MODE=%s means standard mode', (mode) => { + test.each(['standard', 'adaptive', 'aggressive'])('passes AWS_RETRY_MODE=%s through as is', (mode) => { process.env.AWS_RETRY_MODE = mode; - expect(retrySettingsFromEnv().mode).toBe('standard'); + expect(retrySettingsFromEnv().mode).toBe(mode); }); }); @@ -282,10 +290,10 @@ describe('reading shared config files', () => { await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); - test('rejects a max_attempts that is not a number and names the profile', async () => { + test('a max_attempts that is not a number gives NaN', async () => { writeConfigFile('[profile ci]\nmax_attempts = lots\n'); - await expect(retrySettingsFromConfig('ci')).rejects.toThrow("'max_attempts' in profile 'ci' must be a number, got 'lots'"); + await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: NaN, mode: undefined }); }); }); @@ -302,7 +310,7 @@ describe('reading shared config files', () => { writeConfigFile('[profile ci]\nretry_mode = adaptive\n'); process.env.AWS_RETRY_MODE = 'aggressive'; - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: 'standard' }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: 'aggressive' }); }); }); }); From 68f0cc3b6d4df8f3894cfaa514bac8a54412651c Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Fri, 27 Nov 2026 21:15:09 -0500 Subject: [PATCH 05/17] refactor(toolkit-lib): always resolve retry settings through retrySettings() Retry settings are now resolved in one way only: retrySettings(profile) reads the environment variables and the profile in ~/.aws/config together. The separate environment and config file readers are no longer exported. SdkProvider no longer falls back to the environment variables when it is not given retry settings, which ignored the profile. SdkProviderOptions.retry and the SDK constructor's retrySettings parameter are now required. Toolkit resolves the settings with the AWS_PROFILE or default profile when the base credentials don't provide them, as with BaseCredentials.custom() and none(). Also fix the test build: ConfiguredRetryStrategy exposes the max attempts as maxAttempts() rather than maxAttemptsProvider(). --- .../lib/api/aws-auth/awscli-compatible.ts | 2 +- .../lib/api/aws-auth/base-credentials.ts | 2 +- .../toolkit-lib/lib/api/aws-auth/retry.ts | 6 +- .../lib/api/aws-auth/sdk-provider.ts | 15 ++--- .../toolkit-lib/lib/api/aws-auth/sdk.ts | 2 +- .../toolkit-lib/lib/toolkit/toolkit.ts | 7 ++- .../toolkit-lib/test/_helpers/mock-sdk.ts | 3 +- .../test/api/aws-auth/sdk-provider.test.ts | 32 ++++------ .../test/api/aws-auth/sdk-retry.test.ts | 59 ++++++++++--------- .../test/context-providers/amis.test.ts | 2 +- .../availability-zones.test.ts | 2 +- ...ndpoint-service-availability-zones.test.ts | 2 +- .../context-providers/hosted-zones.test.ts | 2 +- .../context-providers/load-balancers.test.ts | 2 +- .../context-providers/security-groups.test.ts | 2 +- .../context-providers/ssm-parameters.test.ts | 2 +- packages/aws-cdk/test/_helpers/mock-sdk.ts | 3 +- 17 files changed, 69 insertions(+), 76 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index 6397201fd..847f15d33 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -303,6 +303,6 @@ export function sdkRequestHandler(agent?: Agent): RequestHandlerSettings { /** * The profile the AWS CLI would use: the given one, then the environment, then `default` */ -function resolveProfile(maybeProfile?: string): string { +export function resolveProfile(maybeProfile?: string): string { return maybeProfile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default'; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts index 09e568dea..1ec0e51bd 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts @@ -51,7 +51,7 @@ export interface SdkBaseConfig { * * The backoff schedule between attempts is not configurable. * - * @default - only the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables apply + * @default - read from the environment and the `AWS_PROFILE` or `default` profile */ readonly retry?: SdkRetrySettings; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index b0218617f..c3af5d137 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -18,7 +18,7 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; * * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt - * @param settings - the user's retry settings, see `retrySettingsFromEnv` and `retrySettings` + * @param settings - the user's retry settings, see `retrySettings` */ export function sdkRetryStrategy( defaultMaxAttempts: number, @@ -61,7 +61,7 @@ export function sdkRetryStrategy( /** * Read the user's retry settings from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables */ -export function retrySettingsFromEnv(): SdkRetrySettings { +function retrySettingsFromEnv(): SdkRetrySettings { const maxAttempts = process.env.AWS_MAX_ATTEMPTS; return { maxAttempts: maxAttempts ? parseInt(maxAttempts) : undefined, @@ -93,7 +93,7 @@ export async function retrySettings(profile: string): Promise * * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html */ -export async function retrySettingsFromConfig(profile: string): Promise { +async function retrySettingsFromConfig(profile: string): Promise { const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); const fromProfile = (key: string): string | undefined => configFile?.[profile]?.[key]; const maxAttempts = fromProfile('max_attempts'); diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts index f4793e789..eea17b907 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts @@ -10,7 +10,6 @@ import type { RequestHandlerSettings, SdkRetrySettings } from './base-credential import { cached } from './cached'; import { CredentialPlugins } from './credential-plugins'; import { makeCachingProvider } from './provider-caching'; -import { retrySettingsFromEnv } from './retry'; import { SDK } from './sdk'; import type { UserAgentMetadata } from './sdk'; import type { ISdkLogger } from './sdk-logger'; @@ -54,11 +53,9 @@ export interface SdkProviderOptions { readonly userAgentMetadata?: UserAgentMetadata[]; /** - * Retry settings configured by the user - * - * @default - read from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables + * Retry settings configured by the user, see `retrySettings` */ - readonly retry?: SdkRetrySettings; + readonly retry: SdkRetrySettings; } const CACHED_ACCOUNT = Symbol('cached_account'); @@ -126,10 +123,10 @@ export class SdkProvider { * @param region - Region override. Takes priority over environment variables, profile config, and the us-east-1 default. * @returns a configured SdkProvider */ - public static async withAwsCliCompatibleDefaults(options: SdkProviderOptions, profile?: string, region?: string) { + public static async withAwsCliCompatibleDefaults(options: Omit, profile?: string, region?: string) { callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger); const config = await new AwsCliCompatible(options.ioHelper, options.requestHandler ?? {}, options.logger).baseConfig(profile, region); - return new SdkProvider(config.credentialProvider, config.defaultRegion, { ...options, retry: options.retry ?? config.retry }); + return new SdkProvider(config.credentialProvider, config.defaultRegion, { ...options, retry: config.retry }); } public readonly defaultRegion: string; @@ -152,7 +149,7 @@ export class SdkProvider { this.ioHelper = options.ioHelper; this.logger = options.logger; this.userAgentMetadata = options.userAgentMetadata ?? []; - this.retrySettings = options.retry ?? retrySettingsFromEnv(); + this.retrySettings = options.retry; this.plugins = new CredentialPlugins(options.pluginHost ?? new PluginHost(), this.ioHelper); } @@ -425,7 +422,7 @@ export class SdkProvider { credProvider: SDKv3CompatibleCredentialProvider, region: string, ) { - const sdk = new SDK(credProvider, region, this.requestHandler, this.ioHelper, this.logger, this.retrySettings); + const sdk = new SDK(credProvider, region, this.requestHandler, this.ioHelper, this.retrySettings, this.logger); for (const metadata of this.userAgentMetadata) { sdk.appendCustomUserAgent(metadata); } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 838014935..5fce9a74d 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -729,8 +729,8 @@ export class SDK { region: string, requestHandler: RequestHandlerSettings, ioHelper: IoHelper, + private readonly retrySettings: SdkRetrySettings, logger?: ISdkLogger, - private readonly retrySettings: SdkRetrySettings = {}, ) { const debugFn = async (msg: string) => ioHelper.defaults.debug(msg); this.accountCache = new AccountAccessKeyCache(AccountAccessKeyCache.DEFAULT_PATH, debugFn); diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 7f49ee9d6..19226ff49 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -69,8 +69,8 @@ import { type SdkBaseClientConfig, type SdkConfig, } from '../api/aws-auth'; -import { sdkRequestHandler } from '../api/aws-auth/awscli-compatible'; -import { IoHostSdkLogger, SdkProvider } from '../api/aws-auth/private'; +import { resolveProfile, sdkRequestHandler } from '../api/aws-auth/awscli-compatible'; +import { IoHostSdkLogger, retrySettings, SdkProvider } from '../api/aws-auth/private'; import { Bootstrapper } from '../api/bootstrap'; import type { ICloudAssemblySource, StackSelector } from '../api/cloud-assembly'; import { CachedCloudAssembly, StackSelectionStrategy } from '../api/cloud-assembly'; @@ -254,7 +254,8 @@ export class Toolkit extends CloudAssemblySourceBuilder { logger: new IoHostSdkLogger(ioHelper), pluginHost: this.pluginHost, requestHandler: clientConfig.requestHandler, - retry: config.retry, + // Base credentials that don't know about profiles still get the environment and default profile + retry: config.retry ?? await retrySettings(resolveProfile()), }); } diff --git a/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts b/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts index ba23b146d..4eaec9816 100644 --- a/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/test/_helpers/mock-sdk.ts @@ -150,6 +150,7 @@ export class MockSdkProvider extends SdkProvider { constructor() { super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', { ioHelper: new TestIoHost().asHelper('sdk'), + retry: {}, }); } @@ -173,7 +174,7 @@ export class MockSdkProvider extends SdkProvider { */ export class MockSdk extends SDK { constructor() { - super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', {}, new TestIoHost().asHelper('sdk')); + super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', {}, new TestIoHost().asHelper('sdk'), {}); } public async currentAccount(): Promise { diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts index 792afaac4..cb6bd00c0 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts @@ -16,6 +16,7 @@ import { randomUUID } from 'node:crypto'; import os from 'node:os'; import * as cxapi from '@aws-cdk/cloud-assembly-api'; import * as fromEnv from '@aws-sdk/credential-provider-env'; +import { AdaptiveRetryStrategy, type ConfiguredRetryStrategy } from '@smithy/util-retry'; import type { RegisterRoleOptions, RegisterUserOptions } from './fake-sts'; import { FakeSts } from './fake-sts'; import type { ConfigurationOptions, CredentialsOptions, SDK } from '../../../lib/api/aws-auth/private'; @@ -169,7 +170,7 @@ describe('with intercepted network calls', () => { const error = new Error('Expired Token'); error.name = 'ExpiredToken'; const identityProvider = () => Promise.reject(error); - const provider = new SdkProvider(identityProvider, 'rgn', { ioHelper, pluginHost: pluginHost }); + const provider = new SdkProvider(identityProvider, 'rgn', { ioHelper, pluginHost: pluginHost, retry: {} }); const creds = await provider.baseCredentialsPartition({ ...env(account), region: 'rgn' }, Mode.ForReading); expect(creds).toBeUndefined(); @@ -770,6 +771,7 @@ test('SDKs created by the provider get the userAgentMetadata', () => { // GIVEN const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper, + retry: {}, userAgentMetadata: [{ key: 'agent', value: 'kiro' }, { key: 'ci', value: 'github-actions' }], }); @@ -789,29 +791,15 @@ test('SDKs created by the provider use the retry settings', async () => { // THEN expect(sdkConfig(sdk).retryStrategy.mode).toBe('adaptive'); - await expect(sdkConfig(sdk).retryStrategy.maxAttemptsProvider()).resolves.toBe(2); + await expect(maxAttemptsOf(sdkConfig(sdk).retryStrategy)).resolves.toBe(2); }); -test('the provider reads retry settings from the environment if none are given', async () => { - // GIVEN - const original = process.env.AWS_MAX_ATTEMPTS; - process.env.AWS_MAX_ATTEMPTS = '2'; - try { - const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper }); - - // WHEN - const sdk = provider._makeSdk(jest.fn(), 'rgn'); - - // THEN - await expect(sdkConfig(sdk).retryStrategy.maxAttemptsProvider()).resolves.toBe(2); - } finally { - if (original === undefined) { - delete process.env.AWS_MAX_ATTEMPTS; - } else { - process.env.AWS_MAX_ATTEMPTS = original; - } - } -}); +/** + * The configured max attempts; the two strategies expose it under different names + */ +function maxAttemptsOf(strategy: ConfiguredRetryStrategy | AdaptiveRetryStrategy) { + return strategy instanceof AdaptiveRetryStrategy ? strategy.maxAttemptsProvider() : strategy.maxAttempts(); +} /** * Use object hackery to get the credentials out of the SDK object diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 7c41d9c3d..50c8003de 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -5,8 +5,6 @@ import * as fs from 'fs-extra'; import { cappedExponentialBackoff, retrySettings, - retrySettingsFromConfig, - retrySettingsFromEnv, sdkRetryStrategy, } from '../../../lib/api/aws-auth/private'; @@ -128,6 +126,13 @@ describe(cappedExponentialBackoff, () => { }); }); +/** + * The configured max attempts; the two strategies expose it under different names + */ +function maxAttemptsOf(strategy: ConfiguredRetryStrategy | AdaptiveRetryStrategy) { + return strategy instanceof AdaptiveRetryStrategy ? strategy.maxAttemptsProvider() : strategy.maxAttempts(); +} + describe(sdkRetryStrategy, () => { /** * A zero-delay backoff, so retries in these tests don't actually sleep @@ -150,7 +155,7 @@ describe(sdkRetryStrategy, () => { const strategy = sdkRetryStrategy(7, backoffMs, {}); expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); - await expect(strategy.maxAttemptsProvider()).resolves.toBe(7); + await expect(maxAttemptsOf(strategy)).resolves.toBe(7); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalledWith(1); }); @@ -158,7 +163,7 @@ describe(sdkRetryStrategy, () => { test('maxAttempts overrides the default number of attempts and keeps our backoff', async () => { const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 2 }); - await expect(strategy.maxAttemptsProvider()).resolves.toBe(2); + await expect(maxAttemptsOf(strategy)).resolves.toBe(2); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalled(); }); @@ -185,7 +190,7 @@ describe(sdkRetryStrategy, () => { const strategy = sdkRetryStrategy(5, backoffMs, { mode: 'adaptive' }); expect(strategy).toBeInstanceOf(AdaptiveRetryStrategy); - await expect(strategy.maxAttemptsProvider()).resolves.toBe(5); + await expect(maxAttemptsOf(strategy)).resolves.toBe(5); await retryOnce(strategy); // Same attempt numbering as ConfiguredRetryStrategy expect(backoffMs).toHaveBeenCalledWith(1); @@ -194,28 +199,28 @@ describe(sdkRetryStrategy, () => { test('adaptive mode honours maxAttempts', async () => { const strategy = sdkRetryStrategy(7, backoffMs, { mode: 'adaptive', maxAttempts: 1 }); - await expect(strategy.maxAttemptsProvider()).resolves.toBe(1); + await expect(maxAttemptsOf(strategy)).resolves.toBe(1); await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); }); }); -describe(retrySettingsFromEnv, () => { - test('returns nothing when no environment variables are set', () => { - expect(retrySettingsFromEnv()).toEqual({ maxAttempts: undefined, mode: undefined }); +describe('retrySettings from the environment', () => { + test('returns nothing when no environment variables are set', async () => { + await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); - test('treats empty environment variables as unset', () => { + test('treats empty environment variables as unset', async () => { process.env.AWS_MAX_ATTEMPTS = ''; process.env.AWS_RETRY_MODE = ''; - expect(retrySettingsFromEnv()).toEqual({ maxAttempts: undefined, mode: undefined }); + await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); - test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', () => { + test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', async () => { process.env.AWS_MAX_ATTEMPTS = '2'; process.env.AWS_RETRY_MODE = 'adaptive'; - expect(retrySettingsFromEnv()).toEqual({ maxAttempts: 2, mode: 'adaptive' }); + await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); }); test.each([ @@ -223,26 +228,26 @@ describe(retrySettingsFromEnv, () => { ['3abc', 3], ['0', 0], ['-1', -1], - ])('parses AWS_MAX_ATTEMPTS=%p like the SDK, as %p', (value, expected) => { + ])('parses AWS_MAX_ATTEMPTS=%p like the SDK, as %p', async (value, expected) => { process.env.AWS_MAX_ATTEMPTS = value; - expect(retrySettingsFromEnv().maxAttempts).toBe(expected); + expect((await retrySettings('default')).maxAttempts).toBe(expected); }); - test.each(['abc', ' '])('AWS_MAX_ATTEMPTS that is not a number gives NaN: %p', (value) => { + test.each(['abc', ' '])('AWS_MAX_ATTEMPTS that is not a number gives NaN: %p', async (value) => { process.env.AWS_MAX_ATTEMPTS = value; - expect(retrySettingsFromEnv().maxAttempts).toBeNaN(); + expect((await retrySettings('default')).maxAttempts).toBeNaN(); }); - test.each(['standard', 'adaptive', 'aggressive'])('passes AWS_RETRY_MODE=%s through as is', (mode) => { + test.each(['standard', 'adaptive', 'aggressive'])('passes AWS_RETRY_MODE=%s through as is', async (mode) => { process.env.AWS_RETRY_MODE = mode; - expect(retrySettingsFromEnv().mode).toBe(mode); + expect((await retrySettings('default')).mode).toBe(mode); }); }); -describe('reading shared config files', () => { +describe('retrySettings from the config file', () => { let workdir: string; beforeEach(() => { @@ -265,39 +270,39 @@ describe('reading shared config files', () => { process.env.AWS_SHARED_CREDENTIALS_FILE = credentialsPath; } - describe(retrySettingsFromConfig, () => { + describe('profile lookup', () => { test('reads settings from the profile in the config file', async () => { writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); }); test('reads settings from the default profile', async () => { writeConfigFile('[default]\nmax_attempts = 4\n'); - await expect(retrySettingsFromConfig('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); + await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); }); test('ignores settings in the credentials file', async () => { writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); test('does not fall back to the default profile', async () => { writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); - await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); test('a max_attempts that is not a number gives NaN', async () => { writeConfigFile('[profile ci]\nmax_attempts = lots\n'); - await expect(retrySettingsFromConfig('ci')).resolves.toEqual({ maxAttempts: NaN, mode: undefined }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: NaN, mode: undefined }); }); }); - describe(retrySettings, () => { + describe('precedence', () => { test('environment variables take precedence over the profile, per setting', async () => { writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); process.env.AWS_MAX_ATTEMPTS = '2'; diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/amis.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/amis.test.ts index 4849c9481..3758da9e8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/amis.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/amis.test.ts @@ -8,7 +8,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/availability-zones.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/availability-zones.test.ts index 8c39ebfb0..f0f574cd8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/availability-zones.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/availability-zones.test.ts @@ -7,7 +7,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/endpoint-service-availability-zones.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/endpoint-service-availability-zones.test.ts index 402d3e6a7..72ecc2060 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/endpoint-service-availability-zones.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/endpoint-service-availability-zones.test.ts @@ -9,7 +9,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/hosted-zones.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/hosted-zones.test.ts index f38a50c9b..b4c4026fb 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/hosted-zones.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/hosted-zones.test.ts @@ -7,7 +7,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/load-balancers.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/load-balancers.test.ts index bcd104833..42ab642de 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/load-balancers.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/load-balancers.test.ts @@ -20,7 +20,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/security-groups.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/security-groups.test.ts index 4f29f7789..7931109fd 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/security-groups.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/security-groups.test.ts @@ -7,7 +7,7 @@ import { FAKE_CREDENTIAL_CHAIN, MockSdkProvider, mockEC2Client, restoreSdkMocksT const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/@aws-cdk/toolkit-lib/test/context-providers/ssm-parameters.test.ts b/packages/@aws-cdk/toolkit-lib/test/context-providers/ssm-parameters.test.ts index 234915158..7fe2f9c4d 100644 --- a/packages/@aws-cdk/toolkit-lib/test/context-providers/ssm-parameters.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/context-providers/ssm-parameters.test.ts @@ -7,7 +7,7 @@ import { TestIoHost } from '../_helpers/test-io-host'; const mockSDK = new (class extends MockSdkProvider { public forEnvironment(): Promise { - return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy')), didAssumeRole: false }); + return Promise.resolve({ sdk: new SDK(FAKE_CREDENTIAL_CHAIN, mockSDK.defaultRegion, {}, new TestIoHost().asHelper('deploy'), {}), didAssumeRole: false }); } })(); diff --git a/packages/aws-cdk/test/_helpers/mock-sdk.ts b/packages/aws-cdk/test/_helpers/mock-sdk.ts index 0db92735d..941877b67 100644 --- a/packages/aws-cdk/test/_helpers/mock-sdk.ts +++ b/packages/aws-cdk/test/_helpers/mock-sdk.ts @@ -153,6 +153,7 @@ export class MockSdkProvider extends SdkProvider { constructor() { super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', { ioHelper: new TestIoHost().asHelper('sdk'), + retry: {}, }); } @@ -176,7 +177,7 @@ export class MockSdkProvider extends SdkProvider { */ export class MockSdk extends SDK { constructor() { - super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', {}, new TestIoHost().asHelper('sdk')); + super(FAKE_CREDENTIAL_CHAIN, 'bermuda-triangle-1337', {}, new TestIoHost().asHelper('sdk'), {}); } } From 2e824fa9f27c01a5465269acd18e347188ecff80 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 12:05:28 -0500 Subject: [PATCH 06/17] fix(toolkit-lib): validate retry settings eagerly and give each SDK client its own retry strategy Validate AWS_MAX_ATTEMPTS / max_attempts and AWS_RETRY_MODE / retry_mode in retrySettings(), when the values are read, instead of when an SDK client is created. SDK clients are first created inside credential resolution, whose error handling turned an invalid setting into a misleading "no credentials" or "could not assume role" error. Only the value that is used is validated, and the error quotes it. This supersedes the validation in sdkRetryStrategy() from an earlier commit, and SdkRetrySettings.mode is a 'standard' | 'adaptive' union again. Accept retry mode 'legacy' with a warning and use standard mode. It is a documented mode that other SDKs support, so users may have it configured for other tools; rejecting it would fail every command after upgrading. Build a retry strategy per SDK client instead of sharing one across all clients. The strategy holds the retry quota and, in adaptive mode, the client-side rate limiter, so throttling on one service slowed down calls to every other service. Trim the retry tests to the ones that cover our own logic. --- .../lib/api/aws-auth/awscli-compatible.ts | 2 +- .../lib/api/aws-auth/base-credentials.ts | 8 +- .../toolkit-lib/lib/api/aws-auth/retry.ts | 91 +++++---- .../toolkit-lib/lib/api/aws-auth/sdk.ts | 7 +- .../toolkit-lib/lib/toolkit/toolkit.ts | 2 +- .../test/api/aws-auth/sdk-provider.test.ts | 37 +++- .../test/api/aws-auth/sdk-retry.test.ts | 172 ++++++------------ 7 files changed, 153 insertions(+), 166 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index 847f15d33..1335f60d8 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -43,7 +43,7 @@ export class AwsCliCompatible { logger: this.logger, }); const defaultRegion = region ?? await this.region(profile); - const retry = await retrySettings(resolveProfile(profile)); + const retry = await retrySettings(resolveProfile(profile), this.ioHelper); return { credentialProvider, defaultRegion, retry }; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts index 1ec0e51bd..7b27a4940 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts @@ -63,20 +63,18 @@ export interface SdkRetrySettings { /** * Total number of attempts, including the initial call * - * Values below 2 disable retries. `NaN` is rejected when SDK clients are created. + * Values below 2 disable retries. * * @default - a per-client default chosen by the toolkit */ readonly maxAttempts?: number; /** - * The retry mode, `standard` or `adaptive` - * - * Other values are rejected when SDK clients are created. + * The retry mode * * @default 'standard' */ - readonly mode?: string; + readonly mode?: 'standard' | 'adaptive'; } export interface SdkBaseClientConfig { diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index c3af5d137..990fb42a9 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -2,6 +2,7 @@ import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; import type { SdkRetrySettings } from './base-credentials'; import { ToolkitError } from '../../toolkit/toolkit-error'; +import type { IoHelper } from '../io/private'; /** * The retry strategies the CLI can hand to an SDK client @@ -16,6 +17,9 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; * when they have not set one. The backoff schedule is not user-configurable: there is no * standard setting for it, and we tune it per client. * + * The strategy holds per-client state (the retry quota, and in adaptive mode the client-side + * rate limiter), so build one for every SDK client rather than sharing it. + * * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt * @param settings - the user's retry settings, see `retrySettings` @@ -25,9 +29,6 @@ export function sdkRetryStrategy( backoffMs: (attempt: number) => number, settings: SdkRetrySettings, ): SdkRetryStrategy { - if (Number.isNaN(settings.maxAttempts)) { - throw new ToolkitError('InvalidRetryConfiguration', 'invalid value provided for max attempts, must be a whole number'); - } const maxAttempts = settings.maxAttempts ?? defaultMaxAttempts; switch (settings.mode) { @@ -46,46 +47,27 @@ export function sdkRetryStrategy( setDelayBase: () => undefined, }, }); - default: - // Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't - // exactly 'adaptive', typos included: - // https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114 - // We reject unknown modes like the AWS CLI v2 does, which also rejects 'legacy'. - throw new ToolkitError( - 'InvalidRetryConfiguration', - `invalid value provided for retry mode: '${settings.mode}', must be one of 'standard' or 'adaptive'`, - ); } } -/** - * Read the user's retry settings from the `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables - */ -function retrySettingsFromEnv(): SdkRetrySettings { - const maxAttempts = process.env.AWS_MAX_ATTEMPTS; - return { - maxAttempts: maxAttempts ? parseInt(maxAttempts) : undefined, - mode: process.env.AWS_RETRY_MODE || undefined, - }; -} - /** * Read the user's retry settings the way the AWS CLI does * * Each setting is taken from its environment variable first, then from the given profile - * in the shared config files. + * in the shared config file. The values are validated here, before any SDK client exists, + * so that a bad value fails with a clear error instead of surfacing from inside credential + * resolution. */ -export async function retrySettings(profile: string): Promise { - const fromEnv = retrySettingsFromEnv(); +export async function retrySettings(profile: string, ioHelper: IoHelper): Promise { const fromConfig = await retrySettingsFromConfig(profile); return { - maxAttempts: fromEnv.maxAttempts ?? fromConfig.maxAttempts, - mode: fromEnv.mode ?? fromConfig.mode, + maxAttempts: parseMaxAttempts(process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts), + mode: await parseRetryMode(process.env.AWS_RETRY_MODE || fromConfig.mode, ioHelper), }; } /** - * Read the user's retry settings from the given profile in the shared config file + * Read the raw retry settings from the given profile in the shared config file * * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the * retry settings are documented for the config file only. There is no fallback to the @@ -93,17 +75,56 @@ export async function retrySettings(profile: string): Promise * * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html */ -async function retrySettingsFromConfig(profile: string): Promise { +async function retrySettingsFromConfig(profile: string): Promise<{ maxAttempts?: string; mode?: string }> { const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); - const fromProfile = (key: string): string | undefined => configFile?.[profile]?.[key]; - const maxAttempts = fromProfile('max_attempts'); - return { - maxAttempts: maxAttempts ? parseInt(maxAttempts) : undefined, - mode: fromProfile('retry_mode') || undefined, + maxAttempts: configFile?.[profile]?.max_attempts, + mode: configFile?.[profile]?.retry_mode, }; } +/** + * Parse max attempts with `parseInt`, like the SDK does, so `1.5` means 1 + */ +function parseMaxAttempts(raw: string | undefined): number | undefined { + if (!raw) { + return undefined; + } + const value = parseInt(raw); + if (Number.isNaN(value)) { + throw new ToolkitError('InvalidRetryConfiguration', `invalid value provided for max attempts: '${raw}', must be a whole number`); + } + return value; +} + +/** + * Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't + * exactly 'adaptive', typos included: + * https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114 + * + * We reject unknown modes like the AWS CLI v2 does. 'legacy' is a documented mode that other + * SDKs support but the JavaScript SDK doesn't, so users may have it configured for other tools: + * we warn and use standard mode instead of failing. + */ +async function parseRetryMode(raw: string | undefined, ioHelper: IoHelper): Promise { + switch (raw) { + case undefined: + case '': + return undefined; + case 'standard': + case 'adaptive': + return raw; + case 'legacy': + await ioHelper.defaults.warn("Retry mode 'legacy' is not supported by the AWS SDK for JavaScript, using 'standard' instead"); + return 'standard'; + default: + throw new ToolkitError( + 'InvalidRetryConfiguration', + `invalid value provided for retry mode: '${raw}', must be one of 'standard' or 'adaptive'`, + ); + } +} + /** * Build a jittered exponential-backoff delay function whose result is capped at a maximum. * diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 5fce9a74d..72eeea7be 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -694,7 +694,7 @@ export interface IStepFunctionsClient { export class SDK { public readonly currentRegion: string; - private readonly baseConfig: Omit; + private readonly baseConfig: Omit; /** * The legacy User-Agent string, sent as the first token @@ -739,7 +739,6 @@ export class SDK { region, credentials: credProvider, requestHandler, - retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(300, 15_000), retrySettings), logger: logger ? makeSdkLoggerSafeByBindingThis(logger) : undefined, }; this.stsRetryStrategy = sdkRetryStrategy(3, (attempt) => 100 * (2 ** attempt), retrySettings); @@ -750,12 +749,16 @@ export class SDK { /** * The configuration to create SDK clients with * + * Every access builds a new retry strategy, so each client gets its own retry quota and + * adaptive rate limiter, as it would without an explicit strategy. + * * The legacy User-Agent string is passed through unchanged as the first token, * so it looks exactly like before. Metadata follows as separate tokens. */ public get config(): ConfigurationOptions { return { ...this.baseConfig, + retryStrategy: sdkRetryStrategy(7, cappedExponentialBackoff(300, 15_000), this.retrySettings), customUserAgent: [ [this.customUserAgent], ...Array.from(this.userAgentMetadata, ([key, value]): [string, string] => [`aws-cdk/${key}`, value]), diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 19226ff49..65a8bb36c 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -255,7 +255,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { pluginHost: this.pluginHost, requestHandler: clientConfig.requestHandler, // Base credentials that don't know about profiles still get the environment and default profile - retry: config.retry ?? await retrySettings(resolveProfile()), + retry: config.retry ?? await retrySettings(resolveProfile(), ioHelper), }); } diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts index cb6bd00c0..8a893379f 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts @@ -16,7 +16,6 @@ import { randomUUID } from 'node:crypto'; import os from 'node:os'; import * as cxapi from '@aws-cdk/cloud-assembly-api'; import * as fromEnv from '@aws-sdk/credential-provider-env'; -import { AdaptiveRetryStrategy, type ConfiguredRetryStrategy } from '@smithy/util-retry'; import type { RegisterRoleOptions, RegisterUserOptions } from './fake-sts'; import { FakeSts } from './fake-sts'; import type { ConfigurationOptions, CredentialsOptions, SDK } from '../../../lib/api/aws-auth/private'; @@ -782,24 +781,42 @@ test('SDKs created by the provider get the userAgentMetadata', () => { expect((sdk as any).userAgentMetadata).toEqual(new Map([['agent', 'kiro'], ['ci', 'github-actions']])); }); -test('SDKs created by the provider use the retry settings', async () => { +test('SDKs created by the provider use the retry settings', () => { // GIVEN - const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper, retry: { maxAttempts: 2, mode: 'adaptive' } }); + const provider = new SdkProvider(jest.fn(), 'rgn', { ioHelper, retry: { mode: 'adaptive' } }); // WHEN const sdk = provider._makeSdk(jest.fn(), 'rgn'); // THEN expect(sdkConfig(sdk).retryStrategy.mode).toBe('adaptive'); - await expect(maxAttemptsOf(sdkConfig(sdk).retryStrategy)).resolves.toBe(2); }); -/** - * The configured max attempts; the two strategies expose it under different names - */ -function maxAttemptsOf(strategy: ConfiguredRetryStrategy | AdaptiveRetryStrategy) { - return strategy instanceof AdaptiveRetryStrategy ? strategy.maxAttemptsProvider() : strategy.maxAttempts(); -} +test('every SDK client gets its own retry strategy', () => { + // GIVEN + const sdk = new SdkProvider(jest.fn(), 'rgn', { ioHelper, retry: { mode: 'adaptive' } })._makeSdk(jest.fn(), 'rgn'); + + // THEN - the retry quota and adaptive rate limiter are per-client state + expect(sdkConfig(sdk).retryStrategy).not.toBe(sdkConfig(sdk).retryStrategy); +}); + +test('an invalid retry setting fails when the provider is created, not as a credentials error', async () => { + // GIVEN + const original = process.env.AWS_RETRY_MODE; + process.env.AWS_RETRY_MODE = 'adaptve'; + try { + // THEN + await expect(SdkProvider.withAwsCliCompatibleDefaults({ ioHelper, pluginHost })).rejects.toThrow( + "invalid value provided for retry mode: 'adaptve'", + ); + } finally { + if (original === undefined) { + delete process.env.AWS_RETRY_MODE; + } else { + process.env.AWS_RETRY_MODE = original; + } + } +}); /** * Use object hackery to get the credentials out of the SDK object diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 50c8003de..7b84ead6f 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -1,12 +1,13 @@ import * as os from 'os'; import * as path from 'path'; -import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; +import { AdaptiveRetryStrategy, type ConfiguredRetryStrategy } from '@smithy/util-retry'; import * as fs from 'fs-extra'; import { cappedExponentialBackoff, retrySettings, sdkRetryStrategy, } from '../../../lib/api/aws-auth/private'; +import { TestIoHost } from '../../_helpers/test-io-host'; /** * The top of the jitter window is the delay the schedule asks for, so mocking @@ -151,106 +152,38 @@ describe(sdkRetryStrategy, () => { return strategy.refreshRetryTokenForRetry(token as any, { errorType: 'TRANSIENT' } as any); } - test('uses the defaults when the user has not configured retries', async () => { - const strategy = sdkRetryStrategy(7, backoffMs, {}); + test.each([undefined, 'standard' as const])('mode %p uses the default attempts and our backoff', async (mode) => { + const strategy = sdkRetryStrategy(7, backoffMs, { mode }); - expect(strategy).toBeInstanceOf(ConfiguredRetryStrategy); await expect(maxAttemptsOf(strategy)).resolves.toBe(7); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalledWith(1); }); - test('maxAttempts overrides the default number of attempts and keeps our backoff', async () => { + test('maxAttempts overrides the default number of attempts', async () => { const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 2 }); await expect(maxAttemptsOf(strategy)).resolves.toBe(2); - await retryOnce(strategy); - expect(backoffMs).toHaveBeenCalled(); - }); - - test.each([1, 0, -1])('maxAttempts of %p disables retries', async (maxAttempts) => { - const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts }); - - await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); - }); - - test('standard mode uses the standard strategy', () => { - expect(sdkRetryStrategy(7, backoffMs, { mode: 'standard' })).toBeInstanceOf(ConfiguredRetryStrategy); - }); - - test('rejects a max attempts that is not a number', () => { - expect(() => sdkRetryStrategy(7, backoffMs, { maxAttempts: NaN })).toThrow('invalid value provided for max attempts, must be a whole number'); - }); - - test.each(['legacy', 'ADAPTIVE', 'aggressive', ''])('rejects unknown mode %p', (mode) => { - expect(() => sdkRetryStrategy(7, backoffMs, { mode })).toThrow(`invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`); }); - test('adaptive mode uses the adaptive strategy with our attempts and backoff', async () => { - const strategy = sdkRetryStrategy(5, backoffMs, { mode: 'adaptive' }); + test('adaptive mode uses our attempts and backoff', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, { mode: 'adaptive', maxAttempts: 2 }); expect(strategy).toBeInstanceOf(AdaptiveRetryStrategy); - await expect(maxAttemptsOf(strategy)).resolves.toBe(5); + await expect(maxAttemptsOf(strategy)).resolves.toBe(2); await retryOnce(strategy); // Same attempt numbering as ConfiguredRetryStrategy expect(backoffMs).toHaveBeenCalledWith(1); }); - - test('adaptive mode honours maxAttempts', async () => { - const strategy = sdkRetryStrategy(7, backoffMs, { mode: 'adaptive', maxAttempts: 1 }); - - await expect(maxAttemptsOf(strategy)).resolves.toBe(1); - await expect(retryOnce(strategy)).rejects.toThrow(/No retry token available/); - }); -}); - -describe('retrySettings from the environment', () => { - test('returns nothing when no environment variables are set', async () => { - await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); - - test('treats empty environment variables as unset', async () => { - process.env.AWS_MAX_ATTEMPTS = ''; - process.env.AWS_RETRY_MODE = ''; - - await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); - - test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', async () => { - process.env.AWS_MAX_ATTEMPTS = '2'; - process.env.AWS_RETRY_MODE = 'adaptive'; - - await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); - }); - - test.each([ - ['1.5', 1], - ['3abc', 3], - ['0', 0], - ['-1', -1], - ])('parses AWS_MAX_ATTEMPTS=%p like the SDK, as %p', async (value, expected) => { - process.env.AWS_MAX_ATTEMPTS = value; - - expect((await retrySettings('default')).maxAttempts).toBe(expected); - }); - - test.each(['abc', ' '])('AWS_MAX_ATTEMPTS that is not a number gives NaN: %p', async (value) => { - process.env.AWS_MAX_ATTEMPTS = value; - - expect((await retrySettings('default')).maxAttempts).toBeNaN(); - }); - - test.each(['standard', 'adaptive', 'aggressive'])('passes AWS_RETRY_MODE=%s through as is', async (mode) => { - process.env.AWS_RETRY_MODE = mode; - - expect((await retrySettings('default')).mode).toBe(mode); - }); }); -describe('retrySettings from the config file', () => { +describe(retrySettings, () => { + const ioHost = new TestIoHost(); + const ioHelper = ioHost.asHelper('sdk'); let workdir: string; beforeEach(() => { + ioHost.clear(); workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-retry.test')); }); @@ -270,52 +203,67 @@ describe('retrySettings from the config file', () => { process.env.AWS_SHARED_CREDENTIALS_FILE = credentialsPath; } - describe('profile lookup', () => { - test('reads settings from the profile in the config file', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', async () => { + process.env.AWS_MAX_ATTEMPTS = '2'; + process.env.AWS_RETRY_MODE = 'adaptive'; - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); - }); + await expect(retrySettings('default', ioHelper)).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + }); - test('reads settings from the default profile', async () => { - writeConfigFile('[default]\nmax_attempts = 4\n'); + test('reads settings from the profile in the config file', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 4, mode: undefined }); - }); + await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); - test('ignores settings in the credentials file', async () => { - writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + test('ignores settings in the credentials file', async () => { + writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); + await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + }); - test('does not fall back to the default profile', async () => { - writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); + test('does not fall back to the default profile', async () => { + writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); + await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + }); - test('a max_attempts that is not a number gives NaN', async () => { - writeConfigFile('[profile ci]\nmax_attempts = lots\n'); + test('environment variables take precedence over the profile, per setting, and only the used value is validated', async () => { + writeConfigFile('[profile ci]\nmax_attempts = lots\nretry_mode = adaptive\n'); + process.env.AWS_MAX_ATTEMPTS = '2'; - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: NaN, mode: undefined }); - }); + await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); }); - describe('precedence', () => { - test('environment variables take precedence over the profile, per setting', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - process.env.AWS_MAX_ATTEMPTS = '2'; + test('empty environment variables fall through to the profile', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + process.env.AWS_MAX_ATTEMPTS = ''; + process.env.AWS_RETRY_MODE = ''; - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); - }); + await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }); + + test('rejects a max attempts that is not a number', async () => { + writeConfigFile('[profile ci]\nmax_attempts = lots\n'); + + await expect(retrySettings('ci', ioHelper)).rejects.toThrow("invalid value provided for max attempts: 'lots', must be a whole number"); + }); + + test('rejects an unknown retry mode', async () => { + process.env.AWS_RETRY_MODE = 'adaptve'; + + await expect(retrySettings('default', ioHelper)).rejects.toThrow( + "invalid value provided for retry mode: 'adaptve', must be one of 'standard' or 'adaptive'", + ); + }); - test('an unknown AWS_RETRY_MODE still takes precedence over the profile', async () => { - // Like the SDK: the environment variable is set, so the profile is not consulted - writeConfigFile('[profile ci]\nretry_mode = adaptive\n'); - process.env.AWS_RETRY_MODE = 'aggressive'; + test('treats legacy mode as standard, with a warning', async () => { + writeConfigFile('[default]\nretry_mode = legacy\n'); - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: 'aggressive' }); - }); + await expect(retrySettings('default', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: 'standard' }); + expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ + level: 'warn', + message: expect.stringContaining("Retry mode 'legacy' is not supported"), + })); }); }); From eee2248e6e25f07115978a55fb97dc37d34dcb50 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 12:41:10 -0500 Subject: [PATCH 07/17] refactor(toolkit-lib): validate retry settings like the AWS CLI v2 Reject retry mode 'legacy' instead of warning and falling back to standard: the AWS CLI v2 rejects it too, so a value like that is already broken for the user. This supersedes the 'legacy' handling from the previous commit. An environment variable that is set, even to an empty string, now always takes precedence over the profile, and empty values are invalid, as in the AWS CLI v2. Max attempts must be a whole number of at least 1; '3x', '1.5', '0' and '-1' are rejected instead of being parsed with parseInt. retrySettings() reads the values and checks them with validateMaxAttempts() and validateMode(). SdkRetrySettings.mode stays a 'standard' | 'adaptive' union. --- .../lib/api/aws-auth/awscli-compatible.ts | 2 +- .../toolkit-lib/lib/api/aws-auth/retry.ts | 105 +++++++++--------- .../toolkit-lib/lib/toolkit/toolkit.ts | 2 +- .../test/api/aws-auth/sdk-retry.test.ts | 47 +++----- 4 files changed, 70 insertions(+), 86 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index 1335f60d8..847f15d33 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -43,7 +43,7 @@ export class AwsCliCompatible { logger: this.logger, }); const defaultRegion = region ?? await this.region(profile); - const retry = await retrySettings(resolveProfile(profile), this.ioHelper); + const retry = await retrySettings(resolveProfile(profile)); return { credentialProvider, defaultRegion, retry }; } diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 990fb42a9..4dba16e75 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -2,7 +2,6 @@ import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; import type { SdkRetrySettings } from './base-credentials'; import { ToolkitError } from '../../toolkit/toolkit-error'; -import type { IoHelper } from '../io/private'; /** * The retry strategies the CLI can hand to an SDK client @@ -22,7 +21,7 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; * * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt - * @param settings - the user's retry settings, see `retrySettings` + * @param settings - the user's retry settings */ export function sdkRetryStrategy( defaultMaxAttempts: number, @@ -51,80 +50,78 @@ export function sdkRetryStrategy( } /** - * Read the user's retry settings the way the AWS CLI does + * Read the user's retry settings the way the AWS CLI v2 does * - * Each setting is taken from its environment variable first, then from the given profile - * in the shared config file. The values are validated here, before any SDK client exists, - * so that a bad value fails with a clear error instead of surfacing from inside credential - * resolution. + * Each setting is taken from its environment variable if it is set, even to an empty string, + * and otherwise from the given profile in the shared config file. */ -export async function retrySettings(profile: string, ioHelper: IoHelper): Promise { +export async function retrySettings(profile: string): Promise { const fromConfig = await retrySettingsFromConfig(profile); - return { - maxAttempts: parseMaxAttempts(process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts), - mode: await parseRetryMode(process.env.AWS_RETRY_MODE || fromConfig.mode, ioHelper), - }; + const maxAttempts = process.env.AWS_MAX_ATTEMPTS ?? fromConfig.maxAttempts; + const mode = process.env.AWS_RETRY_MODE ?? fromConfig.mode; + validateMaxAttempts(maxAttempts); + validateMode(mode); + return { maxAttempts: maxAttempts === undefined ? undefined : Number(maxAttempts), mode }; } /** - * Read the raw retry settings from the given profile in the shared config file + * Validate max attempts the way the AWS CLI v2 does: a whole number of at least 1 * - * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the - * retry settings are documented for the config file only. There is no fallback to the - * `default` profile. + * The AWS CLI parses with Python's `int()`, which also rejects numeric formats that `Number` + * accepts, like '0x10', '1e2' or '3.0'. We accept those: nobody writes them by accident. * - * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html - */ -async function retrySettingsFromConfig(profile: string): Promise<{ maxAttempts?: string; mode?: string }> { - const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); - return { - maxAttempts: configFile?.[profile]?.max_attempts, - mode: configFile?.[profile]?.retry_mode, - }; -} - -/** - * Parse max attempts with `parseInt`, like the SDK does, so `1.5` means 1 + * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/configprovider.py#L145 + * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L400-L403 */ -function parseMaxAttempts(raw: string | undefined): number | undefined { - if (!raw) { - return undefined; +function validateMaxAttempts(maxAttempts: string | undefined): void { + if (maxAttempts === undefined) { + return; } - const value = parseInt(raw); - if (Number.isNaN(value)) { - throw new ToolkitError('InvalidRetryConfiguration', `invalid value provided for max attempts: '${raw}', must be a whole number`); + // `Number('')` and `Number(' ')` are 0, so blanks fail the minimum + const value = Number(maxAttempts); + if (!Number.isInteger(value) || value < 1) { + throw new ToolkitError('InvalidRetryConfiguration', `invalid value provided for max attempts: '${maxAttempts}', must be a whole number of at least 1`); } - return value; } /** + * Validate the retry mode the way the AWS CLI v2 does + * * Stricter than the JavaScript SDK, which silently uses standard mode for anything that isn't * exactly 'adaptive', typos included: * https://github.com/smithy-lang/smithy-typescript/blob/d6725176da29286396c921bbe52d3bbd6b93a46b/packages/core/src/submodules/retry/middleware-retry/configurations.ts#L102-L114 * - * We reject unknown modes like the AWS CLI v2 does. 'legacy' is a documented mode that other - * SDKs support but the JavaScript SDK doesn't, so users may have it configured for other tools: - * we warn and use standard mode instead of failing. + * We reject anything the AWS CLI v2 rejects, which includes 'legacy': it's a documented mode, but + * neither the JavaScript SDK nor the AWS CLI v2 supports it. + * + * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L404-L405 */ -async function parseRetryMode(raw: string | undefined, ioHelper: IoHelper): Promise { - switch (raw) { - case undefined: - case '': - return undefined; - case 'standard': - case 'adaptive': - return raw; - case 'legacy': - await ioHelper.defaults.warn("Retry mode 'legacy' is not supported by the AWS SDK for JavaScript, using 'standard' instead"); - return 'standard'; - default: - throw new ToolkitError( - 'InvalidRetryConfiguration', - `invalid value provided for retry mode: '${raw}', must be one of 'standard' or 'adaptive'`, - ); +function validateMode(mode: string | undefined): asserts mode is SdkRetrySettings['mode'] { + if (mode !== undefined && mode !== 'standard' && mode !== 'adaptive') { + throw new ToolkitError( + 'InvalidRetryConfiguration', + `invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`, + ); } } +/** + * Read the raw retry settings from the given profile in the shared config file + * + * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the + * retry settings are documented for the config file only. There is no fallback to the + * `default` profile. + * + * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html + */ +async function retrySettingsFromConfig(profile: string): Promise<{ maxAttempts?: string; mode?: string }> { + const { configFile } = await loadSharedConfigFiles({ ignoreCache: true }); + return { + maxAttempts: configFile?.[profile]?.max_attempts, + mode: configFile?.[profile]?.retry_mode, + }; +} + /** * Build a jittered exponential-backoff delay function whose result is capped at a maximum. * diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 65a8bb36c..19226ff49 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -255,7 +255,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { pluginHost: this.pluginHost, requestHandler: clientConfig.requestHandler, // Base credentials that don't know about profiles still get the environment and default profile - retry: config.retry ?? await retrySettings(resolveProfile(), ioHelper), + retry: config.retry ?? await retrySettings(resolveProfile()), }); } diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 7b84ead6f..ab74324b8 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -7,7 +7,6 @@ import { retrySettings, sdkRetryStrategy, } from '../../../lib/api/aws-auth/private'; -import { TestIoHost } from '../../_helpers/test-io-host'; /** * The top of the jitter window is the delay the schedule asks for, so mocking @@ -178,12 +177,9 @@ describe(sdkRetryStrategy, () => { }); describe(retrySettings, () => { - const ioHost = new TestIoHost(); - const ioHelper = ioHost.asHelper('sdk'); let workdir: string; beforeEach(() => { - ioHost.clear(); workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-retry.test')); }); @@ -207,63 +203,54 @@ describe(retrySettings, () => { process.env.AWS_MAX_ATTEMPTS = '2'; process.env.AWS_RETRY_MODE = 'adaptive'; - await expect(retrySettings('default', ioHelper)).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); }); test('reads settings from the profile in the config file', async () => { writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); }); test('ignores settings in the credentials file', async () => { writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); test('does not fall back to the default profile', async () => { writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); - await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); }); test('environment variables take precedence over the profile, per setting, and only the used value is validated', async () => { writeConfigFile('[profile ci]\nmax_attempts = lots\nretry_mode = adaptive\n'); process.env.AWS_MAX_ATTEMPTS = '2'; - await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); }); - test('empty environment variables fall through to the profile', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); + test('an empty environment variable is invalid and does not fall through to the profile, like the AWS CLI v2', async () => { + writeConfigFile('[profile ci]\nmax_attempts = 4\n'); process.env.AWS_MAX_ATTEMPTS = ''; - process.env.AWS_RETRY_MODE = ''; - await expect(retrySettings('ci', ioHelper)).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + await expect(retrySettings('ci')).rejects.toThrow("invalid value provided for max attempts: '', must be a whole number of at least 1"); }); - test('rejects a max attempts that is not a number', async () => { - writeConfigFile('[profile ci]\nmax_attempts = lots\n'); - - await expect(retrySettings('ci', ioHelper)).rejects.toThrow("invalid value provided for max attempts: 'lots', must be a whole number"); - }); + test.each(['3x', '1.5', '0', '-1'])('rejects max attempts %p, like the AWS CLI v2', async (value) => { + writeConfigFile(`[profile ci]\nmax_attempts = ${value}\n`); - test('rejects an unknown retry mode', async () => { - process.env.AWS_RETRY_MODE = 'adaptve'; - - await expect(retrySettings('default', ioHelper)).rejects.toThrow( - "invalid value provided for retry mode: 'adaptve', must be one of 'standard' or 'adaptive'", + await expect(retrySettings('ci')).rejects.toThrow( + `invalid value provided for max attempts: '${value}', must be a whole number of at least 1`, ); }); - test('treats legacy mode as standard, with a warning', async () => { - writeConfigFile('[default]\nretry_mode = legacy\n'); + test.each(['adaptve', 'legacy', ''])('rejects retry mode %p, like the AWS CLI v2', async (mode) => { + process.env.AWS_RETRY_MODE = mode; - await expect(retrySettings('default', ioHelper)).resolves.toEqual({ maxAttempts: undefined, mode: 'standard' }); - expect(ioHost.notifySpy).toHaveBeenCalledWith(expect.objectContaining({ - level: 'warn', - message: expect.stringContaining("Retry mode 'legacy' is not supported"), - })); + await expect(retrySettings('default')).rejects.toThrow( + `invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`, + ); }); }); From 9b023818b8d9e6446d900d04024a13d82e7518a0 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 13:11:46 -0500 Subject: [PATCH 08/17] fix(toolkit-lib): cap the STS retry backoff and require @smithy/util-retry 4.3.0 The STS client's backoff was an uncapped 100ms * 2^attempt. That was fine with the fixed 3 attempts, but users can now raise max attempts, and with AWS_MAX_ATTEMPTS=15 the last wait alone is about 27 minutes. Use cappedExponentialBackoff(100, 15_000) like the other clients. Require @smithy/util-retry ^4.3.0 in toolkit-lib. Older 4.x versions of AdaptiveRetryStrategy only read `rateLimiter` from their options, so adaptive mode would silently drop our max attempts and capped backoff. The lockfile is deduplicated, so the bundled CLI moves from 4.5.5 to 4.6.2. Clarify that a retry strategy must not be shared across services; the two STS clients keep sharing one. --- .projenrc.ts | 3 ++- packages/@aws-cdk/toolkit-lib/.projen/deps.json | 2 +- .../@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts | 2 +- .../@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts | 2 +- packages/@aws-cdk/toolkit-lib/package.json | 2 +- packages/aws-cdk/THIRD_PARTY_LICENSES | 2 +- yarn.lock | 12 ++++++------ 7 files changed, 13 insertions(+), 12 deletions(-) diff --git a/.projenrc.ts b/.projenrc.ts index ff1be9bbb..f56836732 100644 --- a/.projenrc.ts +++ b/.projenrc.ts @@ -977,7 +977,8 @@ const toolkitLib = configureProject( smithyDep('@smithy/middleware-endpoint'), smithyDep('@smithy/property-provider'), smithyDep('@smithy/shared-ini-file-loader'), - smithyDep('@smithy/util-retry'), + // AdaptiveRetryStrategy only honours the `maxAttempts` and `backoff` options from 4.3.0 + '@smithy/util-retry@^4.3.0', smithyDep('@smithy/util-waiter'), 'cdk-from-cfn', 'chalk@^4', diff --git a/packages/@aws-cdk/toolkit-lib/.projen/deps.json b/packages/@aws-cdk/toolkit-lib/.projen/deps.json index 6476f8f4d..925d4ec7c 100644 --- a/packages/@aws-cdk/toolkit-lib/.projen/deps.json +++ b/packages/@aws-cdk/toolkit-lib/.projen/deps.json @@ -338,7 +338,7 @@ }, { "name": "@smithy/util-retry", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 4dba16e75..3e62e1dbd 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -17,7 +17,7 @@ export type SdkRetryStrategy = ConfiguredRetryStrategy | AdaptiveRetryStrategy; * standard setting for it, and we tune it per client. * * The strategy holds per-client state (the retry quota, and in adaptive mode the client-side - * rate limiter), so build one for every SDK client rather than sharing it. + * rate limiter), so don't share one across services: throttling on one would slow the others. * * @param defaultMaxAttempts - total number of attempts, including the initial call, if the user has not set one * @param backoffMs - delay in milliseconds before the given attempt diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index 72eeea7be..f713911fd 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -741,7 +741,7 @@ export class SDK { requestHandler, logger: logger ? makeSdkLoggerSafeByBindingThis(logger) : undefined, }; - this.stsRetryStrategy = sdkRetryStrategy(3, (attempt) => 100 * (2 ** attempt), retrySettings); + this.stsRetryStrategy = sdkRetryStrategy(3, cappedExponentialBackoff(100, 15_000), retrySettings); this.customUserAgent = defaultCliUserAgent(); this.currentRegion = region; } diff --git a/packages/@aws-cdk/toolkit-lib/package.json b/packages/@aws-cdk/toolkit-lib/package.json index b96e73cf0..24c360601 100644 --- a/packages/@aws-cdk/toolkit-lib/package.json +++ b/packages/@aws-cdk/toolkit-lib/package.json @@ -116,7 +116,7 @@ "@smithy/middleware-endpoint": "^4", "@smithy/property-provider": "^4", "@smithy/shared-ini-file-loader": "^4", - "@smithy/util-retry": "^4", + "@smithy/util-retry": "^4.3.0", "@smithy/util-waiter": "^4", "cdk-from-cfn": "^0.344.0", "chalk": "^4", diff --git a/packages/aws-cdk/THIRD_PARTY_LICENSES b/packages/aws-cdk/THIRD_PARTY_LICENSES index af0e8cfab..7eabf9c07 100644 --- a/packages/aws-cdk/THIRD_PARTY_LICENSES +++ b/packages/aws-cdk/THIRD_PARTY_LICENSES @@ -10414,7 +10414,7 @@ Apache License ---------------- -** @smithy/util-retry@4.5.5 - https://www.npmjs.com/package/@smithy/util-retry/v/4.5.5 | Apache-2.0 +** @smithy/util-retry@4.6.2 - https://www.npmjs.com/package/@smithy/util-retry/v/4.6.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/yarn.lock b/yarn.lock index df3245a8a..6760d0e2e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -552,7 +552,7 @@ __metadata: "@smithy/middleware-endpoint": "npm:^4" "@smithy/property-provider": "npm:^4" "@smithy/shared-ini-file-loader": "npm:^4" - "@smithy/util-retry": "npm:^4" + "@smithy/util-retry": "npm:^4.3.0" "@smithy/util-stream": "npm:^4.8.2" "@smithy/util-waiter": "npm:^4" "@stylistic/eslint-plugin": "npm:^3" @@ -4176,13 +4176,13 @@ __metadata: languageName: node linkType: hard -"@smithy/util-retry@npm:^4": - version: 4.5.5 - resolution: "@smithy/util-retry@npm:4.5.5" +"@smithy/util-retry@npm:^4, @smithy/util-retry@npm:^4.3.0": + version: 4.6.2 + resolution: "@smithy/util-retry@npm:4.6.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/984f758718f6950b847e4470feb047628c5cbe16af5a9b4134ba2362400011497d02c600112e5a79806f482690df1b7129534c30b0eaa1a47bc972127099a052 + checksum: 10c0/3eb066c24c900a59abc9289d5b4fee3ff9d6259407c9bcf3b2555bacc62713dcb456aa19d1511d59db91b5a60b1bd7a7d8ba6e3cb0e42cf8f3afa65513650dd6 languageName: node linkType: hard From 9dc68ff58e8d60dadde96b07cf1018ef4f5192a0 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 14:47:04 -0500 Subject: [PATCH 09/17] chore: link the evidence for the @smithy/util-retry 4.3.0 minimum Point the comment at the change that added the `maxAttempts` and `backoff` options to AdaptiveRetryStrategy (smithy-typescript#1922) and at the 4.3.0 changelog entry that shipped it. This corrects the previous commit, which said older versions also drop our max attempts: they accept it as the first constructor argument, and only the options object is ignored. --- .projenrc.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.projenrc.ts b/.projenrc.ts index f56836732..25e525461 100644 --- a/.projenrc.ts +++ b/.projenrc.ts @@ -977,7 +977,9 @@ const toolkitLib = configureProject( smithyDep('@smithy/middleware-endpoint'), smithyDep('@smithy/property-provider'), smithyDep('@smithy/shared-ini-file-loader'), - // AdaptiveRetryStrategy only honours the `maxAttempts` and `backoff` options from 4.3.0 + // AdaptiveRetryStrategy accepts the `maxAttempts` and `backoff` options we pass only from 4.3.0: + // https://github.com/smithy-lang/smithy-typescript/pull/1922/changes#diff-9fc896562a39cfba7f662ba86c13f140d4245ee45884b3fe9d79769e00a40ff7R14 + // https://github.com/smithy-lang/smithy-typescript/blob/%40smithy/util-retry%404.3.0/packages/util-retry/CHANGELOG.md?plain=1#L3-L8 '@smithy/util-retry@^4.3.0', smithyDep('@smithy/util-waiter'), 'cdk-from-cfn', From 82d8102b1939d645a4afbef1298f4c3b5632c8ec Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 14:56:15 -0500 Subject: [PATCH 10/17] chore(deps): require @smithy/* ^4.3.0 for all packages Raise the minimum in smithyDep() instead of overriding only @smithy/util-retry, and move the explanation and links onto smithyDep(). This supersedes the util-retry-only override from the previous commits. Without a raised minimum, consumers who upgrade toolkit-lib keep whatever @smithy/util-retry their lockfile already has, as long as it satisfies the range. Versions before 4.3.0 ignore the options we pass to AdaptiveRetryStrategy. Re-resolving the range moves the bundled Smithy packages to their latest 4.x releases. --- .projenrc.ts | 12 +- .../cli-integ/.projen/deps.json | 4 +- .../@aws-cdk-testing/cli-integ/package.json | 4 +- .../@aws-cdk/cdk-assets-lib/.projen/deps.json | 4 +- packages/@aws-cdk/cdk-assets-lib/package.json | 4 +- .../@aws-cdk/toolkit-lib/.projen/deps.json | 8 +- packages/@aws-cdk/toolkit-lib/package.json | 8 +- packages/aws-cdk/.projen/deps.json | 14 +-- packages/aws-cdk/THIRD_PARTY_LICENSES | 12 +- packages/aws-cdk/package.json | 14 +-- yarn.lock | 108 +++++++++--------- 11 files changed, 97 insertions(+), 95 deletions(-) diff --git a/.projenrc.ts b/.projenrc.ts index 25e525461..d556ee164 100644 --- a/.projenrc.ts +++ b/.projenrc.ts @@ -67,12 +67,17 @@ function sdkDep(name: string) { /** * Same as `sdkDepForLib`, but for smithy + * + * The minimum is 4.3.0 because that's where AdaptiveRetryStrategy starts accepting the `maxAttempts` + * and `backoff` options we pass: + * https://github.com/smithy-lang/smithy-typescript/pull/1922/changes#diff-9fc896562a39cfba7f662ba86c13f140d4245ee45884b3fe9d79769e00a40ff7R14 + * https://github.com/smithy-lang/smithy-typescript/blob/%40smithy/util-retry%404.3.0/packages/util-retry/CHANGELOG.md?plain=1#L3-L8 */ function smithyDep(name: string) { if (!name.startsWith('@smithy/')) { throw new Error('Must be a Smithy package'); } - return `${name}@^4`; + return `${name}@^4.3.0`; } const BUNDLED_LICENSES = [ @@ -977,10 +982,7 @@ const toolkitLib = configureProject( smithyDep('@smithy/middleware-endpoint'), smithyDep('@smithy/property-provider'), smithyDep('@smithy/shared-ini-file-loader'), - // AdaptiveRetryStrategy accepts the `maxAttempts` and `backoff` options we pass only from 4.3.0: - // https://github.com/smithy-lang/smithy-typescript/pull/1922/changes#diff-9fc896562a39cfba7f662ba86c13f140d4245ee45884b3fe9d79769e00a40ff7R14 - // https://github.com/smithy-lang/smithy-typescript/blob/%40smithy/util-retry%404.3.0/packages/util-retry/CHANGELOG.md?plain=1#L3-L8 - '@smithy/util-retry@^4.3.0', + smithyDep('@smithy/util-retry'), smithyDep('@smithy/util-waiter'), 'cdk-from-cfn', 'chalk@^4', diff --git a/packages/@aws-cdk-testing/cli-integ/.projen/deps.json b/packages/@aws-cdk-testing/cli-integ/.projen/deps.json index f78ccdfc4..e96d2dd21 100644 --- a/packages/@aws-cdk-testing/cli-integ/.projen/deps.json +++ b/packages/@aws-cdk-testing/cli-integ/.projen/deps.json @@ -221,12 +221,12 @@ }, { "name": "@smithy/types", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/util-retry", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { diff --git a/packages/@aws-cdk-testing/cli-integ/package.json b/packages/@aws-cdk-testing/cli-integ/package.json index 55384522f..c22f0fa1e 100644 --- a/packages/@aws-cdk-testing/cli-integ/package.json +++ b/packages/@aws-cdk-testing/cli-integ/package.json @@ -89,8 +89,8 @@ "@aws-sdk/credential-providers": "^3", "@cdklabs/cdk-atmosphere-client": "^0.0.128", "@octokit/rest": "^20", - "@smithy/types": "^4", - "@smithy/util-retry": "^4", + "@smithy/types": "^4.3.0", + "@smithy/util-retry": "^4.3.0", "chalk": "^4", "cross-spawn": "^7.0.6", "fast-glob": "^3.3.3", diff --git a/packages/@aws-cdk/cdk-assets-lib/.projen/deps.json b/packages/@aws-cdk/cdk-assets-lib/.projen/deps.json index 25bc9c978..41273e739 100644 --- a/packages/@aws-cdk/cdk-assets-lib/.projen/deps.json +++ b/packages/@aws-cdk/cdk-assets-lib/.projen/deps.json @@ -181,12 +181,12 @@ }, { "name": "@smithy/config-resolver", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/node-config-provider", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { diff --git a/packages/@aws-cdk/cdk-assets-lib/package.json b/packages/@aws-cdk/cdk-assets-lib/package.json index e332455cd..29ca768ec 100644 --- a/packages/@aws-cdk/cdk-assets-lib/package.json +++ b/packages/@aws-cdk/cdk-assets-lib/package.json @@ -75,8 +75,8 @@ "@aws-sdk/client-sts": "^3", "@aws-sdk/credential-providers": "^3", "@aws-sdk/lib-storage": "^3", - "@smithy/config-resolver": "^4", - "@smithy/node-config-provider": "^4", + "@smithy/config-resolver": "^4.3.0", + "@smithy/node-config-provider": "^4.3.0", "cross-spawn": "^7.0.6", "fast-glob": "^3.3.3", "mime": "^2", diff --git a/packages/@aws-cdk/toolkit-lib/.projen/deps.json b/packages/@aws-cdk/toolkit-lib/.projen/deps.json index 925d4ec7c..a48869486 100644 --- a/packages/@aws-cdk/toolkit-lib/.projen/deps.json +++ b/packages/@aws-cdk/toolkit-lib/.projen/deps.json @@ -323,17 +323,17 @@ }, { "name": "@smithy/middleware-endpoint", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/property-provider", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/shared-ini-file-loader", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { @@ -343,7 +343,7 @@ }, { "name": "@smithy/util-waiter", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { diff --git a/packages/@aws-cdk/toolkit-lib/package.json b/packages/@aws-cdk/toolkit-lib/package.json index 24c360601..b832e2a80 100644 --- a/packages/@aws-cdk/toolkit-lib/package.json +++ b/packages/@aws-cdk/toolkit-lib/package.json @@ -113,11 +113,11 @@ "@aws-sdk/credential-providers": "^3", "@aws-sdk/ec2-metadata-service": "^3", "@aws-sdk/lib-storage": "^3", - "@smithy/middleware-endpoint": "^4", - "@smithy/property-provider": "^4", - "@smithy/shared-ini-file-loader": "^4", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/property-provider": "^4.3.0", + "@smithy/shared-ini-file-loader": "^4.3.0", "@smithy/util-retry": "^4.3.0", - "@smithy/util-waiter": "^4", + "@smithy/util-waiter": "^4.3.0", "cdk-from-cfn": "^0.344.0", "chalk": "^4", "chokidar": "^4", diff --git a/packages/aws-cdk/.projen/deps.json b/packages/aws-cdk/.projen/deps.json index d3448cb21..f172f5581 100644 --- a/packages/aws-cdk/.projen/deps.json +++ b/packages/aws-cdk/.projen/deps.json @@ -339,37 +339,37 @@ }, { "name": "@smithy/middleware-endpoint", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/property-provider", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/shared-ini-file-loader", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/smithy-client", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/types", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/util-retry", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { "name": "@smithy/util-waiter", - "version": "^4", + "version": "^4.3.0", "type": "runtime" }, { diff --git a/packages/aws-cdk/THIRD_PARTY_LICENSES b/packages/aws-cdk/THIRD_PARTY_LICENSES index 7eabf9c07..5d833bdc1 100644 --- a/packages/aws-cdk/THIRD_PARTY_LICENSES +++ b/packages/aws-cdk/THIRD_PARTY_LICENSES @@ -8156,7 +8156,7 @@ SOFTWARE. ---------------- -** @smithy/config-resolver@4.6.5 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.6.5 | Apache-2.0 +** @smithy/config-resolver@4.7.2 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -8772,7 +8772,7 @@ Apache License ---------------- -** @smithy/middleware-endpoint@4.6.5 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.6.5 | Apache-2.0 +** @smithy/middleware-endpoint@4.7.2 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -8977,7 +8977,7 @@ Apache License ---------------- -** @smithy/node-config-provider@4.5.5 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.5.5 | Apache-2.0 +** @smithy/node-config-provider@4.6.2 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.6.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -9387,7 +9387,7 @@ Apache License ---------------- -** @smithy/property-provider@4.4.5 - https://www.npmjs.com/package/@smithy/property-provider/v/4.4.5 | Apache-2.0 +** @smithy/property-provider@4.5.2 - https://www.npmjs.com/package/@smithy/property-provider/v/4.5.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -9592,7 +9592,7 @@ Apache License ---------------- -** @smithy/shared-ini-file-loader@4.6.5 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.6.5 | Apache-2.0 +** @smithy/shared-ini-file-loader@4.7.2 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -10002,7 +10002,7 @@ Apache License ---------------- -** @smithy/smithy-client@4.14.5 - https://www.npmjs.com/package/@smithy/smithy-client/v/4.14.5 | Apache-2.0 +** @smithy/smithy-client@4.15.2 - https://www.npmjs.com/package/@smithy/smithy-client/v/4.15.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/packages/aws-cdk/package.json b/packages/aws-cdk/package.json index 47131f8a2..d3896fc92 100644 --- a/packages/aws-cdk/package.json +++ b/packages/aws-cdk/package.json @@ -116,13 +116,13 @@ "@aws-sdk/credential-providers": "^3", "@aws-sdk/ec2-metadata-service": "^3", "@aws-sdk/lib-storage": "^3", - "@smithy/middleware-endpoint": "^4", - "@smithy/property-provider": "^4", - "@smithy/shared-ini-file-loader": "^4", - "@smithy/smithy-client": "^4", - "@smithy/types": "^4", - "@smithy/util-retry": "^4", - "@smithy/util-waiter": "^4", + "@smithy/middleware-endpoint": "^4.3.0", + "@smithy/property-provider": "^4.3.0", + "@smithy/shared-ini-file-loader": "^4.3.0", + "@smithy/smithy-client": "^4.3.0", + "@smithy/types": "^4.3.0", + "@smithy/util-retry": "^4.3.0", + "@smithy/util-waiter": "^4.3.0", "camelcase": "^6", "cdk-from-cfn": "^0.344.0", "chalk": "^4", diff --git a/yarn.lock b/yarn.lock index 6760d0e2e..26142b5f5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -30,8 +30,8 @@ __metadata: "@cdklabs/cdk-atmosphere-client": "npm:^0.0.128" "@cdklabs/eslint-plugin": "npm:^2.0.28" "@octokit/rest": "npm:^20" - "@smithy/types": "npm:^4" - "@smithy/util-retry": "npm:^4" + "@smithy/types": "npm:^4.3.0" + "@smithy/util-retry": "npm:^4.3.0" "@stylistic/eslint-plugin": "npm:^3" "@types/fs-extra": "npm:^11" "@types/jest": "npm:^29.5.14" @@ -127,8 +127,8 @@ __metadata: "@aws-sdk/credential-providers": "npm:^3" "@aws-sdk/lib-storage": "npm:^3" "@cdklabs/eslint-plugin": "npm:^2.0.28" - "@smithy/config-resolver": "npm:^4" - "@smithy/node-config-provider": "npm:^4" + "@smithy/config-resolver": "npm:^4.3.0" + "@smithy/node-config-provider": "npm:^4.3.0" "@stylistic/eslint-plugin": "npm:^3" "@types/jest": "npm:^29.5.14" "@types/mime": "npm:^2" @@ -549,12 +549,12 @@ __metadata: "@jest/globals": "npm:^29.7.0" "@jest/types": "npm:^29.6.3" "@microsoft/api-extractor": "npm:^7.60.1" - "@smithy/middleware-endpoint": "npm:^4" - "@smithy/property-provider": "npm:^4" - "@smithy/shared-ini-file-loader": "npm:^4" + "@smithy/middleware-endpoint": "npm:^4.3.0" + "@smithy/property-provider": "npm:^4.3.0" + "@smithy/shared-ini-file-loader": "npm:^4.3.0" "@smithy/util-retry": "npm:^4.3.0" "@smithy/util-stream": "npm:^4.8.2" - "@smithy/util-waiter": "npm:^4" + "@smithy/util-waiter": "npm:^4.3.0" "@stylistic/eslint-plugin": "npm:^3" "@types/fs-extra": "npm:^11" "@types/jest": "npm:^29.5.14" @@ -4040,17 +4040,17 @@ __metadata: languageName: node linkType: hard -"@smithy/config-resolver@npm:^4": - version: 4.6.5 - resolution: "@smithy/config-resolver@npm:4.6.5" +"@smithy/config-resolver@npm:^4.3.0": + version: 4.7.2 + resolution: "@smithy/config-resolver@npm:4.7.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/fd2bce8497861f8b5449765c5a6926195a7dd3299e9b697d5f146b3bd892535e42fe5d4537793dd3de51cf98d78ca1f26e1db46bb1680eb83767f7bf14c744e5 + checksum: 10c0/ca61aba7cf9655ecd98a2bb883d94ee089fc1ebb3ec0e6c36f9db89a566bc7320bd5088720336d3fa4a8ddc82d3bc08d691859026f7bed0c1e815056ec250753 languageName: node linkType: hard -"@smithy/core@npm:^3.29.0, @smithy/core@npm:^3.33.2, @smithy/core@npm:^3.36.0, @smithy/core@npm:^3.38.0, @smithy/core@npm:^3.39.0, @smithy/core@npm:^3.40.0": +"@smithy/core@npm:^3.33.2, @smithy/core@npm:^3.36.0, @smithy/core@npm:^3.38.0, @smithy/core@npm:^3.39.0, @smithy/core@npm:^3.40.0": version: 3.40.0 resolution: "@smithy/core@npm:3.40.0" dependencies: @@ -4094,23 +4094,23 @@ __metadata: languageName: node linkType: hard -"@smithy/middleware-endpoint@npm:^4": - version: 4.6.5 - resolution: "@smithy/middleware-endpoint@npm:4.6.5" +"@smithy/middleware-endpoint@npm:^4.3.0": + version: 4.7.2 + resolution: "@smithy/middleware-endpoint@npm:4.7.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/3a468a6ba53953eb7162388fc5355b33752e93a36e45ea2f2f84da6b1bb0a5c7c36baf125c8c75a8b65684f1a6e45c88c562722822dfe3499e1f8e2fdbaec59d + checksum: 10c0/0b90badc6d0314b789f2748ae5afc721e908d05c9b5c9007bf9ef696245a96864baf10cbea9c7cc04d082bdad92c0a328953d66cce7b51c5196ffe171501a0db languageName: node linkType: hard -"@smithy/node-config-provider@npm:^4": - version: 4.5.5 - resolution: "@smithy/node-config-provider@npm:4.5.5" +"@smithy/node-config-provider@npm:^4.3.0": + version: 4.6.2 + resolution: "@smithy/node-config-provider@npm:4.6.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/709537f42625422acf9ea6e727efaf3785c2cf889f390679a7d832b2fcb618232f457e0a4ea8161bb5c70226e4defb7a5b5f23d346734fff26f694908773f703 + checksum: 10c0/4ca8e6cf20230059c0424e8707d19e347634fa2edd69f3c8ff2bc0bcdb53c3ef3cfe6a6d8ec38b9daf9d89aad0db5f666d00a5e42f07b1675a300e14863c9c90 languageName: node linkType: hard @@ -4125,23 +4125,23 @@ __metadata: languageName: node linkType: hard -"@smithy/property-provider@npm:^4": - version: 4.4.5 - resolution: "@smithy/property-provider@npm:4.4.5" +"@smithy/property-provider@npm:^4.3.0": + version: 4.5.2 + resolution: "@smithy/property-provider@npm:4.5.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/bc8e6128b12ca8eacac980d598e0bb88daafb4e644185c964276a0407cd4d19c25894b9f8c5cea9a14188c1f5905d49d348c0ae72ad372509efcaff04e55c041 + checksum: 10c0/a778f1f44cff3f269ad0364b26f48c550a823a0f84990979289f8395b37276f9db509ed3bdad7ecd9e0612ec0517254a41ab3f07336c7b7d0e86a108c689015b languageName: node linkType: hard -"@smithy/shared-ini-file-loader@npm:^4": - version: 4.6.5 - resolution: "@smithy/shared-ini-file-loader@npm:4.6.5" +"@smithy/shared-ini-file-loader@npm:^4.3.0": + version: 4.7.2 + resolution: "@smithy/shared-ini-file-loader@npm:4.7.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/f6983638e0c795e06382b2615f373043a0157edfcdf8aaf0a9497bf5c05c4f00d787e4a0891b9163b6645fca54fa8c9e104c13fb329023e3f5df72b304b9fd1c + checksum: 10c0/c36a5b8528eb8a1bcc87b8878a80d54f41ef8551e3cc49de3974dd92335d76144b257fe657061fcf74750dd9c54cee1963cc2a0ba09a12608975a7389ddc8825 languageName: node linkType: hard @@ -4156,18 +4156,18 @@ __metadata: languageName: node linkType: hard -"@smithy/smithy-client@npm:^4": - version: 4.14.5 - resolution: "@smithy/smithy-client@npm:4.14.5" +"@smithy/smithy-client@npm:^4.3.0": + version: 4.15.2 + resolution: "@smithy/smithy-client@npm:4.15.2" dependencies: - "@smithy/core": "npm:^3.29.0" - "@smithy/types": "npm:^4.15.1" + "@smithy/core": "npm:^3.33.2" + "@smithy/types": "npm:^4.17.2" tslib: "npm:^2.6.2" - checksum: 10c0/6d6a385f8198f6396e879ead608885db1e29661af8cd70599748a820e4c4359ecb9b1ead0bd0cf0ede6c570ce5de32bb3ce437c536b3e48868688a6f9a6fdfca + checksum: 10c0/1a1e1a667c509ae811c4682dceb9a7ebd47affa7f7192e48df79e127988b788bc03e7d9929fcaa1dedb20897ddc3002e319498e8d33837e6da91cd8a34ac6589 languageName: node linkType: hard -"@smithy/types@npm:^4, @smithy/types@npm:^4.15.1, @smithy/types@npm:^4.17.2, @smithy/types@npm:^4.19.0, @smithy/types@npm:^4.20.0": +"@smithy/types@npm:^4.17.2, @smithy/types@npm:^4.19.0, @smithy/types@npm:^4.20.0, @smithy/types@npm:^4.3.0": version: 4.20.0 resolution: "@smithy/types@npm:4.20.0" dependencies: @@ -4176,7 +4176,7 @@ __metadata: languageName: node linkType: hard -"@smithy/util-retry@npm:^4, @smithy/util-retry@npm:^4.3.0": +"@smithy/util-retry@npm:^4.3.0": version: 4.6.2 resolution: "@smithy/util-retry@npm:4.6.2" dependencies: @@ -4196,13 +4196,13 @@ __metadata: languageName: node linkType: hard -"@smithy/util-waiter@npm:^4": - version: 4.5.5 - resolution: "@smithy/util-waiter@npm:4.5.5" +"@smithy/util-waiter@npm:^4.3.0": + version: 4.6.2 + resolution: "@smithy/util-waiter@npm:4.6.2" dependencies: - "@smithy/core": "npm:^3.29.0" + "@smithy/core": "npm:^3.33.2" tslib: "npm:^2.6.2" - checksum: 10c0/fc29b215df450c8b9eae507b5590646caa343d23833dc01f36ab0a57d794fbb124b58b7930eca8d56eb3f39d005ba80fdbb4ec22e673a19b36a72393934df947 + checksum: 10c0/1d7ac07df8aa869f242daeb03da495314d819c6304f6d67e5c628a4bd8412266e145ee4fb196340c3279b3d613f3b64c674816ac41199ed6e4544bdffcc53851 languageName: node linkType: hard @@ -5974,13 +5974,13 @@ __metadata: "@aws-sdk/ec2-metadata-service": "npm:^3" "@aws-sdk/lib-storage": "npm:^3" "@cdklabs/eslint-plugin": "npm:^2.0.28" - "@smithy/middleware-endpoint": "npm:^4" - "@smithy/property-provider": "npm:^4" - "@smithy/shared-ini-file-loader": "npm:^4" - "@smithy/smithy-client": "npm:^4" - "@smithy/types": "npm:^4" - "@smithy/util-retry": "npm:^4" - "@smithy/util-waiter": "npm:^4" + "@smithy/middleware-endpoint": "npm:^4.3.0" + "@smithy/property-provider": "npm:^4.3.0" + "@smithy/shared-ini-file-loader": "npm:^4.3.0" + "@smithy/smithy-client": "npm:^4.3.0" + "@smithy/types": "npm:^4.3.0" + "@smithy/util-retry": "npm:^4.3.0" + "@smithy/util-waiter": "npm:^4.3.0" "@stylistic/eslint-plugin": "npm:^3" "@types/fs-extra": "npm:^11" "@types/jest": "npm:^29.5.14" From e4476a74d5df85817db8b9c455112b4abebf5ee9 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Mon, 30 Nov 2026 15:28:35 -0500 Subject: [PATCH 11/17] test(toolkit-lib): trim retry tests and isolate tests from the developer's AWS settings Keep one retry test per branch or deliberate decision in our code, and drop the ones that only exercise parseInt/Number edge cases, the SDK, or code that doesn't exist (credentials-file lookup, default-profile fallback). Add a withEnv() helper that sets or unsets the given variables and restores only those, and use it instead of hand-written save/restore code. Use bockfs for test config files, as the other aws-auth tests do. Unset AWS_MAX_ATTEMPTS and AWS_RETRY_MODE and point AWS_CONFIG_FILE and AWS_SHARED_CREDENTIALS_FILE at /dev/null in the toolkit-lib and aws-cdk Jest setup. Every test that builds an SdkProvider now validates retry settings, so an invalid value in the developer's shell or ~/.aws/config failed unrelated tests. --- .../@aws-cdk/toolkit-lib/test/_helpers/env.ts | 24 ++++ .../test/_helpers/jest-setup-after-env.ts | 8 ++ .../api/aws-auth/awscli-compatible.test.ts | 47 +++---- .../test/api/aws-auth/sdk-provider.test.ts | 27 ++-- .../test/api/aws-auth/sdk-retry.test.ts | 122 ++++-------------- .../test/_helpers/jest-setup-after-env.ts | 8 ++ 6 files changed, 96 insertions(+), 140 deletions(-) create mode 100644 packages/@aws-cdk/toolkit-lib/test/_helpers/env.ts diff --git a/packages/@aws-cdk/toolkit-lib/test/_helpers/env.ts b/packages/@aws-cdk/toolkit-lib/test/_helpers/env.ts new file mode 100644 index 000000000..e87532632 --- /dev/null +++ b/packages/@aws-cdk/toolkit-lib/test/_helpers/env.ts @@ -0,0 +1,24 @@ +/** + * Run code with some environment variables set, or unset where the value is `undefined` + * + * Only the given variables are touched, and each is restored to its original value afterwards. + */ +export async function withEnv(block: () => Promise, env: Record): Promise { + const original = Object.fromEntries(Object.keys(env).map((key) => [key, process.env[key]])); + setEnv(env); + try { + return await block(); + } finally { + setEnv(original); + } +} + +function setEnv(env: Record) { + for (const [key, value] of Object.entries(env)) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } +} diff --git a/packages/@aws-cdk/toolkit-lib/test/_helpers/jest-setup-after-env.ts b/packages/@aws-cdk/toolkit-lib/test/_helpers/jest-setup-after-env.ts index 49c6190a1..0b2fbe8e2 100644 --- a/packages/@aws-cdk/toolkit-lib/test/_helpers/jest-setup-after-env.ts +++ b/packages/@aws-cdk/toolkit-lib/test/_helpers/jest-setup-after-env.ts @@ -34,6 +34,14 @@ import { isPromise } from 'util/types'; // These tests exercise the toolkit, not aws-cdk-lib's template linter. process.env.CDK_VALIDATION = 'false'; +// Keep the developer's own AWS settings out of the tests: retry settings from the shell, and the +// shared config and credentials files. They reach every test that builds an SdkProvider, and an +// invalid value makes provider creation fail. Tests that need any of them set them explicitly. +delete process.env.AWS_MAX_ATTEMPTS; +delete process.env.AWS_RETRY_MODE; +process.env.AWS_CONFIG_FILE = '/dev/null'; +process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; + let tmpDir: string; let oldDir: string; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts index 7b4f1906d..5af667642 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts @@ -4,6 +4,8 @@ import { MetadataService } from '@aws-sdk/ec2-metadata-service'; import * as fs from 'fs-extra'; import { isEc2Instance } from '../../../lib/api/aws-auth/ec2-detection'; import { AwsCliCompatible } from '../../../lib/api/aws-auth/private'; +import bockfs from '../../_helpers/bockfs'; +import { withEnv } from '../../_helpers/env'; import { TestIoHost } from '../../_helpers/test-io-host'; jest.mock('../../../lib/api/aws-auth/ec2-detection', () => ({ isEc2Instance: jest.fn(() => false) })); @@ -324,45 +326,36 @@ describe('AwsCliCompatible.baseConfig region override', () => { }); describe('AwsCliCompatible.baseConfig retry settings', () => { - let workdir: string; - const originalProfile = process.env.AWS_PROFILE; - beforeEach(() => { - workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'awscli-compatible.test')); - const configPath = path.join(workdir, 'config'); - fs.writeFileSync(configPath, '[default]\nmax_attempts = 2\n[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - process.env.AWS_CONFIG_FILE = configPath; - process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; - process.env.AWS_REGION = 'us-east-1'; - delete process.env.AWS_PROFILE; - delete process.env.AWS_DEFAULT_PROFILE; - delete process.env.AWS_MAX_ATTEMPTS; - delete process.env.AWS_RETRY_MODE; + bockfs({ '/home/me/.aws/config': '[default]\nmax_attempts = 2\n[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n' }); }); afterEach(() => { - fs.removeSync(workdir); - if (originalProfile === undefined) { - delete process.env.AWS_PROFILE; - } else { - process.env.AWS_PROFILE = originalProfile; - } - }); + bockfs.restore(); + }); + + /** + * Resolve the base config with only the test's config file and the given profile variable + */ + function baseConfig(profile: string | undefined, awsProfile?: string) { + return withEnv(() => new AwsCliCompatible(ioHelper, {}).baseConfig(profile), { + AWS_CONFIG_FILE: bockfs.path('/home/me/.aws/config'), + AWS_REGION: 'us-east-1', + AWS_PROFILE: awsProfile, + AWS_DEFAULT_PROFILE: undefined, + }); + } test('reads retry settings from the given profile', async () => { - const config = await new AwsCliCompatible(ioHelper, {}).baseConfig('ci'); - expect(config.retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); + expect((await baseConfig('ci')).retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); }); test('reads retry settings from AWS_PROFILE when no profile is given', async () => { - process.env.AWS_PROFILE = 'ci'; - const config = await new AwsCliCompatible(ioHelper, {}).baseConfig(); - expect(config.retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); + expect((await baseConfig(undefined, 'ci')).retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); }); test('reads retry settings from the default profile otherwise', async () => { - const config = await new AwsCliCompatible(ioHelper, {}).baseConfig(); - expect(config.retry).toEqual({ maxAttempts: 2, mode: undefined }); + expect((await baseConfig(undefined)).retry).toEqual({ maxAttempts: 2, mode: undefined }); }); }); diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts index 8a893379f..5120d4e17 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts @@ -23,6 +23,7 @@ import { SdkProvider, AwsCliCompatible, defaultCliUserAgent } from '../../../lib import { PluginHost, Mode } from '../../../lib/api/plugin'; import { withMocked } from '../../_helpers/as-mock'; import bockfs from '../../_helpers/bockfs'; +import { withEnv } from '../../_helpers/env'; import { undoAllSdkMocks } from '../../_helpers/mock-sdk'; import { TestIoHost } from '../../_helpers/test-io-host'; @@ -796,27 +797,17 @@ test('every SDK client gets its own retry strategy', () => { // GIVEN const sdk = new SdkProvider(jest.fn(), 'rgn', { ioHelper, retry: { mode: 'adaptive' } })._makeSdk(jest.fn(), 'rgn'); - // THEN - the retry quota and adaptive rate limiter are per-client state + // THEN - clients are built from the `config` getter, so it must return a new retry strategy on + // every access: strategies hold per-client state (retry quota, adaptive rate limiter), and the SDK + // itself creates one per client expect(sdkConfig(sdk).retryStrategy).not.toBe(sdkConfig(sdk).retryStrategy); }); -test('an invalid retry setting fails when the provider is created, not as a credentials error', async () => { - // GIVEN - const original = process.env.AWS_RETRY_MODE; - process.env.AWS_RETRY_MODE = 'adaptve'; - try { - // THEN - await expect(SdkProvider.withAwsCliCompatibleDefaults({ ioHelper, pluginHost })).rejects.toThrow( - "invalid value provided for retry mode: 'adaptve'", - ); - } finally { - if (original === undefined) { - delete process.env.AWS_RETRY_MODE; - } else { - process.env.AWS_RETRY_MODE = original; - } - } -}); +test('an invalid retry setting fails when the provider is created, not as a credentials error', () => withEnv(async () => { + await expect(SdkProvider.withAwsCliCompatibleDefaults({ ioHelper, pluginHost })).rejects.toThrow( + "invalid value provided for retry mode: 'adaptve'", + ); +}, { AWS_RETRY_MODE: 'adaptve' })); /** * Use object hackery to get the credentials out of the SDK object diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index ab74324b8..12328d83d 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -1,12 +1,11 @@ -import * as os from 'os'; -import * as path from 'path'; import { AdaptiveRetryStrategy, type ConfiguredRetryStrategy } from '@smithy/util-retry'; -import * as fs from 'fs-extra'; import { cappedExponentialBackoff, retrySettings, sdkRetryStrategy, } from '../../../lib/api/aws-auth/private'; +import bockfs from '../../_helpers/bockfs'; +import { withEnv } from '../../_helpers/env'; /** * The top of the jitter window is the delay the schedule asks for, so mocking @@ -23,29 +22,10 @@ function scheduled(attempt: number, baseMs = 1000, capMs = 15_000) { return Math.min(baseMs * (2 ** attempt), capMs); } -const ENV_VARS = ['AWS_MAX_ATTEMPTS', 'AWS_RETRY_MODE', 'AWS_CONFIG_FILE', 'AWS_SHARED_CREDENTIALS_FILE']; -const originalEnv = Object.fromEntries(ENV_VARS.map((key) => [key, process.env[key]])); - -beforeEach(() => { - delete process.env.AWS_MAX_ATTEMPTS; - delete process.env.AWS_RETRY_MODE; - // make sure we don't read the developer's own config files - process.env.AWS_CONFIG_FILE = '/dev/null'; - process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; -}); - afterEach(() => { // `clearMocks` does not restore a spy's implementation, and two tests below rely // on real randomness. jest.restoreAllMocks(); - - for (const [key, value] of Object.entries(originalEnv)) { - if (value === undefined) { - delete process.env[key]; - } else { - process.env[key] = value; - } - } }); describe(cappedExponentialBackoff, () => { @@ -151,21 +131,15 @@ describe(sdkRetryStrategy, () => { return strategy.refreshRetryTokenForRetry(token as any, { errorType: 'TRANSIENT' } as any); } - test.each([undefined, 'standard' as const])('mode %p uses the default attempts and our backoff', async (mode) => { - const strategy = sdkRetryStrategy(7, backoffMs, { mode }); + test('uses the default attempts and our backoff', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, {}); await expect(maxAttemptsOf(strategy)).resolves.toBe(7); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalledWith(1); }); - test('maxAttempts overrides the default number of attempts', async () => { - const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 2 }); - - await expect(maxAttemptsOf(strategy)).resolves.toBe(2); - }); - - test('adaptive mode uses our attempts and backoff', async () => { + test('adaptive mode uses the configured attempts and our backoff', async () => { const strategy = sdkRetryStrategy(7, backoffMs, { mode: 'adaptive', maxAttempts: 2 }); expect(strategy).toBeInstanceOf(AdaptiveRetryStrategy); @@ -177,80 +151,38 @@ describe(sdkRetryStrategy, () => { }); describe(retrySettings, () => { - let workdir: string; - - beforeEach(() => { - workdir = fs.mkdtempSync(path.join(os.tmpdir(), 'sdk-retry.test')); - }); - afterEach(() => { - fs.removeSync(workdir); + bockfs.restore(); }); - function writeConfigFile(contents: string) { - const configPath = path.join(workdir, 'config'); - fs.writeFileSync(configPath, contents); - process.env.AWS_CONFIG_FILE = configPath; - } - - function writeCredentialsFile(contents: string) { - const credentialsPath = path.join(workdir, 'credentials'); - fs.writeFileSync(credentialsPath, contents); - process.env.AWS_SHARED_CREDENTIALS_FILE = credentialsPath; + /** + * Write an AWS config file and return its path, for AWS_CONFIG_FILE + */ + function configFile(contents: string) { + bockfs({ '/home/me/.aws/config': contents }); + return bockfs.path('/home/me/.aws/config'); } - test('reads AWS_MAX_ATTEMPTS and AWS_RETRY_MODE', async () => { - process.env.AWS_MAX_ATTEMPTS = '2'; - process.env.AWS_RETRY_MODE = 'adaptive'; - - await expect(retrySettings('default')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); - }); - - test('reads settings from the profile in the config file', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - + test('reads settings from the profile in the config file', () => withEnv(async () => { await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); - }); - - test('ignores settings in the credentials file', async () => { - writeCredentialsFile('[ci]\nmax_attempts = 4\nretry_mode = adaptive\n'); - - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); - - test('does not fall back to the default profile', async () => { - writeConfigFile('[default]\nmax_attempts = 4\nretry_mode = adaptive\n[profile ci]\nregion = us-east-1\n'); - - await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: undefined, mode: undefined }); - }); - - test('environment variables take precedence over the profile, per setting, and only the used value is validated', async () => { - writeConfigFile('[profile ci]\nmax_attempts = lots\nretry_mode = adaptive\n'); - process.env.AWS_MAX_ATTEMPTS = '2'; + }, { + AWS_CONFIG_FILE: configFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'), + })); + test('environment variables take precedence over the profile, per setting', () => withEnv(async () => { await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 2, mode: 'adaptive' }); - }); - - test('an empty environment variable is invalid and does not fall through to the profile, like the AWS CLI v2', async () => { - writeConfigFile('[profile ci]\nmax_attempts = 4\n'); - process.env.AWS_MAX_ATTEMPTS = ''; + }, { + AWS_CONFIG_FILE: configFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'), + AWS_MAX_ATTEMPTS: '2', + })); - await expect(retrySettings('ci')).rejects.toThrow("invalid value provided for max attempts: '', must be a whole number of at least 1"); - }); - - test.each(['3x', '1.5', '0', '-1'])('rejects max attempts %p, like the AWS CLI v2', async (value) => { - writeConfigFile(`[profile ci]\nmax_attempts = ${value}\n`); - - await expect(retrySettings('ci')).rejects.toThrow( - `invalid value provided for max attempts: '${value}', must be a whole number of at least 1`, - ); - }); - - test.each(['adaptve', 'legacy', ''])('rejects retry mode %p, like the AWS CLI v2', async (mode) => { - process.env.AWS_RETRY_MODE = mode; + test('rejects an invalid max attempts', () => withEnv(async () => { + await expect(retrySettings('default')).rejects.toThrow("invalid value provided for max attempts: 'lots', must be a whole number of at least 1"); + }, { AWS_MAX_ATTEMPTS: 'lots' })); + test('rejects an invalid retry mode', () => withEnv(async () => { await expect(retrySettings('default')).rejects.toThrow( - `invalid value provided for retry mode: '${mode}', must be one of 'standard' or 'adaptive'`, + "invalid value provided for retry mode: 'adaptve', must be one of 'standard' or 'adaptive'", ); - }); + }, { AWS_RETRY_MODE: 'adaptve' })); }); diff --git a/packages/aws-cdk/test/_helpers/jest-setup-after-env.ts b/packages/aws-cdk/test/_helpers/jest-setup-after-env.ts index e063a80c1..30d5f7bbb 100644 --- a/packages/aws-cdk/test/_helpers/jest-setup-after-env.ts +++ b/packages/aws-cdk/test/_helpers/jest-setup-after-env.ts @@ -27,6 +27,14 @@ import { isPromise } from 'util/types'; * */ +// Keep the developer's own AWS settings out of the tests: retry settings from the shell, and the +// shared config and credentials files. They reach every test that builds an SdkProvider, and an +// invalid value makes provider creation fail. Tests that need any of them set them explicitly. +delete process.env.AWS_MAX_ATTEMPTS; +delete process.env.AWS_RETRY_MODE; +process.env.AWS_CONFIG_FILE = '/dev/null'; +process.env.AWS_SHARED_CREDENTIALS_FILE = '/dev/null'; + let tmpDir: string; let oldDir: string; From 0484f943f23918c72b574229beb221c3b9f21a79 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Tue, 1 Dec 2026 09:29:27 -0500 Subject: [PATCH 12/17] refactor(toolkit-lib): configure retries through SdkConfig instead of base credentials Retry settings are not credentials. Move them out of SdkBaseConfig and add an optional SdkConfig.retry, next to httpOptions, for Toolkit users to set explicitly. Like the proxy settings, the Toolkit doesn't read them from the environment; it validates what it is given when it's constructed. This supersedes SdkBaseConfig.retry from earlier commits, which was never released. The CLI keeps honouring AWS_MAX_ATTEMPTS, AWS_RETRY_MODE and the --profile config: SdkProvider.withAwsCliCompatibleDefaults now reads them itself instead of through AwsCliCompatible.baseConfig(). Also reuse resolveProfile() for the CA bundle lookup in proxy-agent, and drop a test that only guarded an intermediate version of this branch. --- .../lib/api/aws-auth/awscli-compatible.ts | 8 ++--- .../lib/api/aws-auth/base-credentials.ts | 34 ++---------------- .../toolkit-lib/lib/api/aws-auth/retry.ts | 6 ++-- .../lib/api/aws-auth/sdk-provider.ts | 12 ++++--- .../toolkit-lib/lib/api/aws-auth/sdk.ts | 6 ++-- .../toolkit-lib/lib/api/aws-auth/types.ts | 33 +++++++++++++++++ .../toolkit-lib/lib/toolkit/toolkit.ts | 9 ++--- .../api/aws-auth/awscli-compatible.test.ts | 36 ------------------- .../test/api/aws-auth/sdk-provider.test.ts | 14 +++++--- .../test/api/aws-auth/sdk-retry.test.ts | 6 ++-- .../test/toolkit/base-credentials.test.ts | 17 +++++++++ packages/aws-cdk/lib/cli/proxy-agent.ts | 6 ++-- 12 files changed, 90 insertions(+), 97 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts index 847f15d33..53ab03b90 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/awscli-compatible.ts @@ -4,10 +4,9 @@ import type { SDKv3CompatibleCredentialProvider } from '@aws-cdk/cli-plugin-cont import { createCredentialChain, fromEnv, fromIni, fromNodeProviderChain } from '@aws-sdk/credential-providers'; import { MetadataService } from '@aws-sdk/ec2-metadata-service'; import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; -import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; +import type { RequestHandlerSettings } from './base-credentials'; import { isEc2Instance } from './ec2-detection'; import { makeCachingProvider } from './provider-caching'; -import { retrySettings } from './retry'; import type { ISdkLogger } from './sdk-logger'; import { AuthenticationError } from '../../toolkit/toolkit-error'; import { IO, type IoHelper } from '../io/private'; @@ -37,14 +36,13 @@ export class AwsCliCompatible { public async baseConfig( profile?: string, region?: string, - ): Promise<{ credentialProvider: SDKv3CompatibleCredentialProvider; defaultRegion: string; retry: SdkRetrySettings }> { + ): Promise<{ credentialProvider: SDKv3CompatibleCredentialProvider; defaultRegion: string }> { const credentialProvider = await this.credentialChainBuilder({ profile, logger: this.logger, }); const defaultRegion = region ?? await this.region(profile); - const retry = await retrySettings(resolveProfile(profile)); - return { credentialProvider, defaultRegion, retry }; + return { credentialProvider, defaultRegion }; } /** diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts index 7b27a4940..e12247419 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/base-credentials.ts @@ -45,36 +45,6 @@ export interface SdkBaseConfig { * The default region to use for SDK calls. */ readonly defaultRegion?: string; - - /** - * Retry settings configured by the user, overriding the toolkit's per-client defaults - * - * The backoff schedule between attempts is not configurable. - * - * @default - read from the environment and the `AWS_PROFILE` or `default` profile - */ - readonly retry?: SdkRetrySettings; -} - -/** - * Retry settings for SDK calls - */ -export interface SdkRetrySettings { - /** - * Total number of attempts, including the initial call - * - * Values below 2 disable retries. - * - * @default - a per-client default chosen by the toolkit - */ - readonly maxAttempts?: number; - - /** - * The retry mode - * - * @default 'standard' - */ - readonly mode?: 'standard' | 'adaptive'; } export interface SdkBaseClientConfig { @@ -113,9 +83,9 @@ export class BaseCredentials { } /** - * Obtain base credentials, base region and retry settings the same way the AWS CLI would + * Obtain base credentials and base region the same way the AWS CLI would * - * Credentials, region and retry settings will be read from the environment first, falling back + * Credentials and region will be read from the environment first, falling back * to INI files or other sources if available. * * The profile name is configurable. diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 3e62e1dbd..95c41cd6a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -1,6 +1,6 @@ import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import { AdaptiveRetryStrategy, ConfiguredRetryStrategy } from '@smithy/util-retry'; -import type { SdkRetrySettings } from './base-credentials'; +import type { SdkRetrySettings } from './types'; import { ToolkitError } from '../../toolkit/toolkit-error'; /** @@ -73,7 +73,7 @@ export async function retrySettings(profile: string): Promise * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/configprovider.py#L145 * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L400-L403 */ -function validateMaxAttempts(maxAttempts: string | undefined): void { +export function validateMaxAttempts(maxAttempts: string | number | undefined): void { if (maxAttempts === undefined) { return; } @@ -96,7 +96,7 @@ function validateMaxAttempts(maxAttempts: string | undefined): void { * * @see https://github.com/aws/aws-cli/blob/c6a386c0cc58c14eaf6ac11191ab59afdbc832b7/awscli/botocore/config.py#L404-L405 */ -function validateMode(mode: string | undefined): asserts mode is SdkRetrySettings['mode'] { +export function validateMode(mode: string | undefined): asserts mode is SdkRetrySettings['mode'] { if (mode !== undefined && mode !== 'standard' && mode !== 'adaptive') { throw new ToolkitError( 'InvalidRetryConfiguration', diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts index eea17b907..f86d03bb5 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk-provider.ts @@ -5,15 +5,17 @@ import { EnvironmentUtils, UNKNOWN_ACCOUNT, UNKNOWN_REGION } from '@aws-cdk/clou import type { ContextLookupRoleOptions } from '@aws-cdk/cloud-assembly-schema'; import type { AssumeRoleCommandInput } from '@aws-sdk/client-sts'; import { fromTemporaryCredentials } from '@aws-sdk/credential-providers'; -import { AwsCliCompatible } from './awscli-compatible'; -import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; +import { AwsCliCompatible, resolveProfile } from './awscli-compatible'; +import type { RequestHandlerSettings } from './base-credentials'; import { cached } from './cached'; import { CredentialPlugins } from './credential-plugins'; import { makeCachingProvider } from './provider-caching'; +import { retrySettings } from './retry'; import { SDK } from './sdk'; import type { UserAgentMetadata } from './sdk'; import type { ISdkLogger } from './sdk-logger'; import { callTrace, traceMemberMethods } from './tracing'; +import type { SdkRetrySettings } from './types'; import { AuthenticationError } from '../../toolkit/toolkit-error'; import { formatErrorMessage } from '../../util'; import type { IoHelper } from '../io/private'; @@ -116,7 +118,8 @@ export class SdkProvider { * Create a new SdkProvider which gets its defaults in a way that behaves like the AWS CLI does * * The AWS SDK for JS behaves slightly differently from the AWS CLI in a number of ways; see the - * class `AwsCliCompatible` for the details. + * class `AwsCliCompatible` for the details. Retry settings are read from the environment and the + * profile, see `retrySettings`. * * @param options - Options for the default SDK provider * @param profile - Profile to read from ~/.aws @@ -126,7 +129,8 @@ export class SdkProvider { public static async withAwsCliCompatibleDefaults(options: Omit, profile?: string, region?: string) { callTrace(SdkProvider.withAwsCliCompatibleDefaults.name, SdkProvider.constructor.name, options.logger); const config = await new AwsCliCompatible(options.ioHelper, options.requestHandler ?? {}, options.logger).baseConfig(profile, region); - return new SdkProvider(config.credentialProvider, config.defaultRegion, { ...options, retry: config.retry }); + const retry = await retrySettings(resolveProfile(profile)); + return new SdkProvider(config.credentialProvider, config.defaultRegion, { ...options, retry }); } public readonly defaultRegion: string; diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts index f713911fd..634592f8a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/sdk.ts @@ -418,12 +418,13 @@ import { Upload } from '@aws-sdk/lib-storage'; import { getEndpointFromInstructions } from '@smithy/middleware-endpoint'; import type { WaiterResult } from '@smithy/util-waiter'; import { AccountAccessKeyCache } from './account-cache'; -import type { RequestHandlerSettings, SdkRetrySettings } from './base-credentials'; +import type { RequestHandlerSettings } from './base-credentials'; import { cachedAsync } from './cached'; import { cappedExponentialBackoff, sdkRetryStrategy, type SdkRetryStrategy } from './retry'; import type { ISdkLogger } from './sdk-logger'; import type { Account } from './sdk-provider'; import { traceMemberMethods } from './tracing'; +import type { SdkRetrySettings } from './types'; import { defaultCliUserAgent } from './user-agent'; import { forceS3PathStyle } from '../../private/tools'; import { AuthenticationError, ToolkitError } from '../../toolkit/toolkit-error'; @@ -750,7 +751,8 @@ export class SDK { * The configuration to create SDK clients with * * Every access builds a new retry strategy, so each client gets its own retry quota and - * adaptive rate limiter, as it would without an explicit strategy. + * adaptive rate limiter, as it would without an explicit strategy. STS clients are the + * exception: they share `stsRetryStrategy`, which is fine because they all call STS. * * The legacy User-Agent string is passed through unchanged as the first token, * so it looks exactly like before. Metadata follows as separate tokens. diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts index 49ad6b7f5..c8d5012a2 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts @@ -16,6 +16,39 @@ export interface SdkConfig { * HTTP options for SDK */ readonly httpOptions?: SdkHttpOptions; + + /** + * Retry settings for SDK calls + * + * The `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables and the shared config + * file are not read. + * + * @default - the toolkit's per-client defaults + */ + readonly retry?: SdkRetrySettings; +} + +/** + * Retry settings for SDK calls + * + * The backoff schedule between attempts is not configurable. + */ +export interface SdkRetrySettings { + /** + * Total number of attempts, including the initial call + * + * Values below 2 disable retries. + * + * @default - a per-client default chosen by the toolkit + */ + readonly maxAttempts?: number; + + /** + * The retry mode + * + * @default 'standard' + */ + readonly mode?: 'standard' | 'adaptive'; } /** diff --git a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts index 19226ff49..811db148d 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/toolkit/toolkit.ts @@ -69,8 +69,8 @@ import { type SdkBaseClientConfig, type SdkConfig, } from '../api/aws-auth'; -import { resolveProfile, sdkRequestHandler } from '../api/aws-auth/awscli-compatible'; -import { IoHostSdkLogger, retrySettings, SdkProvider } from '../api/aws-auth/private'; +import { sdkRequestHandler } from '../api/aws-auth/awscli-compatible'; +import { IoHostSdkLogger, SdkProvider, validateMaxAttempts, validateMode } from '../api/aws-auth/private'; import { Bootstrapper } from '../api/bootstrap'; import type { ICloudAssemblySource, StackSelector } from '../api/cloud-assembly'; import { CachedCloudAssembly, StackSelectionStrategy } from '../api/cloud-assembly'; @@ -233,6 +233,8 @@ export class Toolkit extends CloudAssemblySourceBuilder { this.ioHost = withTrimmedWhitespace(ioHost); this.baseCredentials = props.sdkConfig?.baseCredentials ?? BaseCredentials.awsCliCompatible(); + validateMaxAttempts(props.sdkConfig?.retry?.maxAttempts); + validateMode(props.sdkConfig?.retry?.mode); this.unstableFeatures = props.unstableFeatures ?? []; } @@ -254,8 +256,7 @@ export class Toolkit extends CloudAssemblySourceBuilder { logger: new IoHostSdkLogger(ioHelper), pluginHost: this.pluginHost, requestHandler: clientConfig.requestHandler, - // Base credentials that don't know about profiles still get the environment and default profile - retry: config.retry ?? await retrySettings(resolveProfile()), + retry: this.props.sdkConfig?.retry ?? {}, }); } diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts index 5af667642..3987aa075 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/awscli-compatible.test.ts @@ -4,8 +4,6 @@ import { MetadataService } from '@aws-sdk/ec2-metadata-service'; import * as fs from 'fs-extra'; import { isEc2Instance } from '../../../lib/api/aws-auth/ec2-detection'; import { AwsCliCompatible } from '../../../lib/api/aws-auth/private'; -import bockfs from '../../_helpers/bockfs'; -import { withEnv } from '../../_helpers/env'; import { TestIoHost } from '../../_helpers/test-io-host'; jest.mock('../../../lib/api/aws-auth/ec2-detection', () => ({ isEc2Instance: jest.fn(() => false) })); @@ -325,40 +323,6 @@ describe('AwsCliCompatible.baseConfig region override', () => { }); }); -describe('AwsCliCompatible.baseConfig retry settings', () => { - beforeEach(() => { - bockfs({ '/home/me/.aws/config': '[default]\nmax_attempts = 2\n[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n' }); - }); - - afterEach(() => { - bockfs.restore(); - }); - - /** - * Resolve the base config with only the test's config file and the given profile variable - */ - function baseConfig(profile: string | undefined, awsProfile?: string) { - return withEnv(() => new AwsCliCompatible(ioHelper, {}).baseConfig(profile), { - AWS_CONFIG_FILE: bockfs.path('/home/me/.aws/config'), - AWS_REGION: 'us-east-1', - AWS_PROFILE: awsProfile, - AWS_DEFAULT_PROFILE: undefined, - }); - } - - test('reads retry settings from the given profile', async () => { - expect((await baseConfig('ci')).retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); - }); - - test('reads retry settings from AWS_PROFILE when no profile is given', async () => { - expect((await baseConfig(undefined, 'ci')).retry).toEqual({ maxAttempts: 4, mode: 'adaptive' }); - }); - - test('reads retry settings from the default profile otherwise', async () => { - expect((await baseConfig(undefined)).retry).toEqual({ maxAttempts: 2, mode: undefined }); - }); -}); - describe('Session token', () => { beforeEach(() => { process.env.AWS_ACCESS_KEY_ID = 'foo'; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts index 5120d4e17..c7820e7cb 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-provider.test.ts @@ -803,11 +803,15 @@ test('every SDK client gets its own retry strategy', () => { expect(sdkConfig(sdk).retryStrategy).not.toBe(sdkConfig(sdk).retryStrategy); }); -test('an invalid retry setting fails when the provider is created, not as a credentials error', () => withEnv(async () => { - await expect(SdkProvider.withAwsCliCompatibleDefaults({ ioHelper, pluginHost })).rejects.toThrow( - "invalid value provided for retry mode: 'adaptve'", - ); -}, { AWS_RETRY_MODE: 'adaptve' })); +test('withAwsCliCompatibleDefaults reads retry settings from the given profile', () => { + bockfs({ '/home/me/.aws/config': '[profile ci]\nretry_mode = adaptive\n' }); + + return withEnv(async () => { + const provider = await SdkProvider.withAwsCliCompatibleDefaults({ ioHelper, pluginHost }, 'ci'); + + expect(sdkConfig(provider._makeSdk(jest.fn(), 'rgn')).retryStrategy.mode).toBe('adaptive'); + }, { AWS_CONFIG_FILE: bockfs.path('/home/me/.aws/config') }); +}); /** * Use object hackery to get the credentials out of the SDK object diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index 12328d83d..dc4351b27 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -131,10 +131,10 @@ describe(sdkRetryStrategy, () => { return strategy.refreshRetryTokenForRetry(token as any, { errorType: 'TRANSIENT' } as any); } - test('uses the default attempts and our backoff', async () => { - const strategy = sdkRetryStrategy(7, backoffMs, {}); + test('standard mode uses the configured attempts and our backoff', async () => { + const strategy = sdkRetryStrategy(7, backoffMs, { maxAttempts: 2 }); - await expect(maxAttemptsOf(strategy)).resolves.toBe(7); + await expect(maxAttemptsOf(strategy)).resolves.toBe(2); await retryOnce(strategy); expect(backoffMs).toHaveBeenCalledWith(1); }); diff --git a/packages/@aws-cdk/toolkit-lib/test/toolkit/base-credentials.test.ts b/packages/@aws-cdk/toolkit-lib/test/toolkit/base-credentials.test.ts index a6567326c..99124a11d 100644 --- a/packages/@aws-cdk/toolkit-lib/test/toolkit/base-credentials.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/toolkit/base-credentials.test.ts @@ -72,3 +72,20 @@ test.each([ delete process.env.AWS_REGION; }); + +test('sdkConfig.retry is used for SDK calls', async () => { + makeSdk.mockRestore(); + const toolkit = new Toolkit({ ioHost, sdkConfig: { baseCredentials: BaseCredentials.none(), retry: { mode: 'adaptive' } } }); + + // Use object hackery to reach the SdkProvider and the SDK client config + const sdkProvider: SdkProvider = await (toolkit as any).sdkProvider('synth'); + const sdk = sdkProvider._makeSdk(jest.fn(), 'rgn'); + + expect((sdk as any).config.retryStrategy.mode).toBe('adaptive'); +}); + +test('invalid sdkConfig.retry is rejected when the Toolkit is created', () => { + expect(() => new Toolkit({ ioHost, sdkConfig: { retry: { maxAttempts: 0 } } })).toThrow( + "invalid value provided for max attempts: '0', must be a whole number of at least 1", + ); +}); diff --git a/packages/aws-cdk/lib/cli/proxy-agent.ts b/packages/aws-cdk/lib/cli/proxy-agent.ts index bc390ed9a..f023d66c3 100644 --- a/packages/aws-cdk/lib/cli/proxy-agent.ts +++ b/packages/aws-cdk/lib/cli/proxy-agent.ts @@ -2,6 +2,7 @@ import * as path from 'node:path'; import { loadSharedConfigFiles } from '@smithy/shared-ini-file-loader'; import * as fs from 'fs-extra'; import { ProxyAgent, proxies } from 'proxy-agent'; +import { resolveProfile } from '../api/aws-auth'; import { ToolkitError } from '../api-private-error'; /** @@ -185,8 +186,7 @@ export class ProxyAgentProvider { * of the active profile in the shared credentials/config files, then the `REQUESTS_CA_BUNDLE` * environment variable. * - * The profile is picked the way `AwsCliCompatible` in toolkit-lib picks it: `--profile`, then - * `AWS_PROFILE`, then `AWS_DEFAULT_PROFILE`, then `default`. + * The profile is picked with `resolveProfile`, the same way as for credentials and region. */ private async caBundlePathFromEnvironment(profile?: string): Promise<{ path: string; source: string } | undefined> { if (process.env.aws_ca_bundle) { @@ -196,7 +196,7 @@ export class ProxyAgentProvider { return { path: process.env.AWS_CA_BUNDLE, source: 'AWS_CA_BUNDLE' }; } - const profileName = profile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE || 'default'; + const profileName = resolveProfile(profile); const profileCaBundle = await this.caBundlePathFromProfile(profileName); if (profileCaBundle) { return { path: profileCaBundle, source: `ca_bundle of profile '${profileName}'` }; From e0ba975598572899f770d6315def0b1959a0d4d5 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Tue, 1 Dec 2026 12:11:57 -0500 Subject: [PATCH 13/17] docs(toolkit-lib): drop redundant note about the default profile fallback retrySettingsFromConfig() takes a required profile, so there is no fallback to state. --- packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index 95c41cd6a..fbf032882 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -109,8 +109,7 @@ export function validateMode(mode: string | undefined): asserts mode is SdkRetry * Read the raw retry settings from the given profile in the shared config file * * Only `~/.aws/config` is read: the credentials file may only hold credentials, and the - * retry settings are documented for the config file only. There is no fallback to the - * `default` profile. + * retry settings are documented for the config file only. * * @see https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html */ From 5f8457ce5b365b5a0ca2be3cc12312a6780058b5 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Tue, 1 Dec 2026 12:25:20 -0500 Subject: [PATCH 14/17] docs(toolkit-lib): drop redundant note from SdkConfig.retry The @default annotation already says the toolkit's defaults apply. --- packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts index c8d5012a2..8225637f4 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts @@ -20,9 +20,6 @@ export interface SdkConfig { /** * Retry settings for SDK calls * - * The `AWS_MAX_ATTEMPTS` and `AWS_RETRY_MODE` environment variables and the shared config - * file are not read. - * * @default - the toolkit's per-client defaults */ readonly retry?: SdkRetrySettings; From afd1d10caffb2449ceffb7da0967d6793ca9827e Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Tue, 1 Dec 2026 13:00:03 -0500 Subject: [PATCH 15/17] docs(toolkit-lib): correct the SdkRetrySettings.maxAttempts range Values below 1 are rejected, so only 1 disables retries. The old wording, 'values below 2 disable retries', predates the validation. --- packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts index 8225637f4..9cbb6bdcc 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/types.ts @@ -34,7 +34,7 @@ export interface SdkRetrySettings { /** * Total number of attempts, including the initial call * - * Values below 2 disable retries. + * Must be a whole number of at least 1. A value of 1 disables retries. * * @default - a per-client default chosen by the toolkit */ From 208b3f4f2aaa595f9247a418ebaad1c29fc1d288 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:41:02 +0000 Subject: [PATCH 16/17] chore: self mutation Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES | 12 ++++++------ packages/cdk-assets/THIRD_PARTY_LICENSES | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES b/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES index 456bdef79..3c502329a 100644 --- a/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES +++ b/packages/@aws-cdk/integ-runner/THIRD_PARTY_LICENSES @@ -8085,7 +8085,7 @@ SOFTWARE. ---------------- -** @smithy/config-resolver@4.6.5 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.6.5 | Apache-2.0 +** @smithy/config-resolver@4.7.2 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -8701,7 +8701,7 @@ Apache License ---------------- -** @smithy/middleware-endpoint@4.6.5 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.6.5 | Apache-2.0 +** @smithy/middleware-endpoint@4.7.2 - https://www.npmjs.com/package/@smithy/middleware-endpoint/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -8906,7 +8906,7 @@ Apache License ---------------- -** @smithy/node-config-provider@4.5.5 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.5.5 | Apache-2.0 +** @smithy/node-config-provider@4.6.2 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.6.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -9316,7 +9316,7 @@ Apache License ---------------- -** @smithy/property-provider@4.4.5 - https://www.npmjs.com/package/@smithy/property-provider/v/4.4.5 | Apache-2.0 +** @smithy/property-provider@4.5.2 - https://www.npmjs.com/package/@smithy/property-provider/v/4.5.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -9521,7 +9521,7 @@ Apache License ---------------- -** @smithy/shared-ini-file-loader@4.6.5 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.6.5 | Apache-2.0 +** @smithy/shared-ini-file-loader@4.7.2 - https://www.npmjs.com/package/@smithy/shared-ini-file-loader/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -10137,7 +10137,7 @@ Apache License ---------------- -** @smithy/util-retry@4.5.5 - https://www.npmjs.com/package/@smithy/util-retry/v/4.5.5 | Apache-2.0 +** @smithy/util-retry@4.6.2 - https://www.npmjs.com/package/@smithy/util-retry/v/4.6.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ diff --git a/packages/cdk-assets/THIRD_PARTY_LICENSES b/packages/cdk-assets/THIRD_PARTY_LICENSES index 6e31780d6..37ae3d4a7 100644 --- a/packages/cdk-assets/THIRD_PARTY_LICENSES +++ b/packages/cdk-assets/THIRD_PARTY_LICENSES @@ -4173,7 +4173,7 @@ SOFTWARE. ---------------- -** @smithy/config-resolver@4.6.5 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.6.5 | Apache-2.0 +** @smithy/config-resolver@4.7.2 - https://www.npmjs.com/package/@smithy/config-resolver/v/4.7.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ @@ -4789,7 +4789,7 @@ Apache License ---------------- -** @smithy/node-config-provider@4.5.5 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.5.5 | Apache-2.0 +** @smithy/node-config-provider@4.6.2 - https://www.npmjs.com/package/@smithy/node-config-provider/v/4.6.2 | Apache-2.0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ From 1ccc6a8756f2808acd7e64a9352a5820b5d9b0b9 Mon Sep 17 00:00:00 2001 From: Eli Polonsky Date: Wed, 2 Dec 2026 15:35:12 -0500 Subject: [PATCH 17/17] fix(toolkit-lib): treat empty retry environment variables as unset An empty `AWS_MAX_ATTEMPTS=` or `AWS_RETRY_MODE=` now falls back to the profile value, like the JavaScript SDK, instead of overriding it and failing validation. CI templates often pass unset variables through this way. This differs from the AWS CLI v2, which treats an empty variable as set. Adds `retrySettings` tests for empty variables, for rejecting `legacy` (as the AWS CLI v2 does), and for validating values from the profile. --- .../toolkit-lib/lib/api/aws-auth/retry.ts | 9 +++++---- .../test/api/aws-auth/sdk-retry.test.ts | 20 +++++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts index fbf032882..5015d6a1a 100644 --- a/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts +++ b/packages/@aws-cdk/toolkit-lib/lib/api/aws-auth/retry.ts @@ -52,13 +52,14 @@ export function sdkRetryStrategy( /** * Read the user's retry settings the way the AWS CLI v2 does * - * Each setting is taken from its environment variable if it is set, even to an empty string, - * and otherwise from the given profile in the shared config file. + * Each setting is taken from its environment variable, and otherwise from the given profile in + * the shared config file. Unlike the AWS CLI v2, an empty environment variable counts as unset, + * like in the JavaScript SDK: CI templates often pass unset variables through that way. */ export async function retrySettings(profile: string): Promise { const fromConfig = await retrySettingsFromConfig(profile); - const maxAttempts = process.env.AWS_MAX_ATTEMPTS ?? fromConfig.maxAttempts; - const mode = process.env.AWS_RETRY_MODE ?? fromConfig.mode; + const maxAttempts = process.env.AWS_MAX_ATTEMPTS || fromConfig.maxAttempts; + const mode = process.env.AWS_RETRY_MODE || fromConfig.mode; validateMaxAttempts(maxAttempts); validateMode(mode); return { maxAttempts: maxAttempts === undefined ? undefined : Number(maxAttempts), mode }; diff --git a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts index dc4351b27..99cf49341 100644 --- a/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts +++ b/packages/@aws-cdk/toolkit-lib/test/api/aws-auth/sdk-retry.test.ts @@ -176,6 +176,14 @@ describe(retrySettings, () => { AWS_MAX_ATTEMPTS: '2', })); + test('empty environment variables fall back to the profile', () => withEnv(async () => { + await expect(retrySettings('ci')).resolves.toEqual({ maxAttempts: 4, mode: 'adaptive' }); + }, { + AWS_CONFIG_FILE: configFile('[profile ci]\nmax_attempts = 4\nretry_mode = adaptive\n'), + AWS_MAX_ATTEMPTS: '', + AWS_RETRY_MODE: '', + })); + test('rejects an invalid max attempts', () => withEnv(async () => { await expect(retrySettings('default')).rejects.toThrow("invalid value provided for max attempts: 'lots', must be a whole number of at least 1"); }, { AWS_MAX_ATTEMPTS: 'lots' })); @@ -185,4 +193,16 @@ describe(retrySettings, () => { "invalid value provided for retry mode: 'adaptve', must be one of 'standard' or 'adaptive'", ); }, { AWS_RETRY_MODE: 'adaptve' })); + + test('rejects legacy retry mode, like the AWS CLI v2', () => withEnv(async () => { + await expect(retrySettings('default')).rejects.toThrow( + "invalid value provided for retry mode: 'legacy', must be one of 'standard' or 'adaptive'", + ); + }, { AWS_RETRY_MODE: 'legacy' })); + + test('validates settings from the profile', () => withEnv(async () => { + await expect(retrySettings('ci')).rejects.toThrow("invalid value provided for max attempts: '0', must be a whole number of at least 1"); + }, { + AWS_CONFIG_FILE: configFile('[profile ci]\nmax_attempts = 0\n'), + })); });