aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/cli/auth/auth0/auth0.go
blob: 7fae6e78b6138b75c75e1d03bf854c02a39ff4d5 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

package auth0

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"sort"
	"time"

	"github.com/vespa-engine/vespa/client/go/internal/cli/auth"
	"github.com/vespa-engine/vespa/client/go/internal/util"
)

const (
	accessTokenExpiry = 5 * time.Minute
	reauthMessage     = "re-authenticate with 'vespa auth login'"
)

// Credentials holds the credentials retrieved from Auth0.
type Credentials struct {
	AccessToken string    `json:"access_token,omitempty"`
	Scopes      []string  `json:"scopes,omitempty"`
	ExpiresAt   time.Time `json:"expires_at"`
}

// Client is a client for the Auth0 service.
type Client struct {
	httpClient    util.HTTPClient
	Authenticator *auth.Authenticator // TODO: Make this private
	options       Options
	provider      auth0Provider
}

type Options struct {
	ConfigPath string
	SystemName string
	SystemURL  string
}

// config is the root type of the persisted config
type config struct {
	Version   int       `json:"version"`
	Providers providers `json:"providers"`
}

type providers struct {
	Auth0 auth0Provider `json:"auth0"`
}

type auth0Provider struct {
	Version int                    `json:"version"`
	Systems map[string]Credentials `json:"systems"`
}

// flowConfig represents the authorization flow configuration retrieved from a Vespa system.
type flowConfig struct {
	Audience           string `json:"audience"`
	ClientID           string `json:"client-id"`
	DeviceCodeEndpoint string `json:"device-code-endpoint"`
	OauthTokenEndpoint string `json:"oauth-token-endpoint"`
}

func cancelOnInterrupt() 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
}

// NewClient constructs a new Auth0 client, storing configuration in the given configPath. The client will be configured for
// use in the given Vespa system.
func NewClient(httpClient util.HTTPClient, options Options) (*Client, error) {
	a := Client{}
	a.httpClient = httpClient
	a.options = options
	c, err := a.getDeviceFlowConfig()
	if err != nil {
		return nil, err
	}
	a.Authenticator = &auth.Authenticator{
		Audience:           c.Audience,
		ClientID:           c.ClientID,
		DeviceCodeEndpoint: c.DeviceCodeEndpoint,
		OauthTokenEndpoint: c.OauthTokenEndpoint,
	}
	provider, err := readConfig(options.ConfigPath)
	if err != nil {
		return nil, err
	}
	a.provider = provider
	return &a, nil
}

func (a *Client) getDeviceFlowConfig() (flowConfig, error) {
	url := a.options.SystemURL + "/auth0/v1/device-flow-config"
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return flowConfig{}, err
	}
	r, err := a.httpClient.Do(req, time.Second*30)
	if err != nil {
		return flowConfig{}, fmt.Errorf("auth0: failed to get device flow config: %w", err)
	}
	defer r.Body.Close()
	if r.StatusCode/100 != 2 {
		return flowConfig{}, fmt.Errorf("auth0: failed to get device flow config: got response code %d from %s", r.StatusCode, url)
	}
	var cfg flowConfig
	if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
		return flowConfig{}, fmt.Errorf("auth0: failed to decode response: %w", err)
	}
	return cfg, nil
}

func (a *Client) Authenticate(request *http.Request) error {
	accessToken, err := a.AccessToken()
	if err != nil {
		return err
	}
	if request.Header == nil {
		request.Header = make(http.Header)
	}
	request.Header.Set("Authorization", "Bearer "+accessToken)
	return nil
}

// AccessToken returns an access token for the configured system, refreshing it if necessary.
func (a *Client) AccessToken() (string, error) {
	creds, ok := a.provider.Systems[a.options.SystemName]
	if !ok {
		return "", fmt.Errorf("auth0: system %s is not configured: %s", a.options.SystemName, reauthMessage)
	} else if creds.AccessToken == "" {
		return "", fmt.Errorf("auth0: access token missing: %s", reauthMessage)
	} else if scopesChanged(creds) {
		return "", fmt.Errorf("auth0: authentication scopes changed: %s", reauthMessage)
	} else if isExpired(creds.ExpiresAt, accessTokenExpiry) {
		// check if the stored access token is expired:
		// use the refresh token to get a new access token:
		tr := &auth.TokenRetriever{
			Authenticator: a.Authenticator,
			Secrets:       &auth.Keyring{},
			Client:        http.DefaultClient,
		}
		resp, err := tr.Refresh(cancelOnInterrupt(), a.options.SystemName)
		if err != nil {
			return "", fmt.Errorf("auth0: failed to renew access token: %w: %s", err, reauthMessage)
		} else {
			// persist the updated system with renewed access token
			creds.AccessToken = resp.AccessToken
			creds.ExpiresAt = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second)
			if err := a.WriteCredentials(creds); err != nil {
				return "", err
			}
		}
	}
	return creds.AccessToken, nil
}

func isExpired(t time.Time, ttl time.Duration) bool { return time.Now().Add(ttl).After(t) }

func scopesChanged(s Credentials) bool {
	required := auth.RequiredScopes()
	current := s.Scopes
	if len(required) != len(current) {
		return true
	}
	sort.Strings(required)
	sort.Strings(current)
	for i := range s.Scopes {
		if required[i] != current[i] {
			return true
		}
	}
	return false
}

// WriteCredentials writes given credentials to the configuration file.
func (a *Client) WriteCredentials(credentials Credentials) error {
	if a.provider.Systems == nil {
		a.provider.Systems = make(map[string]Credentials)
	}
	a.provider.Systems[a.options.SystemName] = credentials
	if err := writeConfig(a.provider, a.options.ConfigPath); err != nil {
		return fmt.Errorf("auth0: failed to write config: %w", err)
	}
	return nil
}

// RemoveCredentials removes credentials for the system configured in this client.
func (a *Client) RemoveCredentials() error {
	tr := &auth.TokenRetriever{Secrets: &auth.Keyring{}}
	if err := tr.Delete(a.options.SystemName); err != nil {
		return fmt.Errorf("auth0: failed to remove system %s from secret storage: %w", a.options.SystemName, err)
	}
	delete(a.provider.Systems, a.options.SystemName)
	if err := writeConfig(a.provider, a.options.ConfigPath); err != nil {
		return fmt.Errorf("auth0: failed to write config: %w", err)
	}
	return nil
}

func writeConfig(provider auth0Provider, path string) error {
	dir := filepath.Dir(path)
	if err := os.MkdirAll(dir, 0700); err != nil {
		return err
	}
	version := 1
	provider.Version = version
	r := config{
		Version: version,
		Providers: providers{
			Auth0: provider,
		},
	}
	jsonConfig, err := json.MarshalIndent(r, "", "    ")
	if err != nil {
		return err
	}
	return os.WriteFile(path, jsonConfig, 0600)
}

func readConfig(path string) (auth0Provider, error) {
	f, err := os.Open(path)
	if err != nil {
		if os.IsNotExist(err) {
			return auth0Provider{}, nil
		}
		return auth0Provider{}, err
	}
	defer f.Close()
	cfg := config{}
	if err := json.NewDecoder(f).Decode(&cfg); err != nil {
		return auth0Provider{}, err
	}
	auth0Provider := cfg.Providers.Auth0
	if auth0Provider.Systems == nil {
		auth0Provider.Systems = make(map[string]Credentials)
	}
	return auth0Provider, nil
}