Skip to content

Aton-Kish/aws-credscache-go

Repository files navigation

AWS Credentials Cache for Go

Go Reference Go Report Card MIT License

This module provides credentials caching utilities that are compatible with the AWS CLI.

Motivation

The AWS SDK has an in-memory caching feature for credentials. However, it doesn't work effectively for short-lifespan processes like CLI.

nocache
An MFA token code will be requested every time. It's very bothering.

Although the AWS CLI saves credentials into $HOME/.aws/cli/cache, the AWS SDK does not support it. This module provides an easy way to apply a file-caching feature that has compatibility with the AWS CLI.

cache
cache shared with AWS CLI
You will input an MFA token code only once and can also share the cache with the AWS CLI.

See exmples for more details.

Installation

go get github.com/Aton-Kish/aws-credscache-go

Usage

package main

import (
	"context"
	"log"

	credscache "github.com/Aton-Kish/aws-credscache-go/sdkv2"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials/stscreds"
)

func main() {
	cfg, err := config.LoadDefaultConfig(context.Background(), config.WithAssumeRoleCredentialOptions(func(options *stscreds.AssumeRoleOptions) {
		options.TokenProvider = stscreds.StdinTokenProvider
	}))
	if err != nil {
		log.Fatal(err)
	}

	// Inject file cache provider
	if _, err := credscache.InjectFileCacheProvider(&cfg); err != nil {
		log.Fatal(err)
	}

	// client := ec2.NewFromConfig(cfg)
}

See exmples for more details.

Compatibility with the AWS CLI

Assume Role

The AWS CLI stores the temporary credentials in $HOME/.aws/cli/cache. A cache file name is computed by the SHA-1 hash of the JSON-stringified options of the Assume Role API. This module partially supports cache key generators compatible with the AWS CLI.

Assume Role options key in $HOME/.aws/config compatible
RoleArn role_arn
RoleSessionName role_session_name
ExternalID external_id
SerialNumber mfa_serial
Duration duration_seconds ✕ (less than 960 seconds)
✓ (else)
Policy N/A

Development

Setup

go mod tidy

Generate code

rm -rf internal/mock
go generate ./...

Test

: simple
go test ./...
: verbose
go test -v ./...

Docs

go run golang.org/x/tools/cmd/godoc@latest -http ":6060"

License

This library is licensed under the MIT License, see LICENSE.