summaryrefslogtreecommitdiffstats
path: root/Godeps/_workspace/src/github.com/awslabs/aws-sdk-go/aws/credentials.go
blob: 4490c674a22985437d9e115dc0743a1c0f071c89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package aws

import (
	"bufio"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"os"
	"path/filepath"
	"sync"
	"time"

	"github.com/vaughan0/go-ini"
)

var currentTime = time.Now

// Credentials are used to authenticate and authorize calls that you make to
// AWS.
type Credentials struct {
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
}

// A CredentialsProvider is a provider of credentials.
type CredentialsProvider interface {
	// Credentials returns a set of credentials (or an error if no credentials
	// could be provided).
	Credentials() (*Credentials, error)
}

var (
	// ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be
	// found in the process's environment.
	ErrAccessKeyIDNotFound = fmt.Errorf("AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment")
	// ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key
	// can't be found in the process's environment.
	ErrSecretAccessKeyNotFound = fmt.Errorf("AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment")
)

type DefaultCredentialsProvider struct {
}

func (p *DefaultCredentialsProvider) Credentials() (*Credentials, error) {
	env, err := EnvCreds()
	if err == nil {
		return env.Credentials()
	}

	profile, err := ProfileCreds("", "", 10*time.Minute)
	if err == nil {
		profileCreds, err := profile.Credentials()
		if err == nil {
			return profileCreds, nil
		}
	}

	return IAMCreds().Credentials()
}

func DefaultCreds() CredentialsProvider {
	return &DefaultCredentialsProvider{}
}

// DetectCreds returns a CredentialsProvider based on the available information.
//
// If the access key ID and secret access key are provided, it returns a basic
// provider.
//
// If credentials are available via environment variables, it returns an
// environment provider.
//
// If a profile configuration file is available in the default location and has
// a default profile configured, it returns a profile provider.
//
// Otherwise, it returns an IAM instance provider.
func DetectCreds(accessKeyID, secretAccessKey, sessionToken string) CredentialsProvider {
	if accessKeyID != "" && secretAccessKey != "" {
		return Creds(accessKeyID, secretAccessKey, sessionToken)
	}

	env, err := EnvCreds()
	if err == nil {
		return env
	}

	profile, err := ProfileCreds("", "", 10*time.Minute)
	if err != nil {
		return IAMCreds()
	}

	_, err = profile.Credentials()
	if err != nil {
		return IAMCreds()
	}

	return profile
}

// EnvCreds returns a static provider of AWS credentials from the process's
// environment, or an error if none are found.
func EnvCreds() (CredentialsProvider, error) {
	id := os.Getenv("AWS_ACCESS_KEY_ID")
	if id == "" {
		id = os.Getenv("AWS_ACCESS_KEY")
	}

	secret := os.Getenv("AWS_SECRET_ACCESS_KEY")
	if secret == "" {
		secret = os.Getenv("AWS_SECRET_KEY")
	}

	if id == "" {
		return nil, ErrAccessKeyIDNotFound
	}

	if secret == "" {
		return nil, ErrSecretAccessKeyNotFound
	}

	return Creds(id, secret, os.Getenv("AWS_SESSION_TOKEN")), nil
}

// Creds returns a static provider of credentials.
func Creds(accessKeyID, secretAccessKey, sessionToken string) CredentialsProvider {
	return staticCredentialsProvider{
		creds: Credentials{
			AccessKeyID:     accessKeyID,
			SecretAccessKey: secretAccessKey,
			SessionToken:    sessionToken,
		},
	}
}

// IAMCreds returns a provider which pulls credentials from the local EC2
// instance's IAM roles.
func IAMCreds() CredentialsProvider {
	return &iamProvider{}
}

// ProfileCreds returns a provider which pulls credentials from the profile
// configuration file.
func ProfileCreds(filename, profile string, expiry time.Duration) (CredentialsProvider, error) {
	if filename == "" {
		homeDir := os.Getenv("HOME") // *nix
		if homeDir == "" {           // Windows
			homeDir = os.Getenv("USERPROFILE")
		}
		if homeDir == "" {
			return nil, errors.New("User home directory not found.")
		}

		filename = filepath.Join(homeDir, ".aws", "credentials")
	}

	if profile == "" {
		profile = "default"
	}

	return &profileProvider{
		filename: filename,
		profile:  profile,
		expiry:   expiry,
	}, nil
}

type profileProvider struct {
	filename string
	profile  string
	expiry   time.Duration

	creds      Credentials
	m          sync.Mutex
	expiration time.Time
}

func (p *profileProvider) Credentials() (*Credentials, error) {
	p.m.Lock()
	defer p.m.Unlock()

	if p.expiration.After(currentTime()) {
		return &p.creds, nil
	}

	config, err := ini.LoadFile(p.filename)
	if err != nil {
		return nil, err
	}
	profile := config.Section(p.profile)

	accessKeyID, ok := profile["aws_access_key_id"]
	if !ok {
		return nil, fmt.Errorf("profile %s in %s did not contain aws_access_key_id", p.profile, p.filename)
	}

	secretAccessKey, ok := profile["aws_secret_access_key"]
	if !ok {
		return nil, fmt.Errorf("profile %s in %s did not contain aws_secret_access_key", p.profile, p.filename)
	}

	sessionToken := profile["aws_session_token"]

	p.creds = Credentials{
		AccessKeyID:     accessKeyID,
		SecretAccessKey: secretAccessKey,
		SessionToken:    sessionToken,
	}
	p.expiration = currentTime().Add(p.expiry)

	return &p.creds, nil
}

type iamProvider struct {
	creds      Credentials
	m          sync.Mutex
	expiration time.Time
}

var metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"

// IAMClient is the HTTP client used to query the metadata endpoint for IAM
// credentials.
var IAMClient = http.Client{
	Timeout: 1 * time.Second,
}

func (p *iamProvider) Credentials() (*Credentials, error) {
	p.m.Lock()
	defer p.m.Unlock()

	if p.expiration.After(currentTime()) {
		return &p.creds, nil
	}

	var body struct {
		Expiration      time.Time
		AccessKeyID     string
		SecretAccessKey string
		Token           string
	}

	resp, err := IAMClient.Get(metadataCredentialsEndpoint)
	if err != nil {
		return nil, fmt.Errorf("listing IAM credentials")
	}
	defer func() {
		_ = resp.Body.Close()
	}()

	// Take the first line of the body of the metadata endpoint
	s := bufio.NewScanner(resp.Body)
	if !s.Scan() {
		return nil, fmt.Errorf("unable to find default IAM credentials")
	} else if s.Err() != nil {
		return nil, fmt.Errorf("%s listing IAM credentials", s.Err())
	}

	resp, err = IAMClient.Get(metadataCredentialsEndpoint + s.Text())
	if err != nil {
		return nil, fmt.Errorf("getting %s IAM credentials", s.Text())
	}
	defer func() {
		_ = resp.Body.Close()
	}()

	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
		return nil, fmt.Errorf("decoding %s IAM credentials", s.Text())
	}

	p.creds = Credentials{
		AccessKeyID:     body.AccessKeyID,
		SecretAccessKey: body.SecretAccessKey,
		SessionToken:    body.Token,
	}
	p.expiration = body.Expiration

	return &p.creds, nil
}

type staticCredentialsProvider struct {
	creds Credentials
}

func (p staticCredentialsProvider) Credentials() (*Credentials, error) {
	return &p.creds, nil
}