forked from Versent/saml2aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aws_account.go
88 lines (69 loc) · 2.19 KB
/
aws_account.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
package saml2aws
import (
"bytes"
"io/ioutil"
"net/http"
"net/url"
"fmt"
"github.com/PuerkitoBio/goquery"
"github.com/pkg/errors"
)
const awsURL = "https://signin.aws.amazon.com/saml"
// AWSAccount holds the AWS account name and roles
type AWSAccount struct {
Name string
Roles []*AWSRole
}
// ParseAWSAccounts extract the aws accounts from the saml assertion
func ParseAWSAccounts(samlAssertion string) ([]*AWSAccount, error) {
res, err := http.PostForm(awsURL, url.Values{"SAMLResponse": {samlAssertion}})
if err != nil {
return nil, errors.Wrap(err, "error retrieving AWS login form")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "error retrieving AWS login body")
}
return ExtractAWSAccounts(data)
}
// ExtractAWSAccounts extract the accounts from the AWS html page
func ExtractAWSAccounts(data []byte) ([]*AWSAccount, error) {
accounts := []*AWSAccount{}
doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(data))
if err != nil {
return nil, errors.Wrap(err, "failed to build document from response")
}
doc.Find("fieldset > div.saml-account").Each(func(i int, s *goquery.Selection) {
account := new(AWSAccount)
account.Name = s.Find("div.saml-account-name").Text()
s.Find("label").Each(func(i int, s *goquery.Selection) {
role := new(AWSRole)
role.Name = s.Text()
role.RoleARN, _ = s.Attr("for")
account.Roles = append(account.Roles, role)
})
accounts = append(accounts, account)
})
return accounts, nil
}
// AssignPrincipals assign principal from roles
func AssignPrincipals(awsRoles []*AWSRole, awsAccounts []*AWSAccount) {
awsPrincipalARNs := make(map[string]string)
for _, awsRole := range awsRoles {
awsPrincipalARNs[awsRole.RoleARN] = awsRole.PrincipalARN
}
for _, awsAccount := range awsAccounts {
for _, awsRole := range awsAccount.Roles {
awsRole.PrincipalARN = awsPrincipalARNs[awsRole.RoleARN]
}
}
}
// LocateRole locate role by name
func LocateRole(awsRoles []*AWSRole, roleName string) (*AWSRole, error) {
for _, awsRole := range awsRoles {
if awsRole.RoleARN == roleName {
return awsRole, nil
}
}
return nil, fmt.Errorf("Supplied RoleArn not found in saml assertion: %s", roleName)
}