Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .nextchanges/cli/ssh-connect-scope-ownership.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* `databricks ssh connect` now reuses an existing secret scope for its SSH keys only if the scope is Databricks-backed and its ACL grants MANAGE to the current user and no access to any other principal, and otherwise fails with an error that explains how to delete the scope and connect again. ([#8141](https://github.com/databricks/cli/pull/8141))
4 changes: 4 additions & 0 deletions acceptance/ssh/connect-scope-not-owned/out.test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Cloud = false
GOOS.darwin = false
GOOS.linux = true
GOOS.windows = false
28 changes: 28 additions & 0 deletions acceptance/ssh/connect-scope-not-owned/output.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@

>>> [CLI] secrets create-scope [USERNAME]-scope-not-owned-ssh-tunnel-keys

>>> [CLI] secrets put-acl [USERNAME]-scope-not-owned-ssh-tunnel-keys other-user@example.test MANAGE

>>> [CLI] secrets put-secret [USERNAME]-scope-not-owned-ssh-tunnel-keys client-private-key --string-value existing-private-key

>>> [CLI] secrets put-secret [USERNAME]-scope-not-owned-ssh-tunnel-keys client-public-key --string-value ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICTzJweKcgiNoBUAyuvCY2Qu1Od8mKBON5aJeA03Nl+D

=== CLI ssh connect

>>> musterr [CLI] ssh connect --name scope-not-owned -- echo 'Connection successful'
Connecting to scope-not-owned...
Error: failed to create secret scope: secret scope [USERNAME]-scope-not-owned-ssh-tunnel-keys already exists and is not exclusively owned by [USERNAME] (the scope must grant MANAGE to [USERNAME] and no access to other principals). Delete the scope with `databricks secrets delete-scope [USERNAME]-scope-not-owned-ssh-tunnel-keys` (this needs MANAGE permission on the scope; otherwise ask a workspace admin) and connect again once no SSH server for this session is running: a running server keeps the keys of the deleted scope and shuts down --shutdown-delay after its last client disconnects. You can instead connect with a different --name

=== Reported error category

>>> jq -r select(.path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.ssh_tunnel_event.error_category [OUTPUT_DIR]/out.requests.txt
SECRET_SCOPE_FAILED

=== Requests made by ssh connect

>>> print_requests.py --get --oneline //api
{"method": "GET", "path": "/api/2.1/settings/port_fwd_serverless_enabled"}
{"method": "GET", "path": "/api/2.0/preview/scim/v2/Me"}
{"method": "GET", "path": "/api/2.0/secrets/list", "q": {"scope": "[USERNAME]-scope-not-owned-ssh-tunnel-keys"}}
{"method": "GET", "path": "/api/2.0/secrets/scopes/list"}
{"method": "GET", "path": "/api/2.0/secrets/acls/list", "q": {"scope": "[USERNAME]-scope-not-owned-ssh-tunnel-keys"}}
23 changes: 23 additions & 0 deletions acceptance/ssh/connect-scope-not-owned/script
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# An existing keys scope for a serverless connection that also grants access to another
# principal and already holds a client key pair. The fake workspace grants MANAGE on create to
# the current user only, so the other principal is modelled by an extra ACL entry. The CLI
# reuses a scope only if the current user exclusively owns it, so ssh connect must fail without
# reading the stored keys or starting a server.
SCOPE="$CURRENT_USER_NAME-scope-not-owned-ssh-tunnel-keys"
trace $CLI secrets create-scope "$SCOPE"
trace $CLI secrets put-acl "$SCOPE" other-user@example.test MANAGE
trace $CLI secrets put-secret "$SCOPE" client-private-key --string-value "existing-private-key"
trace $CLI secrets put-secret "$SCOPE" client-public-key --string-value 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICTzJweKcgiNoBUAyuvCY2Qu1Od8mKBON5aJeA03Nl+D'
# Drop the setup requests so the checks below only see what ssh connect sent.
print_requests.py //api >/dev/null

title "CLI ssh connect"
trace musterr $CLI ssh connect --name scope-not-owned -- "echo 'Connection successful'"

title "Reported error category"
trace jq -r 'select(.path == "/telemetry-ext") | .body.protoLogs[] | fromjson | .entry.databricks_cli_log.ssh_tunnel_event.error_category' "$OUT_REQUESTS"

# Every request ssh connect made: reads up to the ACL check, then nothing. In particular no
# secrets/get (the stored keys are not read), no secrets/put, no upload and no jobs/runs/submit.
title "Requests made by ssh connect"
trace print_requests.py --get --oneline //api
10 changes: 10 additions & 0 deletions acceptance/ssh/connect-scope-not-owned/test.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
Cloud = false

# Record requests so we can assert that nothing is written or started once the CLI refuses
# the scope.
RecordRequests = true

# The rest of acceptance/ssh only runs on Linux; nothing here needs another OS.
GOOS.linux = true
GOOS.darwin = false
GOOS.windows = false
18 changes: 18 additions & 0 deletions experimental/ssh/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ file with `StrictHostKeyChecking yes`. Tunnel host keys therefore never land in
`~/.ssh/known_hosts`, where a name - unique only within one workspace - would collide with an
entry left by other compute.

### The keys secret scope

Each session keeps its keys in a secret scope named `<user>-<session>-ssh-tunnel-keys`, where
the session is the cluster ID or the serverless `--name`. The CLI creates the scope if it is
missing. It reuses an existing scope only if the scope is Databricks-backed and its ACL is
exactly one entry, MANAGE for the current user, which is what a scope the CLI creates looks
like; otherwise `ssh connect` fails. This keeps other principals from reading or replacing the
keys while the scope is in use: the ACL of an Azure Key Vault-backed scope would not, because
whoever controls the vault can read and replace the keys regardless of it. The checks do not
show who created the scope or wrote the keys in it, and the CLI uses the keys an accepted scope
holds as before.

To recover, delete the scope with `databricks secrets delete-scope <scope>` and connect again
once no SSH server for the session is running. A running server keeps authorizing the client
key it read when it started, and the CLI reuses it, so connecting before it shuts down
(`--shutdown-delay` after its last client disconnects) fails. On serverless you can instead
connect with a different `--name`.

### Filesystem access

On dedicated compute, the tunnel server registers its own process with the filesystem
Expand Down
2 changes: 1 addition & 1 deletion experimental/ssh/internal/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -476,7 +476,7 @@ func Run(ctx context.Context, client *databricks.WorkspaceClient, opts ClientOpt
}
}

secretScopeName, err := keys.CreateKeysSecretScope(ctx, client, sessionID)
secretScopeName, err := keys.CreateKeysSecretScope(ctx, client, sessionID, opts.IsServerlessMode())
if err != nil {
outcome.errorCategory = protos.SshTunnelErrorCategorySecretScopeFailed
return fmt.Errorf("failed to create secret scope: %w", err)
Expand Down
74 changes: 73 additions & 1 deletion experimental/ssh/internal/keys/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ import (

// CreateKeysSecretScope creates or retrieves the secret scope for SSH keys.
// sessionID is the unique identifier for the session (cluster ID for dedicated clusters, connection name for serverless).
func CreateKeysSecretScope(ctx context.Context, client *databricks.WorkspaceClient, sessionID string) (string, error) {
// serverless only selects the recovery advice given when an existing scope is refused.
func CreateKeysSecretScope(ctx context.Context, client *databricks.WorkspaceClient, sessionID string, serverless bool) (string, error) {
me, err := client.CurrentUser.Me(ctx, iam.MeRequest{})
if err != nil {
return "", fmt.Errorf("failed to get current user: %w", err)
Expand All @@ -29,6 +30,12 @@ func CreateKeysSecretScope(ctx context.Context, client *databricks.WorkspaceClie
}

if scope != nil && err == nil {
if err := checkScopeBackend(ctx, client, secretScopeName, serverless); err != nil {
return "", err
}
if err := checkScopeOwnership(ctx, client, secretScopeName, me.UserName, serverless); err != nil {
return "", err
}
return secretScopeName, nil
}

Expand All @@ -41,6 +48,71 @@ func CreateKeysSecretScope(ctx context.Context, client *databricks.WorkspaceClie
return secretScopeName, nil
}

// checkScopeBackend returns an error unless the existing scope is Databricks-backed. The ACL
// of a scope backed by Azure Key Vault governs only access through Databricks: whoever
// controls the vault can read and replace the keys regardless of it.
func checkScopeBackend(ctx context.Context, client *databricks.WorkspaceClient, scope string, serverless bool) error {
// The Secrets API has no call that returns a single scope, so find it in the list.
scopes, err := client.Secrets.ListScopesAll(ctx)
if err != nil {
return fmt.Errorf("failed to list secret scopes: %w", err)
}
for _, s := range scopes {
if s.Name != scope {
continue
}
if s.BackendType != workspace.ScopeBackendTypeDatabricks {
return scopeRefusedError(scope, fmt.Sprintf("is backed by %s (the CLI keeps SSH keys only in a %s-backed scope)", s.BackendType, workspace.ScopeBackendTypeDatabricks), serverless)
}
return nil
}
return fmt.Errorf("secret scope %s is missing from the list of secret scopes", scope)
}

// checkScopeOwnership returns an error unless userName is the only principal with access
// to an existing keys scope: its ACL must have exactly one entry, MANAGE for userName, as the
// service grants to the creator of a scope the CLI creates (CreateScope sets no
// initial_manage_principal). This keeps other principals from reading or replacing keys while
// the scope is in use. It does not prove who created the scope or wrote its secrets: another
// principal can write keys, grant userName MANAGE and then remove its own entry, and the
// client and server still use the keys the scope holds.
func checkScopeOwnership(ctx context.Context, client *databricks.WorkspaceClient, scope, userName string, serverless bool) error {
acls, err := client.Secrets.ListAclsAll(ctx, workspace.ListAclsRequest{Scope: scope})
// Listing ACLs requires MANAGE, so a denial means the user does not own the scope.
if errors.Is(err, databricks.ErrPermissionDenied) {
return scopeNotOwnedError(scope, userName, serverless)
}
if err != nil {
return fmt.Errorf("failed to list ACLs of secret scope %s: %w", scope, err)
}
if len(acls) != 1 || acls[0].Principal != userName || acls[0].Permission != workspace.AclPermissionManage {
return scopeNotOwnedError(scope, userName, serverless)
}
return nil
}

// scopeNotOwnedError advises deleting the scope and connecting again once no server for the
// session is running. The CLI reuses a running server, which keeps authorizing the client key
// it read at startup, while the recreated scope gets a new client key pair and holds no host
// key to pin, so connecting before that server shuts down fails.
func scopeNotOwnedError(scope, userName string, serverless bool) error {
return scopeRefusedError(scope, fmt.Sprintf("is not exclusively owned by %s (the scope must grant MANAGE to %s and no access to other principals)", userName, userName), serverless)
}

// scopeRefusedError reports that an existing keys scope cannot be reused because of problem,
// with the recovery advice described at scopeNotOwnedError.
func scopeRefusedError(scope, problem string, serverless bool) error {
msg := fmt.Sprintf("secret scope %s already exists and %s. "+
"Delete the scope with `databricks secrets delete-scope %s` (this needs MANAGE permission on the scope; otherwise ask a workspace admin) "+
"and connect again once no SSH server for this session is running: a running server keeps the keys of the deleted scope "+
"and shuts down --shutdown-delay after its last client disconnects", scope, problem, scope)
// The serverless session ID is the connection name; a dedicated cluster's is its ID.
if serverless {
msg += ". You can instead connect with a different --name"
}
return errors.New(msg)
}

func GetSecret(ctx context.Context, client *databricks.WorkspaceClient, scope, key string) ([]byte, error) {
resp, err := client.Secrets.GetSecret(ctx, workspace.GetSecretRequest{
Scope: scope,
Expand Down
199 changes: 199 additions & 0 deletions experimental/ssh/internal/keys/secrets_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
package keys_test

import (
"testing"

"github.com/databricks/cli/experimental/ssh/internal/keys"
"github.com/databricks/databricks-sdk-go/apierr"
"github.com/databricks/databricks-sdk-go/experimental/mocks"
"github.com/databricks/databricks-sdk-go/service/iam"
"github.com/databricks/databricks-sdk-go/service/workspace"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const (
testUserName = "me@example.test"
testSessionID = "session-1"
testScopeName = testUserName + "-" + testSessionID + "-ssh-tunnel-keys"
)

func newScopeMock(t *testing.T) *mocks.MockWorkspaceClient {
m := mocks.NewMockWorkspaceClient(t)
m.GetMockCurrentUserAPI().EXPECT().Me(t.Context(), iam.MeRequest{}).Return(&iam.User{UserName: testUserName}, nil)
return m
}

func expectExistingScope(t *testing.T, m *mocks.MockWorkspaceClient, acls []workspace.AclItem, aclErr error) {
secrets := m.GetMockSecretsAPI()
secrets.EXPECT().ListSecretsByScope(t.Context(), testScopeName).Return(&workspace.ListSecretsResponse{}, nil)
secrets.EXPECT().ListScopesAll(t.Context()).Return([]workspace.SecretScope{
{Name: "other-scope", BackendType: workspace.ScopeBackendTypeAzureKeyvault},
{Name: testScopeName, BackendType: workspace.ScopeBackendTypeDatabricks},
}, nil)
secrets.EXPECT().ListAclsAll(t.Context(), workspace.ListAclsRequest{Scope: testScopeName}).Return(acls, aclErr)
}

func TestCreateKeysSecretScopeCreatesMissingScope(t *testing.T) {
m := newScopeMock(t)
secrets := m.GetMockSecretsAPI()
secrets.EXPECT().ListSecretsByScope(t.Context(), testScopeName).Return(nil, &apierr.APIError{
StatusCode: 404,
ErrorCode: "RESOURCE_DOES_NOT_EXIST",
})
secrets.EXPECT().CreateScope(t.Context(), workspace.CreateScope{Scope: testScopeName}).Return(nil)

scope, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
require.NoError(t, err)
assert.Equal(t, testScopeName, scope)
}

func TestCreateKeysSecretScopeReusesOwnScope(t *testing.T) {
m := newScopeMock(t)
expectExistingScope(t, m, []workspace.AclItem{
{Principal: testUserName, Permission: workspace.AclPermissionManage},
}, nil)

scope, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
require.NoError(t, err)
assert.Equal(t, testScopeName, scope)
}

func TestCreateKeysSecretScopeRejectsScopeNotExclusivelyOwned(t *testing.T) {
tests := []struct {
name string
acls []workspace.AclItem
}{
{
name: "another principal also has access",
acls: []workspace.AclItem{
{Principal: testUserName, Permission: workspace.AclPermissionManage},
{Principal: "other@example.test", Permission: workspace.AclPermissionRead},
},
},
{
name: "a group has access",
acls: []workspace.AclItem{
{Principal: testUserName, Permission: workspace.AclPermissionManage},
{Principal: "users", Permission: workspace.AclPermissionWrite},
},
},
{
name: "user has only READ",
acls: []workspace.AclItem{
{Principal: testUserName, Permission: workspace.AclPermissionRead},
},
},
{
name: "user has only WRITE",
acls: []workspace.AclItem{
{Principal: testUserName, Permission: workspace.AclPermissionWrite},
},
},
{
name: "only another principal has MANAGE",
acls: []workspace.AclItem{
{Principal: "other@example.test", Permission: workspace.AclPermissionManage},
},
},
{
name: "no ACLs",
acls: []workspace.AclItem{},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
m := newScopeMock(t)
expectExistingScope(t, m, tc.acls, nil)

_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
assertScopeNotOwnedError(t, err)
})
}
}

// Listing ACLs requires MANAGE, so a user with only READ or WRITE gets PERMISSION_DENIED.
func TestCreateKeysSecretScopeRejectsScopeWhenACLListIsDenied(t *testing.T) {
m := newScopeMock(t)
expectExistingScope(t, m, nil, &apierr.APIError{
StatusCode: 403,
ErrorCode: "PERMISSION_DENIED",
})

_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
assertScopeNotOwnedError(t, err)
}

// A different --name gives a serverless connection a different session and so a different
// scope. On a dedicated cluster the session is the cluster ID, so the hint does not apply.
func TestCreateKeysSecretScopeSuggestsOtherNameOnlyOnServerless(t *testing.T) {
notOwned := []workspace.AclItem{{Principal: "other@example.test", Permission: workspace.AclPermissionManage}}

m := newScopeMock(t)
expectExistingScope(t, m, notOwned, nil)
_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, true)
require.Error(t, err)
assert.Equal(t, scopeNotOwnedMessage+". You can instead connect with a different --name", err.Error())

m = newScopeMock(t)
expectExistingScope(t, m, notOwned, nil)
_, err = keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
assertScopeNotOwnedError(t, err)
}

func TestCreateKeysSecretScopeReturnsOtherACLListErrors(t *testing.T) {
m := newScopeMock(t)
expectExistingScope(t, m, nil, &apierr.APIError{
StatusCode: 500,
ErrorCode: "INTERNAL_ERROR",
Message: "boom",
})

_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
require.Error(t, err)
assert.Equal(t, "failed to list ACLs of secret scope "+testScopeName+": boom", err.Error())
}

// scopeNotOwnedMessage is the error for a refused scope outside serverless mode. Deleting the
// scope alone is not enough while a server for the session runs: the CLI reuses that server,
// which still authorizes the old client key, and the new scope has no host key to pin.
const scopeNotOwnedMessage = "secret scope " + testScopeName + " already exists and is not exclusively owned by " + testUserName +
" (the scope must grant MANAGE to " + testUserName + " and no access to other principals). " +
"Delete the scope with `databricks secrets delete-scope " + testScopeName + "` (this needs MANAGE permission on the scope; otherwise ask a workspace admin) " +
"and connect again once no SSH server for this session is running: a running server keeps the keys of the deleted scope " +
"and shuts down --shutdown-delay after its last client disconnects"

func assertScopeNotOwnedError(t *testing.T, err error) {
t.Helper()
require.Error(t, err)
assert.Equal(t, scopeNotOwnedMessage, err.Error())
}

// The ACL of a scope backed by Azure Key Vault does not govern access through the vault, so
// such a scope is refused before its ACL is read. The mock is strict: an ACL list call fails
// the test.
func TestCreateKeysSecretScopeRejectsScopeNotBackedByDatabricks(t *testing.T) {
m := newScopeMock(t)
secrets := m.GetMockSecretsAPI()
secrets.EXPECT().ListSecretsByScope(t.Context(), testScopeName).Return(&workspace.ListSecretsResponse{}, nil)
secrets.EXPECT().ListScopesAll(t.Context()).Return([]workspace.SecretScope{
{Name: testScopeName, BackendType: workspace.ScopeBackendTypeAzureKeyvault},
}, nil)

_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
require.Error(t, err)
assert.Contains(t, err.Error(), "secret scope "+testScopeName+" already exists and is backed by AZURE_KEYVAULT (the CLI keeps SSH keys only in a DATABRICKS-backed scope). Delete the scope with")
}

func TestCreateKeysSecretScopeFailsWhenScopeIsNotListed(t *testing.T) {
m := newScopeMock(t)
secrets := m.GetMockSecretsAPI()
secrets.EXPECT().ListSecretsByScope(t.Context(), testScopeName).Return(&workspace.ListSecretsResponse{}, nil)
secrets.EXPECT().ListScopesAll(t.Context()).Return([]workspace.SecretScope{
{Name: "other-scope", BackendType: workspace.ScopeBackendTypeDatabricks},
}, nil)

_, err := keys.CreateKeysSecretScope(t.Context(), m.WorkspaceClient, testSessionID, false)
require.Error(t, err)
assert.Equal(t, "secret scope "+testScopeName+" is missing from the list of secret scopes", err.Error())
}
Loading