CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-aws-sdk--credential-providers

A collection of credential providers for AWS SDK, enabling authentication across different AWS environments and services

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

temporary-credentials.mddocs/

Temporary Credentials via STS

Temporary credential provider creates credentials using AWS STS AssumeRole API, supporting role chaining, MFA requirements, and custom session policies for fine-grained access control.

Capabilities

Temporary Credentials Provider

Creates temporary credentials using STS AssumeRole operation.

/**
 * Creates a credential provider function that retrieves temporary credentials from STS AssumeRole API
 * @param options - Configuration options for temporary credentials
 * @returns Runtime-configurable credential provider function
 */
function fromTemporaryCredentials(options: FromTemporaryCredentialsOptions): RuntimeConfigAwsCredentialIdentityProvider;

interface FromTemporaryCredentialsOptions {
  /** Parameters passed to STS AssumeRole operation */
  params: Omit<AssumeRoleCommandInput, "RoleSessionName"> & { RoleSessionName?: string };
  /** Optional master credentials used to get and refresh temporary credentials */
  masterCredentials?: AwsCredentialIdentity | AwsCredentialIdentityProvider;
  /** Optional custom STS client configurations */
  clientConfig?: STSClientConfig;
  /** Optional logger instance */
  logger?: Logger;
  /** Optional custom STS client middleware plugins */
  clientPlugins?: Pluggable<any, any>[];
  /** Optional function that returns MFA token code for the provided MFA Serial code */
  mfaCodeProvider?: (mfaSerial: string) => Promise<string>;
}

interface AssumeRoleCommandInput {
  /** ARN of the role to assume (required) */
  RoleArn: string;
  /** An identifier for the assumed role session (optional, auto-generated if not provided) */
  RoleSessionName?: string;
  /** The duration, in seconds, of the role session (optional, default varies by role) */
  DurationSeconds?: number;
  /** An IAM policy in JSON format for inline session policy (optional) */
  Policy?: string;
  /** ARNs of IAM managed policies for managed session policies (optional) */
  PolicyArns?: PolicyDescriptorType[];
  /** MFA device serial number (required if role requires MFA) */
  SerialNumber?: string;
  /** MFA token code (required if SerialNumber is specified) */
  TokenCode?: string;
  /** External ID used to authenticate cross-account role assumption (optional) */
  ExternalId?: string;
  /** Source identity specified when assuming role (optional) */
  SourceIdentity?: string;
  /** List of session tags (optional) */
  Tags?: Tag[];
  /** List of keys for session tags to mark as transitive (optional) */
  TransitiveTagKeys?: string[];
}

Usage Examples:

import { S3Client } from "@aws-sdk/client-s3";
import { fromTemporaryCredentials, fromIni } from "@aws-sdk/credential-providers";

// Basic role assumption
const client = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MyAssumedRole"
    }
  })
});

// Role assumption with custom session
const customClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MyAssumedRole",
      RoleSessionName: "MyCustomSession",
      DurationSeconds: 3600 // 1 hour
    }
  })
});

// Role chaining with explicit master credentials
const chainedClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    masterCredentials: fromIni({ profile: "base-profile" }),
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/ChainedRole",
      RoleSessionName: "ChainedSession"
    }
  })
});

Role Assumption with MFA

For roles that require multi-factor authentication:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const mfaClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MFARequiredRole",
      SerialNumber: "arn:aws:iam::123456789012:mfa/user@example.com"
    },
    mfaCodeProvider: async (mfaSerial) => {
      console.log(`Enter MFA token for device: ${mfaSerial}`);
      return await promptUserForMFAToken();
    }
  })
});

async function promptUserForMFAToken(): Promise<string> {
  // Implementation depends on your environment
  // Could use readline for CLI, a modal for web, etc.
  return "123456"; // Example 6-digit MFA token
}

Cross-Account Role Assumption

Assuming roles in different AWS accounts:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const crossAccountClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::987654321098:role/CrossAccountRole",
      ExternalId: "unique-external-id-12345", // Required for cross-account trust
      RoleSessionName: "CrossAccountSession"
    }
  })
});

Session Policies

Apply additional policies to limit permissions during the session:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

// Inline session policy
const restrictedClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/BroadRole",
      Policy: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Action: ["s3:GetObject"],
            Resource: "arn:aws:s3:::my-specific-bucket/*"
          }
        ]
      }),
      RoleSessionName: "RestrictedSession"
    }
  })
});

// Managed session policies
const managedPolicyClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/FlexibleRole",
      PolicyArns: [
        { arn: "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess" }
      ],
      RoleSessionName: "ManagedPolicySession"
    }
  })
});

Session Tags

Add session tags for auditing and conditional access:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const taggedClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/TaggedRole",
      Tags: [
        { Key: "Department", Value: "Engineering" },
        { Key: "Project", Value: "WebApp" },
        { Key: "Environment", Value: "Production" }
      ],
      TransitiveTagKeys: ["Department", "Project"], // These tags can be passed to subsequent roles
      RoleSessionName: "TaggedSession"
    }
  })
});

Role Chaining

Chain multiple role assumptions together:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

// First level: Assume intermediate role
const intermediateCredentials = fromTemporaryCredentials({
  params: {
    RoleArn: "arn:aws:iam::123456789012:role/IntermediateRole"
  }
});

// Second level: Use intermediate role to assume final role
const finalClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    masterCredentials: intermediateCredentials,
    params: {
      RoleArn: "arn:aws:iam::987654321098:role/FinalRole",
      RoleSessionName: "ChainedFinalRole"
    }
  })
});

Custom STS Client Configuration

Configure the underlying STS client:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

const customStsClient = new S3Client({
  region: "us-east-1",
  credentials: fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MyRole"
    },
    clientConfig: {
      region: "us-west-2", // Use different region for STS calls
      maxAttempts: 5,
      requestTimeout: 30000
    }
  })
});

Error Handling

Common errors and handling strategies:

import { fromTemporaryCredentials } from "@aws-sdk/credential-providers";

try {
  const credentials = await fromTemporaryCredentials({
    params: {
      RoleArn: "arn:aws:iam::123456789012:role/MyRole"
    }
  })();
} catch (error) {
  if (error.name === "AccessDenied") {
    console.error("Not authorized to assume this role");
  } else if (error.name === "InvalidUserType") {
    console.error("Current credentials cannot assume roles");
  } else if (error.name === "TokenRefreshRequired") {
    console.error("MFA token expired or invalid");
  } else if (error.name === "ValidationException") {
    console.error("Invalid role ARN format or parameters");
  } else {
    console.error("Failed to assume role:", error.message);
  }
}

Session Duration Limits

Default and maximum session durations vary by configuration:

  • Default duration: 1 hour (3600 seconds)
  • Maximum for role chaining: 1 hour
  • Maximum for direct assumption: Up to role's MaxSessionDuration setting (max 12 hours)
  • MFA-protected roles: Can have longer sessions if configured

Availability

  • Node.js: ✅ Available
  • Browser: ✅ Available (base version)
  • React Native: ✅ Available (base version)

docs

cognito-credentials.md

configuration-file-credentials.md

custom-credential-chains.md

default-provider-chain.md

environment-credentials.md

http-credentials.md

index.md

metadata-service-credentials.md

process-credentials.md

sso-credentials.md

temporary-credentials.md

web-identity-credentials.md

tile.json