/
aliasing.go
91 lines (75 loc) · 2.27 KB
/
aliasing.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 gcpauth
import (
"fmt"
"sort"
"strconv"
"strings"
"google.golang.org/api/compute/v1"
"google.golang.org/api/iam/v1"
)
type iamAliaser func(role *gcpRole, svcAccount *iam.ServiceAccount) (alias string)
type gceAliaser func(role *gcpRole, instance *compute.Instance) (alias string)
const (
defaultIAMAlias = "unique_id"
defaultGCEAlias = "instance_id"
)
var (
allowedIAMAliases = map[string]iamAliaser{
defaultIAMAlias: getIAMSvcAccountUniqueID,
"": getIAMSvcAccountUniqueID, // For backwards compatibility
"role_id": getIAMRoleID,
}
allowedGCEAliases = map[string]gceAliaser{
defaultGCEAlias: getGCEInstanceID,
"": getGCEInstanceID, // For backwards compatibility
"role_id": getGCERoleID,
}
allowedIAMAliasesSlice = iamMapKeyToSlice(allowedIAMAliases)
allowedGCEAliasesSlice = gceMapKeyToSlice(allowedGCEAliases)
)
func iamMapKeyToSlice(m map[string]iamAliaser) (s []string) {
for key := range m {
if key == "" {
continue
}
s = append(s, key)
}
sort.Strings(s)
return s
}
func gceMapKeyToSlice(m map[string]gceAliaser) (s []string) {
for key := range m {
if key == "" {
continue
}
s = append(s, key)
}
sort.Strings(s)
return s
}
func getIAMSvcAccountUniqueID(_ *gcpRole, svcAccount *iam.ServiceAccount) (alias string) {
return svcAccount.UniqueId
}
func getIAMRoleID(role *gcpRole, _ *iam.ServiceAccount) (alias string) {
return role.RoleID
}
func getGCEInstanceID(_ *gcpRole, instance *compute.Instance) (alias string) {
return fmt.Sprintf("gce-%s", strconv.FormatUint(instance.Id, 10))
}
func getGCERoleID(role *gcpRole, _ *compute.Instance) (alias string) {
return role.RoleID
}
func getIAMAlias(role *gcpRole, svcAccount *iam.ServiceAccount) (alias string, err error) {
aliaser, exists := allowedIAMAliases[role.IAMAliasType]
if !exists {
return "", fmt.Errorf("invalid IAM alias type: must be one of: %s", strings.Join(allowedIAMAliasesSlice, ", "))
}
return aliaser(role, svcAccount), nil
}
func getGCEAlias(role *gcpRole, instance *compute.Instance) (alias string, err error) {
aliaser, exists := allowedGCEAliases[role.GCEAliasType]
if !exists {
return "", fmt.Errorf("invalid GCE alias type: must be one of: %s", strings.Join(allowedIAMAliasesSlice, ", "))
}
return aliaser(role, instance), nil
}