Fix IsServicePrincipal() only working for workspace admins (#732)

## Changes

The latest rendition of isServicePrincipal no longer worked for
non-admin users as it used the "principals get" API.

This new version relies on the property that service principals always
have a UUID as their userName. This was tested with the eng-jaws
principal (8b948b2e-d2b5-4b9e-8274-11b596f3b652).
This commit is contained in:
Lennart Kats (databricks) 2023-09-05 04:20:55 -07:00 committed by GitHub
parent f62def3e77
commit 947d5b1e5c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 29 additions and 21 deletions

View File

@ -160,10 +160,7 @@ func (m *processTargetMode) Apply(ctx context.Context, b *bundle.Bundle) error {
}
return transformDevelopmentMode(b)
case config.Production:
isPrincipal, err := auth.IsServicePrincipal(ctx, b.WorkspaceClient(), b.Config.Workspace.CurrentUser.Id)
if err != nil {
return err
}
isPrincipal := auth.IsServicePrincipal(b.Config.Workspace.CurrentUser.Id)
return validateProductionMode(ctx, b, isPrincipal)
case "":
// No action

View File

@ -1,20 +1,15 @@
package auth
import (
"context"
"github.com/databricks/databricks-sdk-go"
"github.com/databricks/databricks-sdk-go/apierr"
"github.com/google/uuid"
)
// Determines whether a given user id is a service principal.
// This function uses a heuristic: if no user exists with this id, we assume
// it's a service principal. Unfortunately, the standard service principal API is too
// slow for our purposes.
func IsServicePrincipal(ctx context.Context, ws *databricks.WorkspaceClient, userId string) (bool, error) {
_, err := ws.Users.GetById(ctx, userId)
if apierr.IsMissing(err) {
return true, nil
}
return false, err
// This function uses a heuristic: if the user id is a UUID, then we assume
// it's a service principal. Unfortunately, the service principal listing API is too
// slow for our purposes. And the "users" and "service principals get" APIs
// only allow access by workspace admins.
func IsServicePrincipal(userId string) bool {
_, err := uuid.Parse(userId)
return err == nil
}

View File

@ -0,0 +1,19 @@
package auth
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsServicePrincipal_ValidUUID(t *testing.T) {
userId := "8b948b2e-d2b5-4b9e-8274-11b596f3b652"
isSP := IsServicePrincipal(userId)
assert.True(t, isSP, "Expected user ID to be recognized as a service principal")
}
func TestIsServicePrincipal_InvalidUUID(t *testing.T) {
userId := "invalid"
isSP := IsServicePrincipal(userId)
assert.False(t, isSP, "Expected user ID to not be recognized as a service principal")
}

View File

@ -104,10 +104,7 @@ func loadHelpers(ctx context.Context) template.FuncMap {
return false, err
}
}
result, err := auth.IsServicePrincipal(ctx, w, user.Id)
if err != nil {
return false, err
}
result := auth.IsServicePrincipal(user.Id)
is_service_principal = &result
return result, nil
},