/
credentials.go
188 lines (160 loc) · 4.79 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/*
NOTE:
The code is referenced from github.com/openshift/installer//pkg/asset/installconfig/gcp/session.go
this allows ccoctl tool to fetch default gcp credentials in the same way as OpenShift installer
*/
package gcp
import (
"context"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"sync"
"github.com/AlecAivazis/survey/v2"
"github.com/pkg/errors"
"golang.org/x/oauth2/google"
compute "google.golang.org/api/compute/v1"
)
var (
authEnvs = []string{"GOOGLE_CREDENTIALS", "GOOGLE_CLOUD_KEYFILE_JSON", "GCLOUD_KEYFILE_JSON"}
defaultAuthFilePath = filepath.Join(os.Getenv("HOME"), ".gcp", "osServiceAccount.json")
credLoaders = []credLoader{}
onceLoggers = map[credLoader]*sync.Once{}
)
// loadCredentials returns a GCP credentials found in default locations in order:
// env GOOGLE_CREDENTIALS,
// env GOOGLE_CLOUD_KEYFILE_JSON,
// env GCLOUD_KEYFILE_JSON,
// file ~/.gcp/osServiceAccount.json, and
// gcloud cli defaults
// and, if no creds are found, asks for them and stores them on disk in a config file
func loadCredentials(ctx context.Context) (*google.Credentials, error) {
if len(credLoaders) == 0 {
for _, authEnv := range authEnvs {
credLoaders = append(credLoaders, &envLoader{env: authEnv})
}
credLoaders = append(credLoaders, &fileLoader{path: defaultAuthFilePath})
credLoaders = append(credLoaders, &cliLoader{})
for _, credLoader := range credLoaders {
onceLoggers[credLoader] = new(sync.Once)
}
}
for _, loader := range credLoaders {
creds, err := loader.Load(ctx)
if err != nil {
continue
}
onceLoggers[loader].Do(func() {
log.Printf("Credentials loaded from %s", loader)
})
return creds, nil
}
return getCredentials(ctx)
}
func getCredentials(ctx context.Context) (*google.Credentials, error) {
creds, err := (&userLoader{}).Load(ctx)
if err != nil {
return nil, err
}
filePath := defaultAuthFilePath
log.Printf("Saving the credentials to %q", filePath)
if err := os.MkdirAll(filepath.Dir(filePath), 0700); err != nil {
return nil, err
}
if err := ioutil.WriteFile(filePath, creds.JSON, 0600); err != nil {
return nil, err
}
return creds, nil
}
type credLoader interface {
Load(context.Context) (*google.Credentials, error)
}
type envLoader struct {
env string
delegate credLoader
}
func (e *envLoader) Load(ctx context.Context) (*google.Credentials, error) {
if val := os.Getenv(e.env); len(val) > 0 {
e.delegate = &fileOrContentLoader{pathOrContent: val}
return e.delegate.Load(ctx)
}
return nil, errors.New("empty environment variable")
}
func (e *envLoader) String() string {
path := []string{
fmt.Sprintf("environment variable %q", e.env),
}
if e.delegate != nil {
path = append(path, fmt.Sprintf("%s", e.delegate))
}
return strings.Join(path, ", ")
}
type fileOrContentLoader struct {
pathOrContent string
delegate credLoader
}
func (fc *fileOrContentLoader) Load(ctx context.Context) (*google.Credentials, error) {
// if this is a path and we can stat it, assume it's ok
if _, err := os.Stat(fc.pathOrContent); err == nil {
fc.delegate = &fileLoader{path: fc.pathOrContent}
} else {
fc.delegate = &contentLoader{content: fc.pathOrContent}
}
return fc.delegate.Load(ctx)
}
func (fc *fileOrContentLoader) String() string {
if fc.delegate != nil {
return fmt.Sprintf("%s", fc.delegate)
}
return "file or content"
}
type fileLoader struct {
path string
}
func (f *fileLoader) Load(ctx context.Context) (*google.Credentials, error) {
content, err := ioutil.ReadFile(f.path)
if err != nil {
return nil, err
}
return (&contentLoader{content: string(content)}).Load(ctx)
}
func (f *fileLoader) String() string {
return fmt.Sprintf("file %q", f.path)
}
type contentLoader struct {
content string
}
func (f *contentLoader) Load(ctx context.Context) (*google.Credentials, error) {
return google.CredentialsFromJSON(ctx, []byte(f.content), compute.CloudPlatformScope)
}
func (f *contentLoader) String() string {
return "content <redacted>"
}
type cliLoader struct{}
func (c *cliLoader) Load(ctx context.Context) (*google.Credentials, error) {
return google.FindDefaultCredentials(ctx, compute.CloudPlatformScope)
}
func (c *cliLoader) String() string {
return "gcloud CLI defaults"
}
type userLoader struct{}
func (u *userLoader) Load(ctx context.Context) (*google.Credentials, error) {
var content string
err := survey.Ask([]*survey.Question{
{
Prompt: &survey.Multiline{
Message: "Service Account (absolute path to file or JSON content)",
// Due to a bug in survey pkg, help message is not rendered
Help: "The location to file that contains the service account in JSON, or the service account in JSON format",
},
},
}, &content)
if err != nil {
return nil, err
}
content = strings.TrimSpace(content)
return (&fileOrContentLoader{pathOrContent: content}).Load(ctx)
}