forked from hashicorp/vault-plugin-auth-gcp
/
authorizer_client_gcp.go
88 lines (75 loc) · 2.27 KB
/
authorizer_client_gcp.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 gcpauth
import (
"context"
"fmt"
"strings"
log "github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/sdk/helper/strutil"
"google.golang.org/api/compute/v1"
"google.golang.org/api/iam/v1"
)
var _ client = (*gcpClient)(nil)
// gcpClient implements client and communicates with the GCP API. It is
// abstracted as an interface for stubbing during testing. See stubbedClient for
// more details.
type gcpClient struct {
logger log.Logger
computeSvc *compute.Service
iamSvc *iam.Service
}
func (c *gcpClient) InstanceGroups(ctx context.Context, project string, boundInstanceGroups []string) (map[string][]string, error) {
// map of zone names to a slice of instance group names in that zone.
igz := make(map[string][]string)
if err := c.computeSvc.InstanceGroups.
AggregatedList(project).
Fields("items/*/instanceGroups/name").
Pages(ctx, func(l *compute.InstanceGroupAggregatedList) error {
for k, v := range l.Items {
// Some groups returned are regional
// TODO(emilymye, #73): Support regions?
if strings.Contains(k, "/regions/") {
c.logger.Debug("ignoring instance groups under region in instance group aggregated list", "key", k)
continue
}
zone, err := zoneFromSelfLink(k)
if err != nil {
return err
}
for _, g := range v.InstanceGroups {
if strutil.StrListContains(boundInstanceGroups, g.Name) {
igz[zone] = append(igz[zone], g.Name)
}
}
}
return nil
}); err != nil {
return nil, err
}
return igz, nil
}
func (c *gcpClient) InstanceGroupContainsInstance(ctx context.Context, project, zone, group, instanceSelfLink string) (bool, error) {
var req compute.InstanceGroupsListInstancesRequest
resp, err := c.computeSvc.InstanceGroups.
ListInstances(project, zone, group, &req).
Filter(fmt.Sprintf("instance eq %s", instanceSelfLink)).
Context(ctx).
Do()
if err != nil {
return false, err
}
if resp != nil && len(resp.Items) > 0 {
return true, nil
}
return false, nil
}
func (c *gcpClient) ServiceAccount(ctx context.Context, name string) (string, string, error) {
account, err := c.iamSvc.Projects.ServiceAccounts.
Get(name).
Fields("uniqueId", "email").
Context(ctx).
Do()
if err != nil {
return "", "", err
}
return account.UniqueId, account.Email, nil
}