/
authenticate.go
429 lines (359 loc) · 12.4 KB
/
authenticate.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
package authenticate
import (
"encoding/json"
"flag"
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"time"
verbex "github.com/VerbalExpressions/GoVerbalExpressions"
"github.com/cloudfoundry/cli/plugin"
w "github.com/ibmjstart/cf-object-storage/writer"
"github.com/ibmjstart/swiftlygo/auth"
)
// timeout represents the amount of time before explicit new token requests.
// OpenStack Object Storage deploys define an auth token timeout value that
// this should correspond to.
const timeout = "1h"
// flagVal holds the flag values.
type flagVal struct {
UrlFlag bool
XAuthFlag bool
}
// credentials holds the info returned with a new cliConnection.
type credentials struct {
AuthUrl string `json:"Auth_URL"`
DomainID string
DomainName string
Password string
Project string
ProjectID string
Region string
Role string
UserID string
Username string
}
// authInfo holds the info used to restablish an existing connection.
type authInfo struct {
AuthToken string
Service string
StorageUrl string
Timestamp time.Time
}
// authenticator holds the info required to authenticate with Object Storage.
type authenticator struct {
cliConnection plugin.CliConnection
authInfo authInfo
creds credentials
writer *w.ConsoleWriter
flagVals flagVal
targetService string
doSave bool
logFile *os.File
logFileSize int64
}
// findService returns true if the target service is present in the current space.
func (a *authenticator) findService() error {
// Get the services in the current space
services, err := a.cliConnection.GetServices()
if err != nil {
return fmt.Errorf("Failed to get services in requested org: %s", err)
}
if len(services) < 1 {
return fmt.Errorf("No services found in current space (check your internet connection)")
}
// Check for target service in the list of present services
found := false
for _, service := range services {
if service.Name == a.targetService {
found = true
}
}
if !found {
return fmt.Errorf("Service '%s' not found in current space", a.targetService)
}
return nil
}
// getCredentialsName returns the name of the target service's credentials.
func (a *authenticator) getCredentialsName() (string, error) {
// Get the service keys for the target service
stdout, err := a.cliConnection.CliCommandWithoutTerminalOutput("service-keys", a.targetService)
if err != nil {
return "", fmt.Errorf("Failed to find credentials for service '%s': %s", a.targetService, err)
}
// Construct regex to extract credentials name
v := verbex.New().
Find("\nname\n").
BeginCapture().
AnythingBut("\n").
EndCapture().
Captures(strings.Join(stdout, "\n"))
// Get name of target service's credentials
var serviceCredentialsName string
if len(v) > 0 && len(v[0]) > 1 {
serviceCredentialsName = v[0][1]
} else {
return "", fmt.Errorf("Could not find credentials for target service")
}
return serviceCredentialsName, nil
}
// getJSONCredentials returns the target service's credentials.
func (a *authenticator) getJSONCredentials(serviceCredentialsName string) (string, error) {
// Get the service key for the target service's credentials
stdout, err := a.cliConnection.CliCommandWithoutTerminalOutput("service-key", a.targetService, serviceCredentialsName)
if err != nil {
return "", fmt.Errorf("Failed to get credentials '%s' for service '%s': %s", serviceCredentialsName, a.targetService, err)
}
// Construct regex to extract JSON
v := verbex.New().
AnythingBut("{").
BeginCapture().
Then("{").
Anything().
StartOfLine().
Then("}").
EndCapture().
Captures(strings.Join(stdout, ""))
// Get target service's credentials
var serviceCredentialsJSON string
if len(v) > 0 && len(v[0]) > 1 {
serviceCredentialsJSON = v[0][1]
} else {
return "", fmt.Errorf("Failed to fetch JSON credentials for service '%s'", a.targetService)
}
return serviceCredentialsJSON, nil
}
// extractAuthFromJSON unmarshalls the JSON saved with a successful connection.
func (a *authenticator) extractAuthFromJSON(authInfoJSON string) error {
var authInfo authInfo
err := json.Unmarshal([]byte(authInfoJSON), &authInfo)
if err != nil {
return fmt.Errorf("Failed to unmarshall authentication info: %s", err)
}
a.authInfo = authInfo
return nil
}
// extractCredsFromJSON unmarshalls the JSON returned by a new cliConnection.
func (a *authenticator) extractCredsFromJSON(serviceCredentialsJSON string) error {
var creds credentials
err := json.Unmarshal([]byte(serviceCredentialsJSON), &creds)
if err != nil {
return fmt.Errorf("Failed to unmarshall JSON credentials: %s", err)
}
// unescape handles escaped unicode characters in JSON
// see: https://github.com/cloudfoundry/cli/issues/794
unescape := func(escaped string) string {
return strings.Replace(
strings.Replace(
strings.Replace(
escaped,
"\u003c", "<", -1),
"\u003e", ">", -1),
"\u0026", "&", -1)
}
creds.AuthUrl = unescape(creds.AuthUrl)
creds.DomainID = unescape(creds.DomainID)
creds.DomainName = unescape(creds.DomainName)
creds.Password = unescape(creds.Password)
creds.Project = unescape(creds.Project)
creds.ProjectID = unescape(creds.ProjectID)
creds.Region = unescape(creds.Region)
creds.Role = unescape(creds.Role)
creds.UserID = unescape(creds.UserID)
creds.Username = unescape(creds.Username)
a.creds = creds
return nil
}
// getNewCredentials fetches a new set of authentication credentials from Object Storage.
func (a *authenticator) getNewCredentials() error {
// Ensure that user is logged in
if loggedIn, err := a.cliConnection.IsLoggedIn(); !loggedIn {
return fmt.Errorf("You are not logged in, please run `cf login` and rerun this command")
} else if err != nil {
return fmt.Errorf("Failed to log in to Cloud Foundry: %s", err)
}
// Find and display services. Ensure target service is within current space
a.writer.SetCurrentStage("Searching for target service")
err := a.findService()
if err != nil {
return fmt.Errorf("Failed to fetch services: %s", err)
}
// Get service keys for target service
a.writer.SetCurrentStage("Locating target service's credentials")
serviceCredentialsName, err := a.getCredentialsName()
if err != nil {
return fmt.Errorf("Failed to locate target service's credentials: %s", err)
}
// Fetch the JSON credentials
a.writer.SetCurrentStage("Fetching credentials")
serviceCredentialsJSON, err := a.getJSONCredentials(serviceCredentialsName)
if err != nil {
return fmt.Errorf("Failed to fetch target service's credentials: %s", err)
}
// Parse the JSON credentials
a.writer.SetCurrentStage("Parsing credentials")
err = a.extractCredsFromJSON(serviceCredentialsJSON)
if err != nil {
return fmt.Errorf("Failed to extract JSON credentials: %s", err)
}
// Ensure new credentails are saved
a.doSave = true
return nil
}
// getSavedCredentials loads the locally saved credentails.
func (a *authenticator) getSavedCredentials() error {
a.writer.SetCurrentStage("Locating service credentials")
// Get current user
currentUser, err := user.Current()
if err != nil {
return fmt.Errorf("Failed to get current user: %s", err)
}
// Find current user's home directory and construct path to credential file
homeDir := currentUser.HomeDir
logLocation := filepath.Join(homeDir, ".cf", "os_creds.json")
// Create directory structure if necessary
err = os.MkdirAll(filepath.Dir(logLocation), 0700)
if err != nil {
return fmt.Errorf("Failed to create directory %s: %s", filepath.Dir(logLocation), err)
}
// Open or create credential file
logFile, err := os.OpenFile(logLocation, os.O_CREATE|os.O_RDWR, 0700)
if err != nil {
return fmt.Errorf("Failed to open/create %s: %s", logLocation, err)
}
// Get credential file's size
logFileStat, err := logFile.Stat()
if err != nil {
return fmt.Errorf("Failed to get file size: %s", err)
}
a.logFile = logFile
a.logFileSize = logFileStat.Size()
return nil
}
// saveCredentials writes the credentails to a local file.
func (a *authenticator) saveCredentials() error {
// Encode JSON credentials
marshalledCredentials, err := json.Marshal(a.authInfo)
if err != nil {
return fmt.Errorf("Failed to JSON encode authentication info: %s", err)
}
// Write credentails to file
err = a.logFile.Truncate(0)
if err != nil {
return fmt.Errorf("Failed to truncate file: %s", err)
}
_, err = a.logFile.Seek(0, 0)
if err != nil {
return fmt.Errorf("Failed to set file offset to 0: %s", err)
}
_, err = a.logFile.Write(marshalledCredentials)
if err != nil {
return fmt.Errorf("Failed to write authentication info to file: %s", err)
}
return nil
}
// parseFlags reads the flags provided.
func parseFlags(args []string) (*flagVal, error) {
flags := args[3:]
flagSet := flag.NewFlagSet("flagSet", flag.ContinueOnError)
url := flagSet.Bool("url", false, "Display auth url in quiet mode")
xAuth := flagSet.Bool("x", false, "Display x-auth token in quiet mode")
err := flagSet.Parse(flags)
if err != nil {
return nil, fmt.Errorf("Failed to parse arguments: %s", err)
}
flagVals := flagVal{
UrlFlag: bool(*url),
XAuthFlag: bool(*xAuth),
}
return &flagVals, nil
}
// Authenticate authenticates the current session with Object Storage and saves the credentails.
func Authenticate(cliConnection plugin.CliConnection, writer *w.ConsoleWriter, targetService string) (auth.Destination, error) {
var (
destination auth.Destination
a = authenticator{
cliConnection: cliConnection,
writer: writer,
targetService: targetService,
doSave: false,
}
)
// Check for and get saved service credentials
err := a.getSavedCredentials()
if err != nil {
return nil, fmt.Errorf("Failed to get saved credentials: %s", err)
}
defer a.logFile.Close()
// Read contents of credential file
logContents := make([]byte, a.logFileSize)
bytesRead, err := a.logFile.Read(logContents)
if err != nil {
return nil, fmt.Errorf("Failed to read credentials: %s", err)
}
// Extract authentication info from file, if not empty
if bytesRead > 0 {
err = a.extractAuthFromJSON(string(logContents))
if err != nil {
return nil, fmt.Errorf("Failed to parse JSON: %s", err)
}
}
// Determine if the found authentication corresponds to the target server
isTargetService := a.authInfo.Service == a.targetService
// Determine if the authentication token is still valid
timeoutDuration, err := time.ParseDuration(timeout)
if err != nil {
return nil, fmt.Errorf("Failed to parse timeout duration: %s", err)
}
isTimedOut := time.Since(a.authInfo.Timestamp) > timeoutDuration
// Authenticate using service credentials
a.writer.SetCurrentStage("Authenticating")
if isTargetService && !isTimedOut {
destination, err = auth.AuthenticateWithToken(a.authInfo.AuthToken, a.authInfo.StorageUrl)
}
if !isTargetService || isTimedOut || err != nil {
err = a.getNewCredentials()
if err != nil {
return nil, fmt.Errorf("Failed to fetch a new set of credentials (Try running `cf login`): %s", err)
}
destination, err = auth.Authenticate(a.creds.Username, a.creds.Password, a.creds.AuthUrl+"/v3", a.creds.DomainName, "")
if err != nil {
return nil, fmt.Errorf("Failed to authenticate: %s", err)
}
a.authInfo.AuthToken = destination.(*auth.SwiftDestination).SwiftConnection.AuthToken
a.authInfo.StorageUrl = destination.(*auth.SwiftDestination).SwiftConnection.StorageUrl
a.authInfo.Service = a.targetService
a.authInfo.Timestamp = time.Now()
}
// Save the credentials, if necessary
if a.doSave {
a.writer.SetCurrentStage("Saving credentials")
err = a.saveCredentials()
if err != nil {
return nil, fmt.Errorf("Failed to save credentials: %s", err)
}
}
return destination, nil
}
// DisplayAuthInfo prints the requested values.
func DisplayAuthInfo(destination auth.Destination, writer *w.ConsoleWriter, args []string) (string, error) {
writer.SetCurrentStage("Fetching authentication info")
serviceName := args[2]
flagVals, err := parseFlags(args)
if err != nil {
return "", fmt.Errorf("Failed to parse flags: %s", err)
}
result := fmt.Sprintf("\r%s%s\n\nAuthenticated with %s\n", w.ClearLine, w.Green("OK"), w.Cyan(serviceName))
// Print requested attributes
if flagVals.UrlFlag {
authUrl := destination.(*auth.SwiftDestination).SwiftConnection.StorageUrl
result += fmt.Sprintf("%s%s\n", w.White("auth url: "), authUrl)
}
if flagVals.XAuthFlag {
xAuth := destination.(*auth.SwiftDestination).SwiftConnection.AuthToken
result += fmt.Sprintf("%s%s\n", w.White("x-auth: "), xAuth)
}
return result, nil
}