-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathauth.go
More file actions
319 lines (278 loc) · 9.51 KB
/
auth.go
File metadata and controls
319 lines (278 loc) · 9.51 KB
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
package root
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/cmdctx"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/databrickscfg/profile"
"github.com/databricks/cli/libs/logdiag"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/config"
"github.com/manifoldco/promptui"
"github.com/spf13/cobra"
)
type ErrNoWorkspaceProfiles struct {
path string
}
func (e ErrNoWorkspaceProfiles) Error() string {
return e.path + " does not contain workspace profiles; please create one by running 'databricks configure'"
}
type ErrNoAccountProfiles struct {
path string
}
func (e ErrNoAccountProfiles) Error() string {
return e.path + " does not contain account profiles"
}
func initProfileFlag(cmd *cobra.Command) {
cmd.PersistentFlags().StringP("profile", "p", "", "~/.databrickscfg profile")
cmd.RegisterFlagCompletionFunc("profile", profile.ProfileCompletion)
}
func profileFlagValue(cmd *cobra.Command) (string, bool) {
profileFlag := cmd.Flag("profile")
if profileFlag == nil {
return "", false
}
value := profileFlag.Value.String()
return value, value != ""
}
// Helper function to create an account client or prompt once if the given configuration is not valid.
func accountClientOrPrompt(ctx context.Context, cfg *config.Config, allowPrompt bool) (*databricks.AccountClient, error) {
a, err := databricks.NewAccountClient((*databricks.Config)(cfg))
if err == nil {
err = a.Config.Authenticate(emptyHttpRequest(ctx))
}
prompt := false
if allowPrompt && err != nil && cmdio.IsPromptSupported(ctx) {
// Prompt to select a profile if the current configuration is not an account client.
prompt = prompt || errors.Is(err, databricks.ErrNotAccountClient)
// Prompt to select a profile if the current configuration doesn't resolve to a credential provider.
prompt = prompt || errors.Is(err, config.ErrCannotConfigureDefault)
}
if !prompt {
// If we are not prompting, we can return early.
return a, err
}
// Try picking a profile dynamically if the current configuration is not valid.
profile, err := AskForAccountProfile(ctx)
if err != nil {
return nil, err
}
a, err = databricks.NewAccountClient(&databricks.Config{Profile: profile})
if err == nil {
err = a.Config.Authenticate(emptyHttpRequest(ctx))
if err != nil {
return nil, err
}
}
return a, err
}
func MustAnyClient(cmd *cobra.Command, args []string) (bool, error) {
// Try to create a workspace client
werr := MustWorkspaceClient(cmd, args)
if werr == nil {
return false, nil
}
// If the error is other than "not a workspace client error" or "no workspace profiles",
// return it because configuration is for workspace client
// and we don't want to try to create an account client.
if !errors.Is(werr, databricks.ErrNotWorkspaceClient) && !errors.As(werr, &ErrNoWorkspaceProfiles{}) {
return false, werr
}
// Otherwise, the config used is account client one, so try to create an account client
aerr := MustAccountClient(cmd, args)
if errors.As(aerr, &ErrNoAccountProfiles{}) {
return false, aerr
}
return true, aerr
}
func MustAccountClient(cmd *cobra.Command, args []string) error {
cfg := &config.Config{}
// The command-line profile flag takes precedence over DATABRICKS_CONFIG_PROFILE.
pr, hasProfileFlag := profileFlagValue(cmd)
if hasProfileFlag {
cfg.Profile = pr
}
ctx := cmd.Context()
ctx = cmdctx.SetConfigUsed(ctx, cfg)
cmd.SetContext(ctx)
profiler := profile.GetProfiler(ctx)
if cfg.Profile == "" {
// account-level CLI was not really done before, so here are the assumptions:
// 1. only admins will have account configured
// 2. 99% of admins will have access to just one account
// hence, we don't need to create a special "DEFAULT_ACCOUNT" profile yet
profiles, err := profiler.LoadProfiles(cmd.Context(), profile.MatchAccountProfiles)
if err == nil && len(profiles) == 1 {
cfg.Profile = profiles[0].Name
}
// if there is no config file, we don't want to fail and instead just skip it
if err != nil && !errors.Is(err, profile.ErrNoConfiguration) {
return err
}
}
allowPrompt := !hasProfileFlag && !shouldSkipPrompt(cmd.Context())
a, err := accountClientOrPrompt(cmd.Context(), cfg, allowPrompt)
if err != nil {
return renderError(ctx, cfg, err)
}
ctx = cmdctx.SetAccountClient(ctx, a)
cmd.SetContext(ctx)
return nil
}
// Helper function to create a workspace client or prompt once if the given configuration is not valid.
func workspaceClientOrPrompt(ctx context.Context, cfg *config.Config, allowPrompt bool) (*databricks.WorkspaceClient, error) {
w, err := databricks.NewWorkspaceClient((*databricks.Config)(cfg))
if err == nil {
err = w.Config.Authenticate(emptyHttpRequest(ctx))
}
prompt := false
if allowPrompt && err != nil && cmdio.IsPromptSupported(ctx) {
// Prompt to select a profile if the current configuration is not a workspace client.
prompt = prompt || errors.Is(err, databricks.ErrNotWorkspaceClient)
// Prompt to select a profile if the current configuration doesn't resolve to a credential provider.
prompt = prompt || errors.Is(err, config.ErrCannotConfigureDefault)
}
if !prompt {
// If we are not prompting, we can return early.
return w, err
}
// Try picking a profile dynamically if the current configuration is not valid.
profile, err := AskForWorkspaceProfile(ctx)
if err != nil {
return nil, err
}
w, err = databricks.NewWorkspaceClient(&databricks.Config{Profile: profile})
if err == nil {
err = w.Config.Authenticate(emptyHttpRequest(ctx))
if err != nil {
return nil, err
}
}
return w, err
}
func MustWorkspaceClient(cmd *cobra.Command, args []string) error {
ctx := logdiag.InitContext(cmd.Context())
cmd.SetContext(ctx)
cfg := &config.Config{}
// The command-line profile flag takes precedence over DATABRICKS_CONFIG_PROFILE.
profile, hasProfileFlag := profileFlagValue(cmd)
if hasProfileFlag {
cfg.Profile = profile
}
_, isTargetFlagSet := targetFlagValue(cmd)
// If the profile flag is set but the target flag is not, we should skip loading the bundle configuration.
if !isTargetFlagSet && hasProfileFlag {
cmd.SetContext(SkipLoadBundle(cmd.Context()))
}
ctx = cmdctx.SetConfigUsed(cmd.Context(), cfg)
cmd.SetContext(ctx)
// Try to load a bundle configuration if we're allowed to by the caller (see `./auth_options.go`).
if !shouldSkipLoadBundle(cmd.Context()) {
b := TryConfigureBundle(cmd)
// Use the updated context from the command after TryConfigureBundle
ctx = cmd.Context()
if logdiag.HasError(ctx) {
return ErrAlreadyPrinted
}
if b != nil {
ctx = cmdctx.SetConfigUsed(ctx, b.Config.Workspace.Config())
cmd.SetContext(ctx)
client, err := b.WorkspaceClientE()
if err != nil {
return err
}
cfg = client.Config
}
}
allowPrompt := !hasProfileFlag && !shouldSkipPrompt(cmd.Context())
w, err := workspaceClientOrPrompt(cmd.Context(), cfg, allowPrompt)
if err != nil {
return renderError(ctx, cfg, err)
}
ctx = cmdctx.SetWorkspaceClient(ctx, w)
cmd.SetContext(ctx)
return nil
}
func AskForWorkspaceProfile(ctx context.Context) (string, error) {
profiler := profile.GetProfiler(ctx)
path, err := profiler.GetPath(ctx)
if err != nil {
return "", fmt.Errorf("cannot determine Databricks config file path: %w", err)
}
profiles, err := profiler.LoadProfiles(ctx, profile.MatchWorkspaceProfiles)
if err != nil {
return "", err
}
switch len(profiles) {
case 0:
return "", ErrNoWorkspaceProfiles{path: path}
case 1:
return profiles[0].Name, nil
}
i, _, err := cmdio.RunSelect(ctx, &promptui.Select{
Label: "Workspace profiles defined in " + path,
Items: profiles,
Searcher: profiles.SearchCaseInsensitive,
StartInSearchMode: true,
Templates: &promptui.SelectTemplates{
Label: "{{ . | faint }}",
Active: `{{.Name | bold}} ({{.Host|faint}})`,
Inactive: `{{.Name}}`,
Selected: `{{ "Using workspace profile" | faint }}: {{ .Name | bold }}`,
},
})
if err != nil {
return "", err
}
return profiles[i].Name, nil
}
func AskForAccountProfile(ctx context.Context) (string, error) {
profiler := profile.GetProfiler(ctx)
path, err := profiler.GetPath(ctx)
if err != nil {
return "", fmt.Errorf("cannot determine Databricks config file path: %w", err)
}
profiles, err := profiler.LoadProfiles(ctx, profile.MatchAccountProfiles)
if err != nil {
return "", err
}
switch len(profiles) {
case 0:
return "", ErrNoAccountProfiles{path}
case 1:
return profiles[0].Name, nil
}
i, _, err := cmdio.RunSelect(ctx, &promptui.Select{
Label: "Account profiles defined in " + path,
Items: profiles,
Searcher: profiles.SearchCaseInsensitive,
StartInSearchMode: true,
Templates: &promptui.SelectTemplates{
Label: "{{ . | faint }}",
Active: `{{.Name | bold}} ({{.AccountID|faint}} {{.Cloud|faint}})`,
Inactive: `{{.Name}}`,
Selected: `{{ "Using account profile" | faint }}: {{ .Name | bold }}`,
},
})
if err != nil {
return "", err
}
return profiles[i].Name, nil
}
// To verify that a client is configured correctly, we pass an empty HTTP request
// to a client's `config.Authenticate` function. Note: this functionality
// should be supported by the SDK itself.
func emptyHttpRequest(ctx context.Context) *http.Request {
req, err := http.NewRequestWithContext(ctx, "", "", nil)
if err != nil {
panic(err)
}
return req
}
func renderError(ctx context.Context, cfg *config.Config, err error) error {
err, _ = auth.RewriteAuthError(ctx, cfg.Host, cfg.AccountID, cfg.Profile, err)
return err
}