aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/cli/cli.go
blob: e1dde387b89eba26a0dd9d795171e0ad2ba13ebc (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package cli

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/joeshaw/envdecode"
	"github.com/pkg/browser"
	"github.com/vespa-engine/vespa/client/go/util"
	"io/ioutil"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"sort"
	"sync"
	"time"

	"github.com/lestrrat-go/jwx/jwt"
	"github.com/vespa-engine/vespa/client/go/auth"
)

const accessTokenExpThreshold = 5 * time.Minute

var errUnauthenticated = errors.New("not logged in. Try 'vespa login'")

type config struct {
	InstallID     string            `json:"install_id,omitempty"`
	DefaultTenant string            `json:"default_tenant"`
	Tenants       map[string]Tenant `json:"tenants"`
}

// Tenant is an auth0 Tenant.
type Tenant struct {
	Name         string    `json:"name"`
	Domain       string    `json:"domain"`
	AccessToken  string    `json:"access_token,omitempty"`
	Scopes       []string  `json:"scopes,omitempty"`
	ExpiresAt    time.Time `json:"expires_at"`
	ClientID     string    `json:"client_id"`
	ClientSecret string    `json:"client_secret"`
}

type Cli struct {
	Authenticator *auth.Authenticator
	tenant        string
	initOnce      sync.Once
	errOnce       error
	Path          string
	config        config
}

// IsLoggedIn encodes the domain logic for determining whether we're
// logged in. This might check our config storage, or just in memory.
func (c *Cli) IsLoggedIn() bool {
	// No need to check errors for initializing context.
	_ = c.init()

	if c.tenant == "" {
		return false
	}

	// Parse the access token for the tenant.
	t, err := jwt.ParseString(c.config.Tenants[c.tenant].AccessToken)
	if err != nil {
		return false
	}

	// Check if token is valid.
	if err = jwt.Validate(t, jwt.WithIssuer("https://vespa-cd.auth0.com/")); err != nil {
		return false
	}

	return true
}

// default to vespa-cd.auth0.com
var (
	authCfg struct {
		Audience           string `env:"AUTH0_AUDIENCE,default=https://vespa-cd.auth0.com/api/v2/"`
		ClientID           string `env:"AUTH0_CLIENT_ID,default=4wYWA496zBP28SLiz0PuvCt8ltL11DZX"`
		DeviceCodeEndpoint string `env:"AUTH0_DEVICE_CODE_ENDPOINT,default=https://vespa-cd.auth0.com/oauth/device/code"`
		OauthTokenEndpoint string `env:"AUTH0_OAUTH_TOKEN_ENDPOINT,default=https://vespa-cd.auth0.com/oauth/token"`
	}
)

func ContextWithCancel() context.Context {
	ctx, cancel := context.WithCancel(context.Background())
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	go func() {
		<-ch
		defer cancel()
		os.Exit(0)
	}()
	return ctx
}

// Setup will try to initialize the config context, as well as figure out if
// there's a readily available tenant.
func GetCli(configPath string) (*Cli, error) {
	c := Cli{}
	c.Path = configPath
	if err := envdecode.StrictDecode(&authCfg); err != nil {
		return nil, fmt.Errorf("could not decode env: %w", err)
	}
	c.Authenticator = &auth.Authenticator{
		Audience:           authCfg.Audience,
		ClientID:           authCfg.ClientID,
		DeviceCodeEndpoint: authCfg.DeviceCodeEndpoint,
		OauthTokenEndpoint: authCfg.OauthTokenEndpoint,
	}
	return &c, nil
}

// prepareTenant loads the Tenant, refreshing its token if necessary.
// The Tenant access token needs a refresh if:
// 1. the Tenant scopes are different from the currently required scopes.
// 2. the access token is expired.
func (c *Cli) PrepareTenant(ctx context.Context) (Tenant, error) {
	if err := c.init(); err != nil {
		return Tenant{}, err
	}
	t, err := c.getTenant()
	if err != nil {
		return Tenant{}, err
	}

	if t.ClientID != "" && t.ClientSecret != "" {
		return t, nil
	}

	if t.AccessToken == "" || scopesChanged(t) {
		t, err = RunLogin(ctx, c, true)
		if err != nil {
			return Tenant{}, err
		}
	} else if isExpired(t.ExpiresAt, accessTokenExpThreshold) {
		// check if the stored access token is expired:
		// use the refresh token to get a new access token:
		tr := &auth.TokenRetriever{
			Authenticator: c.Authenticator,
			Secrets:       &auth.Keyring{},
			Client:        http.DefaultClient,
		}

		res, err := tr.Refresh(ctx, t.Domain)
		if err != nil {
			// ask and guide the user through the login process:
			fmt.Println(fmt.Errorf("failed to renew access token, %s", err))
			t, err = RunLogin(ctx, c, true)
			if err != nil {
				return Tenant{}, err
			}
		} else {
			// persist the updated tenant with renewed access token
			t.AccessToken = res.AccessToken
			t.ExpiresAt = time.Now().Add(
				time.Duration(res.ExpiresIn) * time.Second,
			)

			err = c.AddTenant(t)
			if err != nil {
				return Tenant{}, err
			}
		}
	}

	return t, nil
}

// isExpired is true if now() + a threshold is after the given date
func isExpired(t time.Time, threshold time.Duration) bool {
	return time.Now().Add(threshold).After(t)
}

// scopesChanged compare the Tenant scopes
// with the currently required scopes.
func scopesChanged(t Tenant) bool {
	want := auth.RequiredScopes()
	got := t.Scopes

	sort.Strings(want)
	sort.Strings(got)

	if (want == nil) != (got == nil) {
		return true
	}

	if len(want) != len(got) {
		return true
	}

	for i := range t.Scopes {
		if want[i] != got[i] {
			return true
		}
	}

	return false
}

func (c *Cli) getTenant() (Tenant, error) {
	if err := c.init(); err != nil {
		return Tenant{}, err
	}

	t, ok := c.config.Tenants[c.tenant]
	if !ok {
		return Tenant{}, fmt.Errorf("unable to find tenant: %s; run 'vespa login' to configure a new tenant", c.tenant)
	}

	return t, nil
}

// AddTenant assigns an existing, or new Tenant. This is expected to be called
// after a login has completed.
func (c *Cli) AddTenant(ten Tenant) error {
	_ = c.init()

	if c.config.DefaultTenant == "" {
		c.config.DefaultTenant = ten.Domain
	}

	// If we're dealing with an empty file, we'll need to initialize this map.
	if c.config.Tenants == nil {
		c.config.Tenants = map[string]Tenant{}
	}

	c.config.Tenants[ten.Domain] = ten

	if err := c.persistConfig(); err != nil {
		return fmt.Errorf("unexpected error persisting config: %w", err)
	}

	return nil
}

func (c *Cli) persistConfig() error {
	dir := filepath.Dir(c.Path)
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		if err := os.MkdirAll(dir, 0700); err != nil {
			return err
		}
	}

	buf, err := json.MarshalIndent(c.config, "", "    ")
	if err != nil {
		return err
	}

	if err := ioutil.WriteFile(c.Path, buf, 0600); err != nil {
		return err
	}

	return nil
}

func (c *Cli) init() error {
	c.initOnce.Do(func() {
		if c.errOnce = c.initContext(); c.errOnce != nil {
			return
		}
	})
	return c.errOnce
}

func (c *Cli) initContext() (err error) {
	if _, err := os.Stat(c.Path); os.IsNotExist(err) {
		return errUnauthenticated
	}

	var buf []byte
	if buf, err = ioutil.ReadFile(c.Path); err != nil {
		return err
	}

	if err := json.Unmarshal(buf, &c.config); err != nil {
		return err
	}

	if c.tenant == "" && c.config.DefaultTenant == "" {
		return errUnauthenticated
	}

	if c.tenant == "" {
		c.tenant = c.config.DefaultTenant
	}

	return nil
}

// RunLogin runs the login flow guiding the user through the process
// by showing the login instructions, opening the browser.
// Use `expired` to run the login from other commands setup:
// this will only affect the messages.
func RunLogin(ctx context.Context, cli *Cli, expired bool) (Tenant, error) {
	if expired {
		fmt.Println("Please sign in to re-authorize the CLI.")
	}

	state, err := cli.Authenticator.Start(ctx)
	if err != nil {
		return Tenant{}, fmt.Errorf("could not start the authentication process: %w", err)
	}

	fmt.Printf("Your Device Confirmation code is: %s\n\n", state.UserCode)
	fmt.Println("Press Enter to open the browser to log in or ^C to quit...")
	fmt.Scanln()

	err = browser.OpenURL(state.VerificationURI)

	if err != nil {
		fmt.Printf("Couldn't open the URL, please do it manually: %s.", state.VerificationURI)
	}

	var res auth.Result
	err = util.Spinner("Waiting for login to complete in browser", func() error {
		res, err = cli.Authenticator.Wait(ctx, state)
		return err
	})

	if err != nil {
		return Tenant{}, fmt.Errorf("login error: %w", err)
	}

	fmt.Print("\n")
	fmt.Println("Successfully logged in.")
	fmt.Print("\n")

	// store the refresh token
	secretsStore := &auth.Keyring{}
	err = secretsStore.Set(auth.SecretsNamespace, res.Domain, res.RefreshToken)
	if err != nil {
		// log the error but move on
		fmt.Println("Could not store the refresh token locally, please expect to login again once your access token expired.")
	}

	t := Tenant{
		Name:        res.Tenant,
		Domain:      res.Domain,
		AccessToken: res.AccessToken,
		ExpiresAt:   time.Now().Add(time.Duration(res.ExpiresIn) * time.Second),
		Scopes:      auth.RequiredScopes(),
	}
	err = cli.AddTenant(t)
	if err != nil {
		return Tenant{}, fmt.Errorf("could not add tenant to config: %w", err)
	}

	return t, nil
}