/
gcp.go
76 lines (70 loc) · 2.06 KB
/
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
package preflightid
import (
"context"
"errors"
"fmt"
"strings"
"cloud.google.com/go/compute/metadata"
log "github.com/sirupsen/logrus"
"google.golang.org/api/iam/v1"
"google.golang.org/api/option"
)
type IDProviderGCP struct {
Email string `json:"email" yaml:"email"`
}
func (p *IDProviderGCP) Equivalent() {
l := Logger
l.Debug("printing equivalent command")
cmd := `ID=$(gcloud auth list --filter=status:ACTIVE --format="value(account)");`
cmd += fmt.Sprintf(`if [ "$ID" != "%s" ]; then echo "ID $ID does not match expected %s"; exit 1; fi`, p.Email, p.Email)
cmd = fmt.Sprintf("sh -c '%s'", cmd)
fmt.Println(cmd)
}
func (p *IDProviderGCP) Run() error {
l := Logger.WithFields(log.Fields{
"preflight": "id",
"provider": "gcp",
})
l.Debug("running preflight-id")
if p.Email == "" {
return errors.New("email not configured")
}
// Initialize a GCP client with the appropriate credentials
ctx := context.Background()
client, err := iam.NewService(ctx, option.WithScopes(iam.CloudPlatformScope))
if err != nil {
l.WithError(err).Error("Failed to initialize GCP client")
return err
}
// Get the list of authorized accounts using the service client.
response, err := client.Projects.ServiceAccounts.List("projects/-").Do()
if err != nil {
l.WithError(err).Error("Failed to retrieve authorized accounts")
return err
}
var accountList []string
for _, account := range response.Accounts {
accountList = append(accountList, account.Email)
if strings.EqualFold(account.Email, p.Email) {
l.Debugf("Service Account match: %s", account.Email)
l.Info("passed")
return nil
}
}
if metadata.OnGCE() {
vmIdentity, err := metadata.Email("default")
if err != nil {
l.WithError(err).Error("Failed to retrieve VM Identity")
return err
}
accountList = append(accountList, vmIdentity)
if strings.EqualFold(vmIdentity, p.Email) {
l.Debugf("VM Identity match: %s", vmIdentity)
l.Info("passed")
return nil
}
}
failStr := fmt.Sprintf("failed - expected %s, got %v", p.Email, accountList)
l.Error(failStr)
return errors.New(failStr)
}