or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

credentials.mdec2rolecreds.mdendpointcreds.mdindex.mdlogincreds.mdprocesscreds.mdssocreds.mdstscreds.md
tile.json

endpointcreds.mddocs/

HTTP Endpoint Credentials Provider

Package: github.com/aws/aws-sdk-go-v2/credentials/endpointcreds

The endpointcreds package provides credential retrieval from arbitrary HTTP endpoints, supporting both static and refreshable credentials.

Import

import "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"

Overview

This provider retrieves AWS credentials from an HTTP endpoint that returns credentials in JSON format. It supports:

  • Static credentials: Credentials without expiration
  • Refreshable credentials: Credentials with expiration that need periodic refresh
  • Authorization tokens: Optional authorization headers for secure endpoints

Credential Response Formats

Static Credentials Response

{
    "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
    "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
}

Refreshable Credentials Response

{
    "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
    "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
    "Token": "AQoDYXdzEJr...",
    "Expiration": "2016-02-25T06:03:31Z"
}

Error Response

Errors are returned with 400 or 500 HTTP status codes:

{
    "code": "ErrorCode",
    "message": "Helpful error message."
}

Usage Examples

Basic Usage

package main

import (
    "context"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func main() {
    // Create endpoint credentials provider
    provider := endpointcreds.New("http://localhost:8080/credentials")

    // Wrap with CredentialsCache for automatic refresh
    credentials := aws.NewCredentialsCache(provider)

    // Use with AWS service clients
    cfg := aws.Config{
        Region:      "us-east-1",
        Credentials: credentials,
    }

    client := s3.NewFromConfig(cfg)
    // Use client
}

With Authorization Token

provider := endpointcreds.New(
    "http://localhost:8080/credentials",
    func(o *endpointcreds.Options) {
        o.AuthorizationToken = "my-secret-token"
    },
)

credentials := aws.NewCredentialsCache(provider)

With Dynamic Token Provider

package main

import (
    "os"
    "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
)

func main() {
    // Read token from file each time credentials are retrieved
    tokenProvider := endpointcreds.TokenProviderFunc(func() (string, error) {
        token, err := os.ReadFile("/path/to/token/file")
        if err != nil {
            return "", err
        }
        return string(token), nil
    })

    provider := endpointcreds.New(
        "http://localhost:8080/credentials",
        func(o *endpointcreds.Options) {
            o.AuthorizationTokenProvider = tokenProvider
        },
    )

    // Use provider
}

Custom HTTP Client

import (
    "net/http"
    "time"
)

customClient := &http.Client{
    Timeout: 10 * time.Second,
}

provider := endpointcreds.New(
    "http://localhost:8080/credentials",
    func(o *endpointcreds.Options) {
        o.HTTPClient = customClient
    },
)

API Reference

Constants

const ProviderName = "CredentialsEndpointProvider"

Name identifier for the credentials endpoint provider.

New

func New(endpoint string, optFns ...func(*Options)) *Provider

Returns a credentials Provider for retrieving AWS credentials from an arbitrary endpoint.

Parameters:

  • endpoint (string): Required. The HTTP(S) endpoint URL to retrieve credentials from
  • optFns (...func(*Options)): Functional options for configuring the provider

Returns:

  • *Provider: Initialized endpoint credentials provider

Example:

// Basic endpoint
provider := endpointcreds.New("http://localhost:8080/credentials")

// With authorization
provider := endpointcreds.New(
    "http://localhost:8080/credentials",
    func(o *endpointcreds.Options) {
        o.AuthorizationToken = "secret-token"
    },
)

Options

type Options struct {
    Endpoint                   string
    HTTPClient                 HTTPClient
    APIOptions                 []func(*middleware.Stack) error
    Retryer                    aws.Retryer
    AuthorizationToken         string
    AuthorizationTokenProvider AuthTokenProvider
    CredentialSources          []aws.CredentialSource
}

Configuration options for the Provider.

Fields:

  • Endpoint (string): Required. Endpoint URL to retrieve credentials from
  • HTTPClient (HTTPClient): HTTP client for sending requests. Defaults to standard http.Client
  • APIOptions ([]func(*middleware.Stack) error): Options to modify credentials operation invocation
  • Retryer (aws.Retryer): Retryer for determining whether failed requests should be retried
  • AuthorizationToken (string): Optional static authorization token for the Authorization header. Can be set via AWS_CONTAINER_AUTHORIZATION_TOKEN environment variable
  • AuthorizationTokenProvider (AuthTokenProvider): Optional dynamic token provider. Overrides AuthorizationToken if set. Can be configured via AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE environment variable
  • CredentialSources ([]aws.CredentialSource): Credential chain information for reporting (not meant to be set directly)

Provider

type Provider struct {
    // Has unexported fields
}

Satisfies the aws.CredentialsProvider interface for retrieving credentials from an arbitrary endpoint.

Retrieve

func (p *Provider) Retrieve(ctx context.Context) (aws.Credentials, error)

Attempts to request credentials from the configured endpoint.

Parameters:

  • ctx (context.Context): Context for the request, supports cancellation and timeouts

Returns:

  • aws.Credentials: Retrieved credentials (static or with expiration)
  • error: Error if retrieval fails

Example:

creds, err := provider.Retrieve(context.TODO())
if err != nil {
    log.Fatalf("Failed to retrieve credentials: %v", err)
}

if creds.CanExpire {
    fmt.Printf("Credentials expire at: %s\n", creds.Expires)
}

ProviderSources

func (p *Provider) ProviderSources() []aws.CredentialSource

Returns the credential chain that was used to construct this provider.

Returns:

  • []aws.CredentialSource: Credential source chain for debugging

HTTPClient

type HTTPClient interface {
    Do(*http.Request) (*http.Response, error)
}

Interface for sending HTTP requests. Allows custom HTTP client implementations.

Methods:

  • Do(*http.Request) (*http.Response, error): Executes an HTTP request

AuthTokenProvider

type AuthTokenProvider interface {
    GetToken() (string, error)
}

Interface for dynamically loading authorization tokens. The token value is used as the Authorization header in credential requests.

Methods:

  • GetToken() (string, error): Retrieves the current authorization token

TokenProviderFunc

type TokenProviderFunc func() (string, error)

Function type implementing the AuthTokenProvider interface, enabling custom token provider behavior.

GetToken

func (p TokenProviderFunc) GetToken() (string, error)

Retrieves the authorization token by calling the underlying function.

Returns:

  • string: The authorization token
  • error: Error if token retrieval fails

Example:

tokenProvider := endpointcreds.TokenProviderFunc(func() (string, error) {
    // Read token from secure storage
    token, err := readTokenFromVault()
    if err != nil {
        return "", err
    }
    return token, nil
})

provider := endpointcreds.New(
    "http://localhost:8080/credentials",
    func(o *endpointcreds.Options) {
        o.AuthorizationTokenProvider = tokenProvider
    },
)

Environment Variable Configuration

The provider can be configured using environment variables:

  • AWS_CONTAINER_AUTHORIZATION_TOKEN: Static authorization token
  • AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE: Path to file containing authorization token (refreshed on each request)

When using AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE, the token file is read before each credential request, allowing token rotation without restarting the application.

Error Handling

The provider handles several error scenarios:

  • HTTP errors: Non-200 status codes from the endpoint
  • Malformed responses: JSON parsing errors or missing required fields
  • Network errors: Connection failures or timeouts
  • Authorization errors: Invalid or missing authorization tokens

Example:

creds, err := provider.Retrieve(ctx)
if err != nil {
    // Check for specific error types
    if strings.Contains(err.Error(), "401") {
        log.Fatal("Authorization failed - invalid token")
    }
    log.Fatalf("Failed to retrieve credentials: %v", err)
}

Integration with ECS Task Roles

This provider is commonly used with Amazon ECS tasks. ECS provides an endpoint for task role credentials:

import (
    "os"
    "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds"
)

func main() {
    // ECS provides credentials endpoint via environment variable
    endpoint := os.Getenv("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI")
    if endpoint != "" {
        endpoint = "http://169.254.170.2" + endpoint
    }

    provider := endpointcreds.New(endpoint)
    // Use provider
}

Best Practices

  1. Use CredentialsCache: Wrap the provider with aws.CredentialsCache to handle automatic refresh of expiring credentials

    provider := endpointcreds.New(endpoint)
    creds := aws.NewCredentialsCache(provider)
  2. Secure endpoints: Use HTTPS for credential endpoints in production to protect credentials in transit

  3. Token rotation: Use AuthorizationTokenProvider for dynamic token loading when tokens need rotation

  4. Timeouts: Set appropriate HTTP client timeouts to prevent hanging requests:

    customClient := &http.Client{Timeout: 5 * time.Second}
    provider := endpointcreds.New(endpoint, func(o *endpointcreds.Options) {
        o.HTTPClient = customClient
    })
  5. Error handling: Implement proper error handling for network failures and invalid responses

  6. Retry configuration: Configure appropriate retry behavior for transient failures:

    import "github.com/aws/aws-sdk-go-v2/aws/retry"
    
    provider := endpointcreds.New(endpoint, func(o *endpointcreds.Options) {
        o.Retryer = retry.NewStandard()
    })

Credential Expiration

  • Static credentials: When no Expiration field is present in the response, credentials never expire
  • Refreshable credentials: When Expiration is present, aws.CredentialsCache automatically refreshes credentials before they expire
  • Refresh timing: By default, credentials are refreshed 5 minutes before expiration