or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-aws-sdk--credential-provider-node

AWS credential provider that sources credentials from a Node.JS environment using a prioritized chain of credential sources.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@aws-sdk/credential-provider-node@3.879.x

To install, run

npx @tessl/cli install tessl/npm-aws-sdk--credential-provider-node@3.879.0

index.mddocs/

AWS Credential Provider Node

AWS credential provider that sources credentials from a Node.js environment using a prioritized chain of credential sources. It automatically attempts to find credentials from environment variables, SSO token cache, web identity tokens, shared credentials/config files, and EC2/ECS Instance Metadata Service in order of precedence.

Package Information

  • Package Name: @aws-sdk/credential-provider-node
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @aws-sdk/credential-provider-node

Core Imports

import { 
  defaultProvider, 
  DefaultProviderInit,
  remoteProvider,
  credentialsWillNeedRefresh,
  credentialsTreatedAsExpired
} from "@aws-sdk/credential-provider-node";

For CommonJS:

const { 
  defaultProvider, 
  DefaultProviderInit,
  remoteProvider,
  credentialsWillNeedRefresh,
  credentialsTreatedAsExpired
} = require("@aws-sdk/credential-provider-node");

Basic Usage

import { defaultProvider } from "@aws-sdk/credential-provider-node";
import { S3Client } from "@aws-sdk/client-s3";

// Simple usage with default settings
const credentialProvider = defaultProvider();
const s3Client = new S3Client({ credentials: credentialProvider });

// Advanced usage with configuration
const credentialProvider = defaultProvider({
  profile: "myprofile",
  timeout: 5000,
  maxRetries: 3,
  logger: console
});

Architecture

The credential provider implements a chain-of-responsibility pattern where providers are invoked sequentially until valid credentials are found:

  1. Environment Variables: Checks AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (skipped if profile is set)
  2. SSO Credentials: Sources from token cache when SSO parameters are provided
  3. Web Identity Tokens: Uses web identity token file for role assumption
  4. Shared Configuration: Reads from ~/.aws/credentials and ~/.aws/config files
  5. Instance Metadata: Retrieves from EC2/ECS Instance Metadata Service

Key Features:

  • Memoization: Credentials are cached until expiration to avoid repeated provider calls
  • Early Termination: Chain stops at first successful provider
  • Error Handling: Detailed error messages with tryNextLink support for recoverable failures
  • Configuration Priority: Profile-based configuration takes precedence over environment variables

Capabilities

Default Provider Function

Creates a memoized credential provider that attempts to find credentials from multiple sources in order of precedence.

/**
 * Creates a credential provider that will attempt to find credentials from the
 * following sources (listed in order of precedence):
 *   * Environment variables exposed via `process.env`
 *   * SSO credentials from token cache
 *   * Web identity token credentials
 *   * Shared credentials and config ini files
 *   * The EC2/ECS Instance Metadata Service
 */
function defaultProvider(init?: DefaultProviderInit): MemoizedProvider<AwsCredentialIdentity>;

/**
 * Configuration options for the default credential provider.
 * This is an intersection type that combines options from multiple credential provider interfaces.
 */
type DefaultProviderInit = FromIniInit &
  FromHttpOptions &
  RemoteProviderInit &
  FromProcessInit &
  (FromSSOInit & Partial<SsoCredentialsParameters>) &
  FromTokenFileInit;

interface MemoizedProvider<T> {
  (): Promise<T>;
  /**
   * Expiry time of the credentials returned by the provider.
   */
  expireTime?: Date;
}

interface AwsCredentialIdentity {
  /**
   * AWS access key ID
   */
  readonly accessKeyId: string;
  
  /**
   * AWS secret access key
   */
  readonly secretAccessKey: string;
  
  /**
   * A security token that was issued by the AWS Security Token Service (STS).
   * This is only required when using temporary credentials.
   */
  readonly sessionToken?: string;
  
  /**
   * A Date when the identity or credential will no longer be accepted.
   */
  readonly expiration?: Date;
}

DefaultProviderInit Type Export

The configuration type for the default credential provider is also exported for use in custom implementations.

/**
 * Configuration options type for the default credential provider.
 * This is an intersection of multiple credential provider configuration interfaces.
 */
type DefaultProviderInit = FromIniInit &
  FromHttpOptions &
  RemoteProviderInit &
  FromProcessInit &
  (FromSSOInit & Partial<SsoCredentialsParameters>) &
  FromTokenFileInit;

Usage Examples:

import { defaultProvider, DefaultProviderInit } from "@aws-sdk/credential-provider-node";
import { getDefaultRoleAssumerWithWebIdentity } from "@aws-sdk/client-sts";

// Basic usage
const provider = defaultProvider();
const credentials = await provider();

// With profile configuration
const provider = defaultProvider({
  profile: "production",
  timeout: 10000
});

// For EKS IAM Roles for Service Accounts
const provider = defaultProvider({
  roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity({
    region: "us-east-1"
  })
});

// With custom role assumption
const provider = defaultProvider({
  roleAssumer: async (sourceCredentials, params) => {
    // Custom role assumption logic
    return assumeRoleWithCustomLogic(sourceCredentials, params);
  },
  mfaCodeProvider: async (serial) => {
    // Custom MFA token provider
    return await promptUserForMFA(serial);
  }
});

DefaultProviderInit Type

Configuration type for the default credential provider, combining options from multiple provider interfaces.

/**
 * Configuration options type for the default credential provider.
 * This is an intersection of multiple credential provider configuration interfaces.
 */
type DefaultProviderInit = FromIniInit &
  FromHttpOptions &
  RemoteProviderInit &
  FromProcessInit &
  (FromSSOInit & Partial<SsoCredentialsParameters>) &
  FromTokenFileInit;

Key Configuration Properties (from constituent interfaces):

  • profile?: string - Configuration profile name
  • filepath?: string - Path to shared credentials file
  • configFilepath?: string - Path to shared config file
  • roleAssumer?: (sourceCredentials: AwsCredentialIdentity, params: AssumeRoleParams) => Promise<AwsCredentialIdentity> - Function for assuming IAM roles
  • roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity> - Function for web identity role assumption
  • roleArn?: string - ARN of role to assume
  • webIdentityTokenFile?: string - Path to web identity token file
  • ssoStartUrl?: string - SSO start URL (optional)
  • ssoAccountId?: string - SSO account ID (optional)
  • ssoRegion?: string - SSO region (optional)
  • ssoRoleName?: string - SSO role name (optional)
  • ssoSession?: string - SSO session name (optional)
  • mfaCodeProvider?: (mfaSerial: string) => Promise<string> - MFA token provider function
  • timeout?: number - Connection timeout for remote requests
  • maxRetries?: number - Maximum retry attempts for HTTP connections
  • logger?: Logger - Logger instance for debugging
  • parentClientConfig?: { region?: string | Provider<string>; profile?: string; [key: string]: unknown } - Parent client configuration

Remote Provider Function (Internal)

Internal function that provides credentials from remote sources like EC2/ECS Instance Metadata Service or ECS Container Metadata.

/**
 * @internal
 * Creates a credential provider for remote sources (EC2/ECS metadata)
 */
function remoteProvider(init: RemoteProviderInit | FromHttpOptions): Promise<AwsCredentialIdentityProvider>;

interface AwsCredentialIdentityProvider {
  (): Promise<AwsCredentialIdentity>;
}

This function:

  • Checks for ECS Container Metadata environment variables (AWS_CONTAINER_CREDENTIALS_RELATIVE_URI, AWS_CONTAINER_CREDENTIALS_FULL_URI)
  • Falls back to EC2 Instance Metadata Service if ECS variables are not present
  • Respects the AWS_EC2_METADATA_DISABLED environment variable to disable IMDS access
  • Returns a provider function that can be called to retrieve credentials

Credential Refresh Utilities (Internal)

Internal utility functions for determining when credentials need to be refreshed.

/**
 * @internal
 * Returns true if credentials have an expiration date.
 */
function credentialsWillNeedRefresh(credentials: AwsCredentialIdentity): boolean;

/**
 * @internal
 * Returns true if credentials expire within 5 minutes (300000ms).
 */
function credentialsTreatedAsExpired(credentials: AwsCredentialIdentity): boolean;

These functions are used internally by the memoization logic to determine when cached credentials should be refreshed.

Environment Variable Constants (Internal)

Internal constants for environment variable names used by the remote provider.

/**
 * @internal
 * Environment variable name for disabling EC2 Instance Metadata Service
 */
const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED";

This constant is used internally to check if IMDS access should be disabled.

Types

interface MemoizedProvider<T> {
  (): Promise<T>;
  /**
   * Expiry time of the credentials returned by the provider.
   */
  expireTime?: Date;
}

interface AwsCredentialIdentity {
  /**
   * AWS access key ID
   */
  readonly accessKeyId: string;
  
  /**
   * AWS secret access key
   */
  readonly secretAccessKey: string;
  
  /**
   * A security token that was issued by the AWS Security Token Service (STS).
   * This is only required when using temporary credentials.
   */
  readonly sessionToken?: string;
  
  /**
   * A Date when the identity or credential will no longer be accepted.
   */
  readonly expiration?: Date;
}

interface Logger {
  debug(...content: any[]): void;
  info(...content: any[]): void;
  warn(...content: any[]): void;
  error(...content: any[]): void;
}

/**
 * Configuration options from @aws-sdk/credential-provider-ini
 */
interface FromIniInit {
  profile?: string;
  filepath?: string;
  configFilepath?: string;
  roleAssumer?: (sourceCredentials: AwsCredentialIdentity, params: AssumeRoleParams) => Promise<AwsCredentialIdentity>;
  roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity>;
  mfaCodeProvider?: (mfaSerial: string) => Promise<string>;
  parentClientConfig?: { region?: string | Provider<string>; profile?: string; [key: string]: unknown };
}

/**
 * Configuration options from @aws-sdk/credential-provider-http
 */
interface FromHttpOptions {
  authorizationToken?: string;
  credentialsFullUri?: string;
}

/**
 * Configuration options from @smithy/credential-provider-imds
 */
interface RemoteProviderInit {
  timeout?: number;
  maxRetries?: number;
  logger?: Logger;
}

/**
 * Configuration options from @aws-sdk/credential-provider-process
 */
interface FromProcessInit {
  profile?: string;
  filepath?: string;
  configFilepath?: string;
  logger?: Logger;
}

/**
 * Configuration options from @aws-sdk/credential-provider-sso
 */
interface FromSSOInit {
  ssoStartUrl?: string;
  ssoAccountId?: string;
  ssoRegion?: string;
  ssoRoleName?: string;
  ssoSession?: string;
  logger?: Logger;
}

/**
 * Additional SSO credential parameters
 */
interface SsoCredentialsParameters {
  clientName?: string;
  clientType?: string;
}

/**
 * Configuration options from @aws-sdk/credential-provider-web-identity
 */
interface FromTokenFileInit {
  webIdentityTokenFile?: string;
  roleArn?: string;
  roleSessionName?: string;
  roleAssumerWithWebIdentity?: (params: AssumeRoleWithWebIdentityParams) => Promise<AwsCredentialIdentity>;
  logger?: Logger;
}

interface AssumeRoleParams {
  roleArn: string;
  roleSessionName?: string;
  durationSeconds?: number;
  externalId?: string;
  policy?: string;
  policyArns?: Array<{ arn?: string }>;
  serialNumber?: string;
  tokenCode?: string;
}

interface AssumeRoleWithWebIdentityParams {
  roleArn: string;
  roleSessionName?: string;
  webIdentityToken: string;
  durationSeconds?: number;
  policy?: string;
  policyArns?: Array<{ arn?: string }>;
  providerId?: string;
}

type Provider<T> = T | (() => Promise<T>);

Error Handling

The credential provider chain throws CredentialsProviderError when:

  • No providers in the chain can supply valid credentials
  • Invalid configuration is encountered (e.g., non-existent source profile)
  • Required parameters are missing for specific providers

Common Error Scenarios:

import { defaultProvider } from "@aws-sdk/credential-provider-node";

try {
  const credentials = await defaultProvider()();
} catch (error) {
  if (error.name === "CredentialsProviderError") {
    console.error("Could not load credentials:", error.message);
    // Handle credential loading failure
  }
}
/**
 * Error thrown when credential providers fail to provide credentials
 */
class CredentialsProviderError extends Error {
  name: "CredentialsProviderError";
  message: string;
  tryNextLink?: boolean;
  logger?: Logger;
  
  constructor(message: string, options?: { tryNextLink?: boolean; logger?: Logger });
}

Warning Cases:

  • Multiple credential sources detected (both AWS_PROFILE and AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY)
  • IMDS access disabled via AWS_EC2_METADATA_DISABLED environment variable

Environment Variables

The provider respects several environment variables:

  • AWS_PROFILE - Configuration profile to use
  • AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY - Static credentials
  • AWS_SHARED_CREDENTIALS_FILE - Path to credentials file
  • AWS_CONFIG_FILE - Path to config file
  • AWS_ROLE_ARN - Role ARN for assumption
  • AWS_WEB_IDENTITY_TOKEN_FILE - Web identity token file path
  • AWS_EC2_METADATA_DISABLED - Disable IMDS access ("true" to disable)