Skip to content

Commit c2f4faa

Browse files
simonfaltumIsaac
andauthored
Remove auth workspace picker limit and support ID search (#7071)
## Why `databricks auth login` against an account host lists the account's workspaces and asks you to pick one. Accounts with more than 50 workspaces only saw the first 50, so the workspace you needed could be missing, and the only way out was rerunning with `--workspace-id`. Search also only matched names, so knowing the ID didn't help. Fixes [BR-2184](https://databricks.atlassian.net/browse/BR-2184), including the picker used by `ug configure`. ## Changes Before: the picker showed the first 50 workspaces and only searched by name. Now: the picker includes every workspace and you can search by name or ID. - Removed the 50-workspace cap in `promptForWorkspaceSelection`. The SDK list call has no pagination or search parameters, so it's still one request and filtering stays local. - Added `newWorkspaceSearcher`, which matches case-insensitive name substrings and ID substrings. An exact ID match narrows the list to that workspace, so typing `123` doesn't also show `1234`. - Every row shows the workspace ID, the highlighted row gets the same `▸` marker as the profile picker, and workspaces without a name render as their ID. The label now says `(search by name or ID)`. - Skip and the manual ID prompt (used when listing fails) behave as before. - Exported `termtest.Run` so command-level prompts can use the same terminal harness as the `cmdio` prompt tests. ## Test plan - [x] Searcher unit tests: name, ID, exact-ID precedence, whitespace, duplicate names, empty names, non-ASCII names, Skip. - [x] Picker tests through the real SDK list/decode path against a local server: more than 50 workspaces, no-results recovery, list errors, non-interactive mode, plus a golden snapshot of the rendered list. - [x] `./task checks`, `./task lint-q`, `./task fmt-q`, and the `cmd/auth/login` acceptance tests. - [x] Synthetic 1k/10k/100k workspace lists through the SDK and terminal picker: search p95 about 17 ms per keystroke. Startup at 100k is dominated by fetching and decoding the full list, which the capped version also did. - [ ] Live account smoke test, including `ug configure`. This pull request and its description were written by Isaac. [BR-2184]: https://databricks.atlassian.net/browse/BR-2184?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ --------- Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 1f5c6ee commit c2f4faa

7 files changed

Lines changed: 316 additions & 13 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* Remove the 50-workspace limit in `auth login` and support searching workspaces by name or ID. ([#7071](https://github.com/databricks/cli/pull/7071))

‎cmd/auth/export_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package auth
2+
3+
var (
4+
NewWorkspaceSearcher = newWorkspaceSearcher
5+
PromptForWorkspaceSelection = promptForWorkspaceSelection
6+
)

‎cmd/auth/login.go‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -882,12 +882,6 @@ func promptForWorkspaceSelection(ctx context.Context, authArguments *auth.AuthAr
882882
return "", nil
883883
}
884884

885-
const maxWorkspaces = 50
886-
if len(workspaces) > maxWorkspaces {
887-
cmdio.LogString(ctx, fmt.Sprintf("Account has %d workspaces. Showing first %d. Use --workspace-id to specify directly.", len(workspaces), maxWorkspaces))
888-
workspaces = workspaces[:maxWorkspaces]
889-
}
890-
891885
if len(workspaces) == 1 {
892886
wsID := strconv.FormatInt(workspaces[0].WorkspaceId, 10)
893887
cmdio.LogString(ctx, fmt.Sprintf("Auto-selected workspace %q (%s)", workspaces[0].WorkspaceName, wsID))
@@ -907,11 +901,38 @@ func promptForWorkspaceSelection(ctx context.Context, authArguments *auth.AuthAr
907901
Id: "",
908902
})
909903

910-
selected, err := cmdio.SelectOrdered(ctx, items, "Select a workspace")
904+
idx, err := cmdio.RunSelect(ctx, cmdio.SelectOptions{
905+
Label: "Select a workspace (search by name or ID)",
906+
Items: items,
907+
HideSelected: true,
908+
StartInSearchMode: true,
909+
Searcher: newWorkspaceSearcher(items),
910+
Active: `▸ {{if .Name}}{{.Name | bold}}{{if .Id}} ({{.Id | faint}}){{end}}{{else}}{{.Id | bold}}{{end}}`,
911+
Inactive: ` {{if .Name}}{{.Name}}{{if .Id}} ({{.Id | faint}}){{end}}{{else}}{{.Id}}{{end}}`,
912+
})
911913
if err != nil {
912914
return "", err
913915
}
914-
return selected, nil
916+
return items[idx].Id, nil
917+
}
918+
919+
// newWorkspaceSearcher gives exact workspace IDs precedence over substring matches.
920+
func newWorkspaceSearcher(items []cmdio.Tuple) func(string, int) bool {
921+
ids := make(map[string]struct{}, len(items))
922+
names := make([]string, len(items))
923+
for idx, item := range items {
924+
names[idx] = strings.ToLower(item.Name)
925+
if item.Id != "" {
926+
ids[item.Id] = struct{}{}
927+
}
928+
}
929+
return func(input string, idx int) bool {
930+
input = strings.TrimSpace(input)
931+
if _, exact := ids[input]; exact {
932+
return items[idx].Id == input
933+
}
934+
return strings.Contains(names[idx], strings.ToLower(input)) || strings.Contains(items[idx].Id, input)
935+
}
915936
}
916937

917938
// promptForWorkspaceID asks the user to manually enter a workspace ID.

‎cmd/auth/login_workspace_test.go‎

Lines changed: 264 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,264 @@
1+
package auth_test
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"encoding/json"
7+
"fmt"
8+
"io"
9+
"net/http"
10+
"net/http/httptest"
11+
"strings"
12+
"sync/atomic"
13+
"testing"
14+
"time"
15+
16+
authcmd "github.com/databricks/cli/cmd/auth"
17+
"github.com/databricks/cli/libs/auth"
18+
"github.com/databricks/cli/libs/cmdio"
19+
"github.com/databricks/cli/libs/cmdio/cmdiotest/termtest"
20+
"github.com/databricks/databricks-sdk-go/service/provisioning"
21+
"github.com/stretchr/testify/assert"
22+
"github.com/stretchr/testify/require"
23+
"golang.org/x/oauth2"
24+
)
25+
26+
const (
27+
workspaceTestAccountID = "test-account"
28+
workspaceTestToken = "test-token"
29+
workspaceSkipLabel = "Skip (account-level access only)"
30+
workspacePickerLabel = "Select a workspace"
31+
workspaceIDPrompt = "Enter workspace ID (empty to skip)"
32+
)
33+
34+
func TestWorkspaceSearcher(t *testing.T) {
35+
items := []cmdio.Tuple{
36+
{Name: "Analytics", Id: "1234"},
37+
{Name: "Report 123", Id: "99"},
38+
{Name: "Production", Id: "123"},
39+
{Name: "Shared", Id: "887766"},
40+
{Name: "Shared", Id: "778899"},
41+
{Name: "", Id: "40"},
42+
{Name: "\u00c5ngstr\u00f6m", Id: "9007199254740993"},
43+
{Name: "Skip Analytics", Id: "0"},
44+
{Name: workspaceSkipLabel, Id: ""},
45+
}
46+
search := authcmd.NewWorkspaceSearcher(items)
47+
for _, tc := range []struct {
48+
name string
49+
query string
50+
want []int
51+
}{
52+
{name: "empty", want: []int{0, 1, 2, 3, 4, 5, 6, 7, 8}},
53+
{name: "whitespace", query: " \t ", want: []int{0, 1, 2, 3, 4, 5, 6, 7, 8}},
54+
{name: "name", query: "aNaLyT", want: []int{0, 7}},
55+
{name: "trim name", query: " Production ", want: []int{2}},
56+
{name: "partial id", query: "887", want: []int{3}},
57+
{name: "partial name or id", query: "12", want: []int{0, 1, 2}},
58+
{name: "exact id beats longer id and numeric name", query: "123", want: []int{2}},
59+
{name: "trim exact id", query: "\t123 ", want: []int{2}},
60+
{name: "duplicate names", query: "shared", want: []int{3, 4}},
61+
{name: "duplicate name by id", query: "778899", want: []int{4}},
62+
{name: "empty name", query: "40", want: []int{5}},
63+
{name: "non ascii name", query: "\u00e5NGSTR\u00d6M", want: []int{6}},
64+
{name: "large id", query: "9007199254740993", want: []int{6}},
65+
{name: "zero id is not skip", query: "0", want: []int{7}},
66+
{name: "skip stays last", query: "sKiP", want: []int{7, 8}},
67+
{name: "skip by label", query: "account-level", want: []int{8}},
68+
{name: "missing name", query: "not-a-workspace"},
69+
{name: "missing id", query: "555555"},
70+
} {
71+
t.Run(tc.name, func(t *testing.T) {
72+
var matches []int
73+
for i := range items {
74+
if search(tc.query, i) {
75+
matches = append(matches, i)
76+
}
77+
}
78+
assert.Equal(t, tc.want, matches)
79+
})
80+
}
81+
}
82+
83+
func TestPromptForWorkspaceSelection(t *testing.T) {
84+
workspaces := make([]provisioning.Workspace, 60)
85+
for i := range workspaces {
86+
workspaces[i] = provisioning.Workspace{
87+
WorkspaceId: int64(1000 + i),
88+
WorkspaceName: fmt.Sprintf("Workspace %c%c", 'A'+i/26, 'A'+i%26),
89+
}
90+
}
91+
workspaces[59] = provisioning.Workspace{WorkspaceId: 9007199254740993, WorkspaceName: "Target Workspace"}
92+
93+
for _, tc := range []struct {
94+
name string
95+
workspaces []provisioning.Workspace
96+
input string
97+
want string
98+
}{
99+
{name: "id beyond first fifty", workspaces: workspaces, input: "9007199254740993", want: "9007199254740993"},
100+
{name: "name beyond first fifty", workspaces: workspaces, input: "tArGeT", want: "9007199254740993"},
101+
{
102+
name: "exact id precedence",
103+
workspaces: []provisioning.Workspace{
104+
{WorkspaceId: 1234, WorkspaceName: "Longer ID"},
105+
{WorkspaceId: 99, WorkspaceName: "Report 123"},
106+
{WorkspaceId: 123, WorkspaceName: "Exact ID"},
107+
},
108+
input: " 123 ", want: "123",
109+
},
110+
{
111+
name: "duplicate names",
112+
workspaces: []provisioning.Workspace{
113+
{WorkspaceId: 111, WorkspaceName: "Shared"},
114+
{WorkspaceId: 222, WorkspaceName: "Shared"},
115+
},
116+
input: "222", want: "222",
117+
},
118+
{
119+
name: "empty name",
120+
workspaces: []provisioning.Workspace{
121+
{WorkspaceId: 111, WorkspaceName: "Named"},
122+
{WorkspaceId: 222},
123+
},
124+
input: "222", want: "222",
125+
},
126+
{
127+
name: "workspace before skip",
128+
workspaces: []provisioning.Workspace{
129+
{WorkspaceId: 111, WorkspaceName: "Named"},
130+
{WorkspaceId: 222, WorkspaceName: "Skip Analytics"},
131+
},
132+
input: "skip", want: "222",
133+
},
134+
{name: "skip", workspaces: workspaces, input: "skip", want: ""},
135+
{name: "whitespace preserves API order", workspaces: workspaces, input: " ", want: "1000"},
136+
} {
137+
t.Run(tc.name, func(t *testing.T) {
138+
args, requests := newWorkspaceListServer(t, http.StatusOK, tc.workspaces)
139+
tm := termtest.Run(t, func(ctx context.Context) (string, error) {
140+
return authcmd.PromptForWorkspaceSelection(ctx, args, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: workspaceTestToken}))
141+
})
142+
tm.WaitFor(workspacePickerLabel)
143+
tm.Type(tc.input + termtest.KeyEnter)
144+
id, err := tm.Result()
145+
require.NoError(t, err)
146+
assert.Equal(t, tc.want, id)
147+
assert.EqualValues(t, 1, requests.Load())
148+
assert.NotContains(t, tm.Raw(), workspaceIDPrompt)
149+
assert.NotContains(t, tm.Raw(), "Showing first")
150+
})
151+
}
152+
}
153+
154+
func TestPromptForWorkspaceSelectionNoResults(t *testing.T) {
155+
args, requests := newWorkspaceListServer(t, http.StatusOK, []provisioning.Workspace{
156+
{WorkspaceId: 111, WorkspaceName: "Alpha"},
157+
{WorkspaceId: 222, WorkspaceName: "Beta"},
158+
{WorkspaceId: 333},
159+
})
160+
tm := termtest.Run(t, func(ctx context.Context) (string, error) {
161+
return authcmd.PromptForWorkspaceSelection(ctx, args, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: workspaceTestToken}))
162+
})
163+
tm.WaitFor(workspacePickerLabel)
164+
tm.Golden("01-initial")
165+
166+
tm.Type("999999")
167+
tm.WaitFor("No results")
168+
tm.Type(termtest.KeyEnter)
169+
tm.Type(strings.Repeat(termtest.KeyBackspace, 6))
170+
require.Eventually(t, func() bool {
171+
return strings.Contains(tm.Snapshot(), workspaceSkipLabel) && !strings.Contains(tm.Snapshot(), "No results")
172+
}, 5*time.Second, 5*time.Millisecond)
173+
tm.Type(termtest.KeyDown + termtest.KeyEnter)
174+
id, err := tm.Result()
175+
require.NoError(t, err)
176+
assert.Equal(t, "222", id)
177+
assert.EqualValues(t, 1, requests.Load())
178+
}
179+
180+
func TestPromptForWorkspaceSelectionWithoutPicker(t *testing.T) {
181+
for _, tc := range []struct {
182+
name string
183+
workspaces []provisioning.Workspace
184+
want string
185+
message string
186+
}{
187+
{name: "no workspaces", workspaces: []provisioning.Workspace{}},
188+
{
189+
name: "one workspace",
190+
workspaces: []provisioning.Workspace{{WorkspaceId: 123, WorkspaceName: "Only Workspace"}},
191+
want: "123",
192+
message: `Auto-selected workspace "Only Workspace" (123)`,
193+
},
194+
} {
195+
t.Run(tc.name, func(t *testing.T) {
196+
args, requests := newWorkspaceListServer(t, http.StatusOK, tc.workspaces)
197+
var output bytes.Buffer
198+
ctx := cmdio.InContext(t.Context(), cmdio.NewTestIO(strings.NewReader(""), io.Discard, &output))
199+
id, err := authcmd.PromptForWorkspaceSelection(ctx, args, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: workspaceTestToken}))
200+
require.NoError(t, err)
201+
assert.Equal(t, tc.want, id)
202+
assert.EqualValues(t, 1, requests.Load())
203+
assert.Contains(t, output.String(), tc.message)
204+
assert.NotContains(t, output.String(), workspacePickerLabel)
205+
assert.NotContains(t, output.String(), workspaceIDPrompt)
206+
})
207+
}
208+
}
209+
210+
func TestPromptForWorkspaceSelectionNonInteractive(t *testing.T) {
211+
args, requests := newWorkspaceListServer(t, http.StatusOK, nil)
212+
ctx, output := cmdio.NewTestContextWithStderr(t.Context())
213+
id, err := authcmd.PromptForWorkspaceSelection(ctx, args, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: workspaceTestToken}))
214+
require.NoError(t, err)
215+
assert.Empty(t, id)
216+
assert.Zero(t, requests.Load())
217+
assert.Contains(t, output.String(), "set workspace_id in your profile")
218+
}
219+
220+
func TestPromptForWorkspaceSelectionListError(t *testing.T) {
221+
for _, input := range []string{" 123456 ", ""} {
222+
t.Run(input, func(t *testing.T) {
223+
args, requests := newWorkspaceListServer(t, http.StatusForbidden, nil)
224+
tm := termtest.Run(t, func(ctx context.Context) (string, error) {
225+
return authcmd.PromptForWorkspaceSelection(ctx, args, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: workspaceTestToken}))
226+
})
227+
tm.WaitFor(workspaceIDPrompt)
228+
tm.Type(input + termtest.KeyEnter)
229+
id, err := tm.Result()
230+
require.NoError(t, err)
231+
assert.Equal(t, strings.TrimSpace(input), id)
232+
assert.EqualValues(t, 1, requests.Load())
233+
assert.NotContains(t, tm.Raw(), workspacePickerLabel)
234+
})
235+
}
236+
}
237+
238+
// newWorkspaceListServer exercises the SDK's actual list decoding without a live account.
239+
func newWorkspaceListServer(t *testing.T, status int, workspaces []provisioning.Workspace) (*auth.AuthArguments, *atomic.Int32) {
240+
t.Helper()
241+
// A developer's DATABRICKS_CONFIG_PROFILE would make the SDK client load
242+
// ~/.databrickscfg and fail on a missing profile. Clearing the whole
243+
// environment instead breaks sockets on Windows, which needs SystemRoot.
244+
t.Setenv("DATABRICKS_CONFIG_PROFILE", "")
245+
body, err := json.Marshal(workspaces)
246+
require.NoError(t, err)
247+
if status != http.StatusOK {
248+
body = []byte(`{"error_code":"PERMISSION_DENIED","message":"Account access denied"}`)
249+
}
250+
requests := new(atomic.Int32)
251+
mux := http.NewServeMux()
252+
mux.HandleFunc("GET /api/2.0/accounts/"+workspaceTestAccountID+"/workspaces", func(w http.ResponseWriter, r *http.Request) {
253+
requests.Add(1)
254+
assert.Empty(t, r.URL.RawQuery)
255+
assert.Equal(t, "Bearer "+workspaceTestToken, r.Header.Get("Authorization"))
256+
w.Header().Set("Content-Type", "application/json")
257+
w.WriteHeader(status)
258+
_, err := w.Write(body)
259+
assert.NoError(t, err)
260+
})
261+
server := httptest.NewServer(mux)
262+
t.Cleanup(server.Close)
263+
return &auth.AuthArguments{Host: server.URL, AccountID: workspaceTestAccountID}, requests
264+
}

‎cmd/auth/testdata/.gitattributes‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# termtest goldens are LF-only snapshots of the VT emulator; keep Windows
2+
# checkouts from converting them to CRLF.
3+
*.golden text eol=lf
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Search: █
2+
? Select a workspace (search by name or ID):
3+
▸ Alpha (111)
4+
Beta (222)
5+
333
6+
Skip (account-level access only)

‎libs/cmdio/cmdiotest/termtest/termtest.go‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,15 @@ type Term[T any] struct {
134134
// it.
135135
func NewPrompt(t *testing.T, opts cmdio.PromptOptions) *Term[string] {
136136
t.Helper()
137-
return run(t, func(ctx context.Context) (string, error) {
137+
return Run(t, func(ctx context.Context) (string, error) {
138138
return cmdio.RunPrompt(ctx, opts)
139139
})
140140
}
141141

142142
// NewSecret runs [cmdio.Secret] in a goroutine and returns a harness for it.
143143
func NewSecret(t *testing.T, label string) *Term[string] {
144144
t.Helper()
145-
return run(t, func(ctx context.Context) (string, error) {
145+
return Run(t, func(ctx context.Context) (string, error) {
146146
return cmdio.Secret(ctx, label)
147147
})
148148
}
@@ -151,7 +151,7 @@ func NewSecret(t *testing.T, label string) *Term[string] {
151151
// it.
152152
func NewSelect(t *testing.T, opts cmdio.SelectOptions) *Term[int] {
153153
t.Helper()
154-
return run(t, func(ctx context.Context) (int, error) {
154+
return Run(t, func(ctx context.Context) (int, error) {
155155
return cmdio.RunSelect(ctx, opts)
156156
})
157157
}
@@ -160,12 +160,14 @@ func NewSelect(t *testing.T, opts cmdio.SelectOptions) *Term[int] {
160160
// harness for it.
161161
func NewSelectOrdered(t *testing.T, items []cmdio.Tuple, label string) *Term[string] {
162162
t.Helper()
163-
return run(t, func(ctx context.Context) (string, error) {
163+
return Run(t, func(ctx context.Context) (string, error) {
164164
return cmdio.SelectOrdered(ctx, items, label)
165165
})
166166
}
167167

168-
func run[T any](t *testing.T, fn func(ctx context.Context) (T, error)) *Term[T] {
168+
// Run drives an interactive command through the same terminal harness as the prompts.
169+
func Run[T any](t *testing.T, fn func(ctx context.Context) (T, error)) *Term[T] {
170+
t.Helper()
169171
inR, inW, err := os.Pipe()
170172
require.NoError(t, err, "open input pipe")
171173
tt := &Term[T]{

0 commit comments

Comments
 (0)