/
bootstrap.go
104 lines (84 loc) · 1.97 KB
/
bootstrap.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
92
93
94
95
96
97
98
99
100
101
102
103
104
package aws
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/manifoldco/torus-cli/gatekeeper/apitypes"
"github.com/manifoldco/torus-cli/gatekeeper/client"
)
const (
// MetadataURL is the metadata URL for AWS
MetadataURL = "http://169.254.169.254/latest/"
)
// Bootstrap bootstraps a the AWS instance into a role to a given Gatekeeper instance
func Bootstrap(url, name, org, role, caFile string) (*apitypes.BootstrapResponse, error) {
var err error
client, err := client.NewClient(url, caFile)
if err != nil {
return nil, fmt.Errorf("cannot initialize bootstrap client: %s", err)
}
identity, err := metadata()
if err != nil {
return nil, err
}
sig, err := signature()
if err != nil {
return nil, err
}
v := Verifier{
Identity: identity,
Signature: sig,
}
if err := v.Verify(); err != nil {
return nil, err
}
var identityDoc identityDocument
json.Unmarshal(identity, &identityDoc)
if name == "" {
name = identityDoc.InstanceID
}
bootreq := apitypes.AWSBootstrapRequest{
Identity: identity,
Signature: sig,
ProvisionTime: identityDoc.PendingTime,
Machine: apitypes.MachineBootstrap{
Name: name,
Org: org,
Team: role,
},
}
return client.Bootstrap("aws", bootreq)
}
func metadata() ([]byte, error) {
identity, err := fetchMetadata("dynamic/instance-identity/document")
if err != nil {
return nil, err
}
return identity, nil
}
func signature() ([]byte, error) {
signature, err := fetchMetadata("dynamic/instance-identity/pkcs7")
if err != nil {
return nil, err
}
return signature, nil
}
func fetchMetadata(endpoint string) ([]byte, error) {
url := fmt.Sprintf("%s%s", MetadataURL, endpoint)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return b, nil
}
type identityDocument struct {
InstanceID string `json:"instanceId"`
PendingTime time.Time `json:"pendingTime"`
}