-
Notifications
You must be signed in to change notification settings - Fork 38
/
sts_creds.go
91 lines (76 loc) · 2.01 KB
/
sts_creds.go
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
package external
import (
"encoding/json"
"strings"
"time"
"github.com/pkg/errors"
"github.com/ucloud/ucloud-sdk-go/private/protocol/http"
"github.com/ucloud/ucloud-sdk-go/ucloud/metadata"
)
const internalBaseUrl = "http://api.service.ucloud.cn"
type AssumeRoleRequest struct {
RoleName string
}
func LoadSTSConfig(req AssumeRoleRequest) (ConfigProvider, error) {
httpClient := http.NewHttpClient()
client := &metadata.DefaultClient{}
err := client.SetHttpClient(&httpClient)
if err != nil {
return nil, err
}
return loadSTSConfig(req, client)
}
type metadataProvider interface {
SendRequest(string) (string, error)
SetHttpClient(http.Client) error
}
type assumeRoleData struct {
Expiration int
PrivateKey string
ProjectID string
PublicKey string
CharacterName string
SecurityToken string
UHostID string
UPHostId string
}
type assumeRoleResponse struct {
RetCode int
Message string
Data assumeRoleData
}
func loadSTSConfig(req AssumeRoleRequest, client metadataProvider) (ConfigProvider, error) {
path := "/meta-data/v1/uam/security-credentials"
if len(req.RoleName) != 0 {
path += "/" + req.RoleName
}
resp, err := client.SendRequest(path)
if err != nil {
return nil, err
}
var roleResp assumeRoleResponse
if err := json.NewDecoder(strings.NewReader(resp)).Decode(&roleResp); err != nil {
return nil, errors.Errorf("failed to decode sts credential, %s", err)
}
region, err := client.SendRequest("/meta-data/latest/region")
if err != nil {
return nil, err
}
zone, err := client.SendRequest("/meta-data/latest/availability-zone")
if err != nil {
return nil, err
}
roleData := roleResp.Data
stsConfig := &config{
CanExpire: true,
Expires: time.Unix(int64(roleData.Expiration), 0),
PrivateKey: roleData.PrivateKey,
PublicKey: roleData.PublicKey,
SecurityToken: roleData.SecurityToken,
ProjectId: roleData.ProjectID,
Region: region,
Zone: zone,
BaseUrl: internalBaseUrl,
}
return stsConfig, nil
}