Skip to content

Commit ce1dbbc

Browse files
mihaimitrea-dbIsaac
andcommitted
auth: check the login settings directly in tests
Compare checksums instead of going through PersistentAuth, the credentials provider and refreshes, and fold the discovery login check into the existing discovery test. Co-authored-by: Isaac <no-reply@databricks.com>
1 parent a190a86 commit ce1dbbc

3 files changed

Lines changed: 40 additions & 120 deletions

File tree

‎cmd/auth/login_test.go‎

Lines changed: 5 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -923,14 +923,15 @@ func TestDiscoveryLogin_IntrospectionFailureStillSavesProfile(t *testing.T) {
923923
introspectionErr: errors.New("introspection failed"),
924924
}
925925

926+
store := storage.NewMemoryStore()
926927
ctx, _ := cmdio.NewTestContextWithStdout(t.Context())
927928
err = discoveryLogin(ctx, discoveryLoginInputs{
928929
dc: dc,
929930
profileName: "DISCOVERY",
930931
timeout: time.Second,
931932
scopes: "all-apis, ,sql,",
932933
browserFunc: func(string) error { return nil },
933-
tokenStore: newTestStore(),
934+
tokenStore: store,
934935
})
935936
require.NoError(t, err)
936937

@@ -944,48 +945,11 @@ func TestDiscoveryLogin_IntrospectionFailureStillSavesProfile(t *testing.T) {
944945
assert.Equal(t, "all-apis,sql", savedProfile.Scopes)
945946
assert.Empty(t, savedProfile.AccountID)
946947
assert.Empty(t, savedProfile.WorkspaceID)
947-
}
948-
949-
func TestDiscoveryLogin_SavedProfileAcceptsStoredToken(t *testing.T) {
950-
configPath := filepath.Join(t.TempDir(), ".databrickscfg")
951-
require.NoError(t, os.WriteFile(configPath, []byte(""), 0o600))
952-
t.Setenv("DATABRICKS_CONFIG_FILE", configPath)
953-
oauthArg, err := u2m.NewBasicDiscoveryOAuthArgument("DISCOVERY")
954-
require.NoError(t, err)
955-
oauthArg.SetDiscoveredHost("https://workspace.example.com")
956-
dc := &fakeDiscoveryClient{
957-
oauthArg: oauthArg,
958-
persistentAuth: &fakeDiscoveryPersistentAuth{
959-
token: &oauth2.Token{AccessToken: "test-token"},
960-
},
961-
introspectionErr: errors.New("introspection failed"),
962-
}
963-
store := storage.NewMemoryStore()
964-
ctx, _ := cmdio.NewTestContextWithStdout(t.Context())
965-
require.NoError(t, discoveryLogin(ctx, discoveryLoginInputs{
966-
dc: dc,
967-
profileName: "DISCOVERY",
968-
timeout: time.Second,
969-
scopes: "sql",
970-
browserFunc: func(string) error { return nil },
971-
tokenStore: store,
972-
}))
973-
savedProfile := loadTestProfile(t, ctx, "DISCOVERY")
974-
975-
// A later read uses the settings saved to the profile, so the stored
976-
// checksum must match them.
977-
savedArg, err := u2m.NewProfileWorkspaceOAuthArgument(savedProfile.Host, "DISCOVERY")
978-
require.NoError(t, err)
979-
read, err := u2m.NewPersistentAuth(ctx,
980-
u2m.WithTokenStore(store),
981-
u2m.WithOAuthArgument(savedArg),
982-
u2m.WithScopes(splitScopes(savedProfile.Scopes)),
983-
)
984-
require.NoError(t, err)
985-
token, err := read.Token()
986948

949+
// Later reads compare the settings saved to the profile with this checksum.
950+
entry, err := store.Lookup("DISCOVERY")
987951
require.NoError(t, err)
988-
assert.Equal(t, "test-token", token.AccessToken)
952+
assert.Equal(t, loginChecksum(*savedProfile), entry.ProfileChecksum)
989953
}
990954

991955
func TestDiscoveryLogin_ProfileSaveFailureDoesNotStoreToken(t *testing.T) {

‎cmd/auth/token_test.go‎

Lines changed: 26 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"context"
66
"encoding/json"
77
"errors"
8-
"fmt"
98
"net/http"
109
"net/url"
1110
"testing"
@@ -84,47 +83,34 @@ func TestLoadTokenChecksLoginSettings(t *testing.T) {
8483
wantErr: new(*u2m.ProfileChangedError),
8584
},
8685
} {
87-
for _, force := range []bool{false, true} {
88-
t.Run(fmt.Sprintf("%s/force=%t", tt.name, force), func(t *testing.T) {
89-
store := storage.NewMemoryStore()
90-
require.NoError(t, store.Put(saved.Name, storage.Entry{
91-
Token: &oauth2.Token{
92-
AccessToken: "cached",
93-
RefreshToken: "refresh",
94-
Expiry: time.Now().Add(time.Hour),
95-
},
96-
ProfileChecksum: tt.checksum,
97-
}))
98-
args := loadTokenArgs{
99-
authArguments: &auth.AuthArguments{},
100-
profileName: saved.Name,
101-
profiler: profile.InMemoryProfiler{Profiles: profile.Profiles{saved}},
102-
tokenStore: store,
103-
tokenTimeout: time.Second,
104-
forceRefresh: force,
105-
persistentAuthOpts: []u2m.PersistentAuthOption{
106-
u2m.WithOAuthEndpointSupplier(&MockApiClient{}),
107-
u2m.WithHttpClient(&http.Client{Transport: fixtures.SliceTransport{refreshSuccessTokenResponse}}),
108-
},
109-
}
86+
t.Run(tt.name, func(t *testing.T) {
87+
store := storage.NewMemoryStore()
88+
require.NoError(t, store.Put(saved.Name, storage.Entry{
89+
Token: &oauth2.Token{
90+
AccessToken: "cached",
91+
Expiry: time.Now().Add(time.Hour),
92+
},
93+
ProfileChecksum: tt.checksum,
94+
}))
95+
args := loadTokenArgs{
96+
authArguments: &auth.AuthArguments{},
97+
profileName: saved.Name,
98+
profiler: profile.InMemoryProfiler{Profiles: profile.Profiles{saved}},
99+
tokenStore: store,
100+
tokenTimeout: time.Second,
101+
}
110102

111-
token, err := loadToken(cmdio.MockDiscard(t.Context()), args)
103+
token, err := loadToken(cmdio.MockDiscard(t.Context()), args)
112104

113-
if tt.wantErr != nil {
114-
require.Error(t, err)
115-
assert.ErrorAs(t, err, tt.wantErr)
116-
assert.Nil(t, token)
117-
assert.NotContains(t, err.Error(), "please report this issue")
118-
return
119-
}
120-
require.NoError(t, err)
121-
if force {
122-
assert.Equal(t, "new-access-token", token.AccessToken)
123-
} else {
124-
assert.Equal(t, "cached", token.AccessToken)
125-
}
126-
})
127-
}
105+
if tt.wantErr != nil {
106+
assert.ErrorAs(t, err, tt.wantErr)
107+
assert.Nil(t, token)
108+
assert.NotContains(t, err.Error(), "please report this issue")
109+
return
110+
}
111+
require.NoError(t, err)
112+
assert.Equal(t, "cached", token.AccessToken)
113+
})
128114
}
129115
}
130116

‎libs/auth/credentials_test.go‎

Lines changed: 9 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,12 @@ import (
88
"path/filepath"
99
"slices"
1010
"testing"
11-
"time"
1211

1312
"github.com/databricks/cli/libs/auth/storage"
1413
"github.com/databricks/cli/libs/auth/u2m"
1514
"github.com/databricks/cli/libs/databrickscfg"
1615
"github.com/databricks/databricks-sdk-go/config"
1716
"github.com/databricks/databricks-sdk-go/config/experimental/auth"
18-
"github.com/databricks/databricks-sdk-go/config/experimental/auth/authconv"
1917
"github.com/stretchr/testify/assert"
2018
"github.com/stretchr/testify/require"
2119
"golang.org/x/oauth2"
@@ -111,53 +109,36 @@ func TestProfileResourcesUsesActualFileSource(t *testing.T) {
111109
assert.Equal(t, []string{"original-resource"}, got)
112110
}
113111

114-
// loginEntry returns the entry that login stores with the given scopes and
115-
// resources.
116-
func loginEntry(scopes, resources []string) storage.Entry {
117-
token := &oauth2.Token{
118-
AccessToken: "token",
119-
Expiry: time.Now().Add(time.Hour),
120-
}
121-
return u2m.NewEntry(token, u2m.TokenRequestParams{
122-
Scopes: scopes,
123-
Resources: resources,
124-
})
125-
}
126-
127112
func TestCLICredentialsChecksLoginSettings(t *testing.T) {
128113
for _, tt := range []struct {
129114
name string
130115
envClientID string
131116
scopes string
132117
resources string
133-
// wantErr is a target for assert.ErrorAs.
134-
wantErr any
118+
// wantMatch is whether the settings still match the login.
119+
wantMatch bool
135120
}{
136121
{
137122
name: "unchanged",
138123
resources: "resource-a",
124+
wantMatch: true,
139125
},
140126
{
141127
name: "client ID from the environment",
142128
envClientID: "other-client",
143129
resources: "resource-a",
144-
wantErr: new(*u2m.ProfileChangedError),
145130
},
146131
{
147132
name: "scopes changed",
148133
scopes: "jobs",
149134
resources: "resource-a",
150-
wantErr: new(*u2m.ProfileChangedError),
151135
},
152136
{
153137
name: "resource changed",
154138
resources: "resource-b",
155-
wantErr: new(*u2m.ProfileChangedError),
156139
},
157140
} {
158141
t.Run(tt.name, func(t *testing.T) {
159-
hermeticAuthStorage(t)
160-
t.Setenv(storage.EnvVar, "plaintext")
161142
t.Setenv("DATABRICKS_CLIENT_ID", tt.envClientID)
162143
scopes := tt.scopes
163144
if scopes == "" {
@@ -169,26 +150,15 @@ func TestCLICredentialsChecksLoginSettings(t *testing.T) {
169150
for _, loader := range databrickscfg.ProfileAuthLoaders {
170151
require.NoError(t, loader.Configure(cfg))
171152
}
172-
store := storage.NewMemoryStore()
173-
require.NoError(t, store.Put("TEST", loginEntry([]string{"sql", "all-apis"}, []string{"resource-a"})))
174-
c := CLICredentials{persistentAuthFn: func(ctx context.Context, opts ...u2m.PersistentAuthOption) (auth.TokenSource, error) {
175-
// Appended last so it replaces the store Configure resolved.
176-
pa, err := u2m.NewPersistentAuth(ctx, append(opts, u2m.WithTokenStore(store))...)
177-
return authconv.AuthTokenSource(pa), err
178-
}}
179-
provider, err := c.Configure(t.Context(), cfg)
180-
require.NoError(t, err)
181-
req, err := http.NewRequest(http.MethodGet, "https://workspace.test", nil)
182-
require.NoError(t, err)
183153

184-
err = provider.SetHeaders(req)
154+
params, err := CLICredentials{}.tokenParamsFromConfig(cfg)
185155

186-
if tt.wantErr != nil {
187-
assert.ErrorAs(t, err, tt.wantErr)
188-
return
189-
}
190156
require.NoError(t, err)
191-
assert.Equal(t, "Bearer token", req.Header.Get("Authorization"))
157+
login := u2m.NewEntry(nil, u2m.TokenRequestParams{
158+
Scopes: []string{"sql", "all-apis"},
159+
Resources: []string{"resource-a"},
160+
})
161+
assert.Equal(t, tt.wantMatch, u2m.NewEntry(nil, params).ProfileChecksum == login.ProfileChecksum)
192162
})
193163
}
194164
}

0 commit comments

Comments
 (0)