-
Notifications
You must be signed in to change notification settings - Fork 108
/
credentials.go
75 lines (63 loc) · 1.88 KB
/
credentials.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
package gcputil
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"gocloud.dev/gcp"
"golang.org/x/oauth2/google"
)
var ErrNoCredentials = errors.New("empty credentials: set `google_application_credentials` env variable")
func Credentials(ctx context.Context, jsonData string, allowHostAccess bool) (*google.Credentials, error) {
if jsonData != "" {
// google_application_credentials is set, use credentials from json string provided by user
return google.CredentialsFromJSON(ctx, []byte(jsonData), "https://www.googleapis.com/auth/cloud-platform")
}
// google_application_credentials is not set
if allowHostAccess {
// use host credentials
creds, err := gcp.DefaultCredentials(ctx)
if err != nil {
if strings.Contains(err.Error(), "google: could not find default credentials") {
return nil, ErrNoCredentials
}
return nil, err
}
return creds, nil
}
return nil, ErrNoCredentials
}
func ProjectID(credentials *google.Credentials) (string, error) {
projectID := credentials.ProjectID
if projectID == "" {
if len(credentials.JSON) == 0 {
return "", fmt.Errorf("unable to get project ID")
}
f := &credentialsFile{}
if err := json.Unmarshal(credentials.JSON, f); err != nil {
return "", err
}
projectID = f.getProjectID()
}
return projectID, nil
}
// credentialsFile is the unmarshalled representation of a credentials file.
type credentialsFile struct {
Type string `json:"type"`
// Service Account fields
ProjectID string `json:"project_id"`
// External Account fields
QuotaProjectID string `json:"quota_project_id"`
// Service account impersonation
SourceCredentials *credentialsFile `json:"source_credentials"`
}
func (c *credentialsFile) getProjectID() string {
if c.Type == "impersonated_service_account" {
return c.SourceCredentials.getProjectID()
}
if c.ProjectID != "" {
return c.ProjectID
}
return c.QuotaProjectID
}