1package gcputil
2
3import (
4	"fmt"
5	"google.golang.org/api/iam/v1"
6)
7
8const (
9	ServiceAccountTemplate    = "projects/%s/serviceAccounts/%s"
10	ServiceAccountKeyTemplate = "projects/%s/serviceAccounts/%s/keys/%s"
11	ServiceAccountKeyFileType = "TYPE_X509_PEM_FILE"
12)
13
14type ServiceAccountId struct {
15	Project   string
16	EmailOrId string
17}
18
19func (id *ServiceAccountId) ResourceName() string {
20	return fmt.Sprintf(ServiceAccountTemplate, id.Project, id.EmailOrId)
21}
22
23type ServiceAccountKeyId struct {
24	Project   string
25	EmailOrId string
26	Key       string
27}
28
29func (id *ServiceAccountKeyId) ResourceName() string {
30	return fmt.Sprintf(ServiceAccountKeyTemplate, id.Project, id.EmailOrId, id.Key)
31}
32
33// ServiceAccount wraps a call to the GCP IAM API to get a service account.
34func ServiceAccount(iamClient *iam.Service, accountId *ServiceAccountId) (*iam.ServiceAccount, error) {
35	account, err := iamClient.Projects.ServiceAccounts.Get(accountId.ResourceName()).Do()
36	if err != nil {
37		return nil, fmt.Errorf("could not find service account '%s': %v", accountId.ResourceName(), err)
38	}
39
40	return account, nil
41}
42
43// ServiceAccountKey wraps a call to the GCP IAM API to get a service account key.
44func ServiceAccountKey(iamClient *iam.Service, keyId *ServiceAccountKeyId) (*iam.ServiceAccountKey, error) {
45	keyResource := keyId.ResourceName()
46	key, err := iamClient.Projects.ServiceAccounts.Keys.Get(keyId.ResourceName()).PublicKeyType(ServiceAccountKeyFileType).Do()
47	if err != nil {
48		return nil, fmt.Errorf("could not find service account key '%s': %v", keyResource, err)
49	}
50	return key, nil
51}
52