summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/goamz/goamz/sts/sts.go
blob: 9739692233c542f25c0db5775778d7e81a535981 (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
//
// sts: This package provides types and functions to interact with the AWS STS API
//
// Depends on https://github.com/goamz/goamz
//

package sts

import (
	"encoding/xml"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strconv"
	"strings"
	"time"

	"github.com/goamz/goamz/aws"
)

// The STS type encapsulates operations within a specific EC2 region.
type STS struct {
	aws.Auth
	aws.Region
	private byte // Reserve the right of using private data.
}

// New creates a new STS Client.
// We can only use us-east for region because AWS..
func New(auth aws.Auth, region aws.Region) *STS {
	// Make sure we can run the package tests
	if region.Name == "" {
		return &STS{auth, region, 0}
	}
	return &STS{auth, aws.Regions["us-east-1"], 0}
}

const debug = false

// ----------------------------------------------------------------------------
// Request dispatching logic.

// Error encapsulates an error returned by the AWS STS API.
//
// See http://goo.gl/zDZbuQ  for more details.
type Error struct {
	// HTTP status code (200, 403, ...)
	StatusCode int
	// STS error code
	Code string
	// The human-oriented error message
	Message   string
	RequestId string `xml:"RequestID"`
}

func (err *Error) Error() string {
	if err.Code == "" {
		return err.Message
	}

	return fmt.Sprintf("%s (%s)", err.Message, err.Code)
}

type xmlErrors struct {
	RequestId string  `xml:"RequestId"`
	Errors    []Error `xml:"Error"`
}

func (sts *STS) query(params map[string]string, resp interface{}) error {
	params["Version"] = "2011-06-15"

	data := strings.NewReader(multimap(params).Encode())

	hreq, err := http.NewRequest("POST", sts.Region.STSEndpoint+"/", data)
	if err != nil {
		return err
	}

	hreq.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")

	token := sts.Auth.Token()
	if token != "" {
		hreq.Header.Set("X-Amz-Security-Token", token)
	}

	signer := aws.NewV4Signer(sts.Auth, "sts", sts.Region)
	signer.Sign(hreq)

	if debug {
		log.Printf("%v -> {\n", hreq)
	}
	r, err := http.DefaultClient.Do(hreq)

	if err != nil {
		log.Printf("Error calling Amazon")
		return err
	}

	defer r.Body.Close()

	if debug {
		dump, _ := httputil.DumpResponse(r, true)
		log.Printf("response:\n")
		log.Printf("%v\n}\n", string(dump))
	}
	if r.StatusCode != 200 {
		return buildError(r)
	}
	err = xml.NewDecoder(r.Body).Decode(resp)
	return err
}

func buildError(r *http.Response) error {
	var (
		err    Error
		errors xmlErrors
	)
	xml.NewDecoder(r.Body).Decode(&errors)
	if len(errors.Errors) > 0 {
		err = errors.Errors[0]
	}

	err.RequestId = errors.RequestId
	err.StatusCode = r.StatusCode
	if err.Message == "" {
		err.Message = r.Status
	}
	return &err
}

func makeParams(action string) map[string]string {
	params := make(map[string]string)
	params["Action"] = action
	return params
}

func multimap(p map[string]string) url.Values {
	q := make(url.Values, len(p))
	for k, v := range p {
		q[k] = []string{v}
	}
	return q
}

// options for the AssumeRole function
//
// See http://goo.gl/Ld6Dbk for details
type AssumeRoleParams struct {
	DurationSeconds int
	ExternalId      string
	Policy          string
	RoleArn         string
	RoleSessionName string
}

type AssumedRoleUser struct {
	Arn           string `xml:"Arn"`
	AssumedRoleId string `xml:"AssumedRoleId"`
}

type Credentials struct {
	AccessKeyId     string    `xml:"AccessKeyId"`
	Expiration      time.Time `xml:"Expiration"`
	SecretAccessKey string    `xml:"SecretAccessKey"`
	SessionToken    string    `xml:"SessionToken"`
}

type AssumeRoleResult struct {
	AssumedRoleUser  AssumedRoleUser `xml:"AssumeRoleResult>AssumedRoleUser"`
	Credentials      Credentials     `xml:"AssumeRoleResult>Credentials"`
	PackedPolicySize int             `xml:"AssumeRoleResult>PackedPolicySize"`
	RequestId        string          `xml:"ResponseMetadata>RequestId"`
}

// AssumeRole assumes the specified role
//
// See http://goo.gl/zDZbuQ for more details.
func (sts *STS) AssumeRole(options *AssumeRoleParams) (resp *AssumeRoleResult, err error) {
	params := makeParams("AssumeRole")

	params["RoleArn"] = options.RoleArn
	params["RoleSessionName"] = options.RoleSessionName

	if options.DurationSeconds != 0 {
		params["DurationSeconds"] = strconv.Itoa(options.DurationSeconds)
	}
	if options.ExternalId != "" {
		params["ExternalId"] = options.ExternalId
	}
	if options.Policy != "" {
		params["Policy"] = options.Policy
	}

	resp = new(AssumeRoleResult)
	if err := sts.query(params, resp); err != nil {
		return nil, err
	}
	return resp, nil
}

// FederatedUser presents dentifiers for the federated user that is associated with the credentials.
//
// See http://goo.gl/uPtr7V for more details
type FederatedUser struct {
	Arn             string `xml:"Arn"`
	FederatedUserId string `xml:"FederatedUserId"`
}

// GetFederationToken wraps GetFederationToken response
//
// See http://goo.gl/Iujjeg for more details
type GetFederationTokenResult struct {
	Credentials      Credentials   `xml:"GetFederationTokenResult>Credentials"`
	FederatedUser    FederatedUser `xml:"GetFederationTokenResult>FederatedUser"`
	PackedPolicySize int           `xml:"GetFederationTokenResult>PackedPolicySize"`
	RequestId        string        `xml:"ResponseMetadata>RequestId"`
}

// GetFederationToken returns a set of temporary credentials for an AWS account or IAM user
//
// See http://goo.gl/Iujjeg for more details
func (sts *STS) GetFederationToken(name, policy string, durationSeconds int) (
	resp *GetFederationTokenResult, err error) {
	params := makeParams("GetFederationToken")
	params["Name"] = name

	if durationSeconds != 0 {
		params["DurationSeconds"] = strconv.Itoa(durationSeconds)
	}
	if policy != "" {
		params["Policy"] = policy
	}

	resp = new(GetFederationTokenResult)
	if err := sts.query(params, resp); err != nil {
		return nil, err
	}
	return resp, nil
}

// GetSessionToken wraps GetSessionToken response
//
// See http://goo.gl/v8s5Y for more details
type GetSessionTokenResult struct {
	Credentials Credentials `xml:"GetSessionTokenResult>Credentials"`
	RequestId   string      `xml:"ResponseMetadata>RequestId"`
}

// GetSessionToken returns a set of temporary credentials for an AWS account or IAM user
//
// See http://goo.gl/v8s5Y for more details
func (sts *STS) GetSessionToken(durationSeconds int, serialnNumber, tokenCode string) (
	resp *GetSessionTokenResult, err error) {
	params := makeParams("GetSessionToken")

	if durationSeconds != 0 {
		params["DurationSeconds"] = strconv.Itoa(durationSeconds)
	}
	if serialnNumber != "" {
		params["SerialNumber"] = serialnNumber
	}
	if tokenCode != "" {
		params["TokenCode"] = tokenCode
	}

	resp = new(GetSessionTokenResult)
	if err := sts.query(params, resp); err != nil {
		return nil, err
	}
	return resp, nil
}