diff --git a/README.md b/README.md
index 521c2846..c5f3cecd 100644
--- a/README.md
+++ b/README.md
@@ -237,6 +237,7 @@ account
├── service principal
└── metastore
└── catalog
+ └── schema
```
A metastore exposes its privileges as entitlements (`CREATE_CATALOG`,
@@ -284,9 +285,9 @@ or `databricks-exclude-workspaces`.
## Unity Catalog provisioning
-A metastore or catalog privilege can be granted to and revoked from a user,
-group or service principal. The `owner` entitlement is read-only: granting or
-revoking it fails with an `InvalidArgument` error.
+A metastore, catalog or schema privilege can be granted to and revoked from a
+user, group or service principal. The `owner` entitlement is read-only: granting
+or revoking it fails with an `InvalidArgument` error.
If a catalog becomes unreachable, provisioning must distinguish deletion from
a workspace binding or visibility change. Requests can fail with
@@ -310,6 +311,15 @@ cover other catalogs. A non-owner using `MANAGE` also needs `USE_CATALOG` for
catalog discovery. An incomplete grants list fails the sync rather than
removing grants the connector cannot see.
+For a schema's full grants list, and to grant or revoke a schema privilege, the
+service principal must own the metastore, the catalog or the schema, hold
+`MANAGE` on the schema or on the catalog above it, or have Admin assigned
+directly on the workspace whose admins group owns the catalog. Listing the
+schemas is a weaker requirement: `USE_SCHEMA` and `ALL_PRIVILEGES` on the
+catalog each return every schema, and neither reads their privileges. A service
+principal holding only one of them syncs its schemas and then fails on their
+grants.
+
The connector requests the `all-apis` OAuth scope. Each resource type declares
the scopes, roles and privileges it needs, so `./baton-databricks capabilities`
reports them per type.
diff --git a/baton_capabilities.json b/baton_capabilities.json
index 6a663099..fbee54d9 100644
--- a/baton_capabilities.json
+++ b/baton_capabilities.json
@@ -255,6 +255,91 @@
]
}
},
+ {
+ "resourceType": {
+ "id": "schema",
+ "displayName": "Schema",
+ "traits": [
+ "TRAIT_APP"
+ ],
+ "annotations": [
+ {
+ "@type": "type.googleapis.com/c1.connector.v2.OptInRequired"
+ },
+ {
+ "@type": "type.googleapis.com/c1.connector.v2.CapabilityPermissions",
+ "permissions": [
+ {
+ "permission": "unity-catalog"
+ },
+ {
+ "permission": "scim"
+ },
+ {
+ "permission": "access-management"
+ },
+ {
+ "permission": "provisioning"
+ },
+ {
+ "permission": "Account admin"
+ },
+ {
+ "permission": "Workspace admin"
+ },
+ {
+ "permission": "USE_CATALOG"
+ },
+ {
+ "permission": "USE_SCHEMA"
+ },
+ {
+ "permission": "MANAGE"
+ }
+ ]
+ },
+ {
+ "@type": "type.googleapis.com/c1.connector.v2.SkipEntitlements"
+ }
+ ]
+ },
+ "capabilities": [
+ "CAPABILITY_SYNC",
+ "CAPABILITY_PROVISION"
+ ],
+ "permissions": {
+ "permissions": [
+ {
+ "permission": "unity-catalog"
+ },
+ {
+ "permission": "scim"
+ },
+ {
+ "permission": "access-management"
+ },
+ {
+ "permission": "provisioning"
+ },
+ {
+ "permission": "Account admin"
+ },
+ {
+ "permission": "Workspace admin"
+ },
+ {
+ "permission": "USE_CATALOG"
+ },
+ {
+ "permission": "USE_SCHEMA"
+ },
+ {
+ "permission": "MANAGE"
+ }
+ ]
+ },
+ "optInRequired": true
+ },
{
"resourceType": {
"id": "service_principal",
diff --git a/docs/connector.mdx b/docs/connector.mdx
index 1593a15a..d9c5cfe1 100644
--- a/docs/connector.mdx
+++ b/docs/connector.mdx
@@ -15,6 +15,7 @@ sidebarTitle: "Databricks"
| Groups | | |
| Metastores | | |
| Roles | | |
+| Schemas | | |
| Service principals | | |
| Users | | |
| Workspaces | | |
@@ -29,19 +30,19 @@ Revoking the workspace **member** entitlement removes the principal's entire wor
[This connector syncs non-human identities](/product/admin/nhi) and displays them on the **Identities overview** dashboard.
-## Metastore and catalog access in C1
+## Metastore, catalog and schema access in C1
The connector syncs Databricks [Unity Catalog](https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges)
-metastores and the catalogs in them as C1 resources. Each privilege Databricks
+metastores, the catalogs in them, and the schemas in those catalogs as C1 resources. Each privilege Databricks
records on one of them (`CREATE_CATALOG` on a metastore, `USE_CATALOG` or
-`SELECT` on a catalog, and so on) becomes an entitlement in C1, so you can
+`SELECT` on a catalog, `USE_SCHEMA` on a schema, and so on) becomes an entitlement in C1, so you can
review who holds it, request it, and revoke it for users, groups and service
principals. A grant held by a group is expandable so C1 can resolve the
group's members as holders. Ownership is shown as a read-only `owner`
entitlement — it cannot be granted or revoked through C1.
-The Metastores and Catalogs resource types are turned off by default. Turn on the ones you want from the connector's configuration page in C1. Catalogs sync under their metastore, so turn on Metastores as well as Catalogs; turning on Catalogs alone syncs nothing. Both use the same OAuth credentials; no additional configuration fields are needed.
+The Metastores, Catalogs and Schemas resource types are turned off by default. Turn on the ones you want from the connector's configuration page in C1. Catalogs sync under their metastore and schemas under their catalog, so turn on every level above the one you want; turning on Catalogs alone, or Schemas without Catalogs, syncs nothing. They all use the same OAuth credentials; no additional configuration fields are needed.
@@ -50,7 +51,8 @@ The Metastores and Catalogs resource types are turned off by default. Turn on th
- Ownership is shown but cannot be provisioned. An owner that is not a Databricks account identity, such as a system account or a workspace admins group, is not shown at all.
- **MANAGE** and **ALL_PRIVILEGES** are not offered on a metastore, because Databricks rejects both at that level.
- A catalog is synced when any running workspace in scope attached to its metastore lists it, and the same catalog name is kept once per metastore. A catalog that only excluded workspaces can reach is not synced.
-- The built-in `system` catalog is never synced, and neither is any other catalog Databricks marks as a system catalog, whoever owns it.
+- The built-in `system` catalog is never synced, and neither is any other catalog Databricks marks as a system catalog, whoever owns it. Their schemas are not synced either.
+- `information_schema` is skipped in every catalog.
- If a catalog becomes unreachable, access requests can fail until the connector can distinguish deletion from a binding or visibility change. Catalog ownership or **MANAGE** alone cannot prove deletion; that check requires the **Metastore Admin**.
- Unity Catalog tags are not synced.
@@ -210,6 +212,32 @@ The connector asks every running workspace in scope attached to the metastore, s
If the service principal cannot list catalogs at all through one of those workspaces, the connector cannot tell which catalogs are there, so the sync fails naming the metastore and that workspace instead of removing the catalogs it could not list. Give the service principal **Admin** on that workspace, or leave that workspace out with **Workspaces** or **Exclude Workspaces**.
+### Let the service principal list schemas and read their privileges
+
+Skip this section if you are not syncing schemas, or if the service principal is the **Metastore Admin** or owns the catalog.
+
+Grant **MANAGE** on each catalog whose schemas you want synced, on top of the **USE CATALOG** from the previous section. **MANAGE** covers both halves: it lists every schema in the catalog and it reads who holds what on each one.
+
+**USE SCHEMA** and **ALL PRIVILEGES** are not substitutes: either one lists every schema, and then the sync fails on their grants.
+
+Workspace **Admin** replaces all of this only when the catalog is owned by that workspace's admins group (`_workspace_admins__`) and the service principal is a direct Admin of that workspace.
+
+
+
+ In the workspace, open **Catalog Explorer** and open the catalog.
+
+
+ Select **Permissions**, then click **Grant**.
+
+
+ Select the service principal, check **MANAGE**, and confirm.
+
+
+
+
+A catalog whose schemas cannot all be listed fails the sync, and so does a schema whose privilege list cannot be proved complete, named in the error.
+
+
**Done.** Here's the set of credentials you'll need when setting up the connector:
- Account ID
diff --git a/docs/docs-info.md b/docs/docs-info.md
index 35740b25..c8c6d939 100644
--- a/docs/docs-info.md
+++ b/docs/docs-info.md
@@ -60,10 +60,14 @@ While developing the connector, please fill out this form. This information is n
- **Ownership is read-only.** It is shown and cannot be granted or revoked. An owner that is not an account identity (`System user`, `_workspace_admins_…`) is not shown.
- **No `MANAGE` or `ALL_PRIVILEGES` on a metastore.** Databricks rejects both, so they are not offered.
- **Read through one running workspace.** Privileges are not served on the account plane. The connector reads each metastore through the first running workspace in scope where it can see every privilege. With no running workspace in scope, the metastore is not synced and ConductorOne removes it. A workspace that is still provisioning fails the sync until it is `RUNNING`. An unreadable assignment list fails the sync and ConductorOne keeps the metastore.
-- **`workspaces` scopes metastores.** An allowlist that names no workspace on the account fails at credential validation, before any sync.
+- **`workspaces` scopes metastores.** An allowlist in which every name is either missing from the account or listed in `databricks-exclude-workspaces` fails at credential validation, before any sync, with one error that names both causes.
- **Catalogs are opt-in.** The resource type is off until it is turned on from the connector's configuration page in C1.
- **Catalog discovery visits every attached workspace in scope.** The connector asks each running workspace attached to the metastore, including for `ISOLATED` catalogs bound to only some workspaces. Each catalog name is kept once per metastore. A catalog bound only to workspaces the sync excludes is not listed, and C1 removes it with its grants.
- **A catalog is keyed by its name.** `CatalogInfo` exposes no immutable catalog id (only `name` and the derived `full_name`), so the resource id is `::`. The update API accepts `new_name`, so an owner can rename a catalog; a rename re-keys the resource and its grants.
- **System catalogs are excluded regardless of ownership.** The built-in `system` catalog and any catalog with `CatalogType == "SYSTEM_CATALOG"` are excluded, including `samples` when it has that type.
- **Seeing a catalog needs more than `MANAGE`.** The list holds the catalogs the service principal owns or holds `USE_CATALOG` on, or every catalog when it is the metastore admin. `MANAGE` alone reads a catalog's privileges but does not make it appear.
-- **Not synced yet:** schemas, tables, volumes, functions, registered models, external locations, storage credentials, connections, shares, recipients, and tags.
+- **Schemas are opt-in and hang from a catalog.** The resource type is off until it is turned on in C1, and it syncs nothing unless Catalogs and Metastores are on as well.
+- **A schema is keyed by its full name.** `SchemaInfo` does carry an immutable `schema_id`, but no endpoint accepts it: `GET` and `PATCH` on a schema both address it as `catalog.schema`, so keying on the id would mean listing the catalog's schemas on every read and write just to recover that name. The parent catalog has no immutable id at all, so a catalog rename re-keys the schema either way. The resource id is `::.`, and a schema rename re-keys the resource and its grants, as it does for a catalog.
+- **`information_schema` is skipped in every catalog.** Databricks creates it read-only in every catalog and its privileges cannot be granted, so it would sync entitlements no one can hold or request.
+- **Listing schemas is weaker than reading their privileges.** `USE_SCHEMA` and `ALL_PRIVILEGES` on the catalog each make the listing complete. Neither reads a schema's privileges, because Databricks leaves `MANAGE` out of `ALL_PRIVILEGES`: that read needs ownership of the metastore, the catalog or the schema, `MANAGE` on the schema or the catalog, or direct workspace Admin where the admins group owns the catalog.
+- **Not synced yet:** tables, volumes, functions, registered models, external locations, storage credentials, connections, shares, recipients, and tags.
diff --git a/pkg/connector/catalog.go b/pkg/connector/catalog.go
index dea8f40c..5d4d5c15 100644
--- a/pkg/connector/catalog.go
+++ b/pkg/connector/catalog.go
@@ -41,7 +41,8 @@ const (
errorCodeMetastoreGone = "METASTORE_DOES_NOT_EXIST"
// systemCatalog is the built-in catalog Databricks puts in every metastore.
- // It is excluded independently of the connector's ownership.
+ // samples is the other one; both are SYSTEM_CATALOG. Both are excluded
+ // independently of the connector's ownership.
systemCatalog = "system"
// workspaceAdminsGroupPrefix starts the name of the system group Databricks
@@ -187,7 +188,10 @@ func catalogResource(
nil,
rs.WithResourceProfile(profile),
rs.WithParentResourceID(parent),
- rs.WithAnnotation(&v2.RawId{Id: resourceID}),
+ rs.WithAnnotation(
+ &v2.ChildResourceType{ResourceTypeId: schemaResourceType.Id},
+ &v2.RawId{Id: resourceID},
+ ),
)
}
@@ -473,7 +477,13 @@ func catalogGrantsAreTrustworthy(
}
}
- return holdsCatalogManage(ctx, client, trust, annos)
+ manages, err := holdsPrivilegeOn(ctx, client, trust, databricks.SecurableCatalog, trust.fullName,
+ managePrivilege, []string{errorCodeCatalogGone}, annos)
+ if errors.Is(err, errSecurableGone) {
+ return false, errCatalogGone
+ }
+
+ return manages, err
}
func catalogAdminWorkspaceID(owner string) (string, bool) {
@@ -492,61 +502,6 @@ func catalogAdminWorkspaceID(owner string) (string, bool) {
return id, true
}
-// holdsCatalogManage asks the permissions endpoint for the connector's own
-// effective privileges on the catalog. The principal filter is effective, not
-// literal: a row can be the MANAGE a group holds and this principal inherits, so
-// only the privileges are read and never the principal field. The read bypasses
-// the cache, because a remembered page would decide this call with the access of
-// an earlier one.
-//
-// ALL_PRIVILEGES is not enough. Databricks leaves MANAGE out of it, so its holder
-// still reads a partial list.
-// https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges
-func holdsCatalogManage(
- ctx context.Context,
- client *databricks.Client,
- trust securableTrust,
- annos *annotations.Annotations,
-) (bool, error) {
- if trust.ownPrincipal == "" || trust.workspace == "" {
- return false, nil
- }
-
- var manages bool
- rateLimit, err := client.ForEachUncachedPermissionsPage(ctx, trust.workspace, databricks.SecurableCatalog, trust.fullName, trust.ownPrincipal,
- func(page []databricks.PrivilegeAssignment) (bool, error) {
- for _, assignment := range page {
- if slices.Contains(assignment.Privileges, privilegeManage) {
- manages = true
-
- return true, nil
- }
- }
-
- return false, nil
- })
- noteRateLimit(annos, rateLimit)
- if err != nil {
- if databricks.IsSecurableGone(err, errorCodeCatalogGone) {
- return false, errCatalogGone
- }
- if apiStatus(err) == http.StatusNotFound {
- return false, refuseUnreadable(
- fmt.Sprintf("databricks-connector: failed to read the connector's own privileges on catalog %s", trust.fullName), err)
- }
- if !deniesTrust(err) {
- return false, fmt.Errorf("databricks-connector: failed to read the connector's own privileges on catalog %s: %w", trust.fullName, err)
- }
- ctxzap.Extract(ctx).Debug("databricks-connector: the connector's own privileges on the catalog cannot be read, so MANAGE stays unproven",
- zap.String("catalog", trust.fullName),
- zap.Error(err))
-
- return false, nil
- }
-
- return manages, nil
-}
-
func (b *catalogBuilder) Grants(ctx context.Context, resource *v2.Resource, attr rs.SyncOpAttrs) ([]*v2.Grant, *rs.SyncOpResults, error) {
return b.syncGrants(ctx, resource, attr)
}
@@ -606,7 +561,7 @@ func (b *catalogBuilder) entitlementOnLiveRoute(
}
var probe catalogProbe
- if route, ok := b.profileRoute(resource, owner); ok {
+ if route, ok := profileCatalogRoute(b.client, b.workspaces, resource, owner); ok {
catalog, err := catalogThrough(ctx, b.client, route.Workspace, metastoreID, catalogName, annos)
// This read is an optimization, so no answer it gives is fatal: a catalog
// absent from this one workspace is not absent from the metastore, a refusal
@@ -647,10 +602,10 @@ func (b *catalogBuilder) entitlementOnLiveRoute(
metastoreID, catalogName)
}
- workspace, catalog, err := workspaceForCatalog(ctx, b.client, metastoreID, catalogName, usable, probe, annos)
+ workspace, catalog, err := workspaceForCatalog(ctx, b.client, metastoreID, catalogName, usable, probe, nil, annos)
if err != nil {
if errors.Is(err, errCatalogGone) {
- return nil, b.confirmCatalogGone(ctx, metastoreID, catalogName, usable[0].DeploymentName, owner, annos)
+ return nil, confirmCatalogGone(ctx, b.client, b.clientID, metastoreID, catalogName, usable[0].DeploymentName, owner, annos)
}
return nil, err
}
@@ -673,24 +628,30 @@ type catalogProbe struct {
deny error
}
-// profileRoute is the route an earlier sync wrote, when this sync still admits
-// that workspace. The profile carries the three identifiers the configuration
-// matches on, so the allowlist and the exclude set are both answered here without
-// reading the account's workspaces or the metastore's assignments.
-func (b *catalogBuilder) profileRoute(resource *v2.Resource, owner string) (catalogRoute, bool) {
+// profileCatalogRoute is the route an earlier sync wrote, when this sync still
+// admits that workspace. The profile carries the three identifiers the
+// configuration matches on, so the allowlist and the exclude set are both
+// answered here without reading the account's workspaces or the metastore's
+// assignments.
+func profileCatalogRoute(
+ client *databricks.Client,
+ workspaces map[string]struct{},
+ resource *v2.Resource,
+ metastoreOwner string,
+) (catalogRoute, bool) {
profile := rs.GetProfile(resource)
- route := catalogRoute{MetastoreOwner: owner}
+ route := catalogRoute{MetastoreOwner: metastoreOwner}
route.Workspace, _ = rs.GetProfileStringValue(profile, profileKeyWorkspace)
route.WorkspaceID, _ = rs.GetProfileStringValue(profile, profileKeyWorkspaceID)
route.WorkspaceName, _ = rs.GetProfileStringValue(profile, profileKeyWorkspaceName)
if route.Workspace == "" {
return catalogRoute{}, false
}
- if b.client.IsWorkspaceExcluded(route.WorkspaceName, route.Workspace, route.WorkspaceID) {
+ if client.IsWorkspaceExcluded(route.WorkspaceName, route.Workspace, route.WorkspaceID) {
return catalogRoute{}, false
}
- if len(b.workspaces) > 0 {
- if _, ok := matchConfiguredWorkspace(b.workspaces, route.Workspace, route.WorkspaceName, route.WorkspaceID); !ok {
+ if len(workspaces) > 0 {
+ if _, ok := matchConfiguredWorkspace(workspaces, route.Workspace, route.WorkspaceName, route.WorkspaceID); !ok {
return catalogRoute{}, false
}
}
@@ -710,19 +671,34 @@ func routedEntitlement(
return nil, err
}
- copyEntitlement := proto.Clone(entitlement).(*v2.Entitlement)
+ return entitlementOnResource(entitlement, routed)
+}
+
+// entitlementOnResource returns the entitlement addressed at the securable as it
+// was just read, leaving the caller's copy untouched.
+func entitlementOnResource(entitlement *v2.Entitlement, routed *v2.Resource) (*v2.Entitlement, error) {
+ copyEntitlement, ok := proto.Clone(entitlement).(*v2.Entitlement)
+ if !ok {
+ return nil, status.Error(codes.Internal, "databricks-connector: cannot copy the entitlement")
+ }
copyEntitlement.Resource = routed
return copyEntitlement, nil
}
-func (b *catalogBuilder) confirmCatalogGone(
+// confirmCatalogGone turns "no workspace in scope lists the catalog" into proof
+// of deletion, which only the metastore owner can get: it lists the metastore's
+// catalogs with include_unbound=true, where a catalog hidden by a binding still
+// appears.
+func confirmCatalogGone(
ctx context.Context,
+ client *databricks.Client,
+ clientID string,
metastoreID, catalogName, workspace, metastoreOwner string,
annos *annotations.Annotations,
) error {
ctx = databricks.WithoutCache(ctx)
- if !ownsPrincipal(b.clientID, metastoreOwner) || workspace == "" {
+ if !ownsPrincipal(clientID, metastoreOwner) || workspace == "" {
return status.Errorf(codes.FailedPrecondition,
"databricks-connector: cannot prove whether catalog %s of metastore %s was deleted; the metastore owner must list it with include_unbound=true",
catalogName, metastoreID)
@@ -730,7 +706,7 @@ func (b *catalogBuilder) confirmCatalogGone(
pageToken := ""
for {
- catalogs, next, rateLimit, err := b.client.ListCatalogs(ctx, workspace, pageToken, ResourcesPageSize, true)
+ catalogs, next, rateLimit, err := client.ListCatalogs(ctx, workspace, pageToken, ResourcesPageSize, true)
noteRateLimit(annos, rateLimit)
if err != nil {
msg := fmt.Sprintf("databricks-connector: cannot prove whether catalog %s of metastore %s was deleted with include_unbound=true",
diff --git a/pkg/connector/catalog_test.go b/pkg/connector/catalog_test.go
index ee332e36..0f148bba 100644
--- a/pkg/connector/catalog_test.go
+++ b/pkg/connector/catalog_test.go
@@ -415,7 +415,7 @@ func TestCatalogListSkipsBuiltInCatalogs(t *testing.T) {
f := &fakeCatalogAccount{
attached: []int{1},
listed: map[string][]map[string]any{"wsa": {
- catalogEntry(systemCatalog, "someone"),
+ catalogEntry(systemCatalog, "System user"),
{"name": "samples", "metastore_id": "ms-1", "owner": "System user", "catalog_type": "SYSTEM_CATALOG"},
catalogEntry("owned", "app-9"),
}},
diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go
index 85d84aa4..f06c4efc 100644
--- a/pkg/connector/connector.go
+++ b/pkg/connector/connector.go
@@ -44,6 +44,7 @@ func (d *Databricks) ResourceSyncers(_ context.Context) []connectorbuilder.Resou
newRoleBuilder(d.client),
newMetastoreBuilder(d.client, d.clientID, workspaces, principals),
newCatalogBuilder(d.client, d.clientID, workspaces, principals),
+ newSchemaBuilder(d.client, d.clientID, workspaces, principals),
}
}
@@ -75,7 +76,7 @@ func (d *Databricks) Metadata(_ context.Context) (*v2.ConnectorMetadata, error)
return &v2.ConnectorMetadata{
DisplayName: "Databricks",
Description: "Connector syncing Databricks workspaces, users, groups, service principals and roles to Baton, " +
- "along with Unity Catalog data assets — metastores and catalogs — and the privileges granted on them",
+ "along with Unity Catalog data assets — metastores, catalogs and schemas — and the privileges granted on them",
AccountCreationSchema: &v2.ConnectorAccountCreationSchema{
FieldMap: map[string]*v2.ConnectorAccountCreationSchema_Field{
"email": {
diff --git a/pkg/connector/connector_test.go b/pkg/connector/connector_test.go
index c38751f9..b2d96dcb 100644
--- a/pkg/connector/connector_test.go
+++ b/pkg/connector/connector_test.go
@@ -87,7 +87,7 @@ func TestResourceSyncersAlwaysRegisterTheUnityCatalogBuilders(t *testing.T) {
for _, syncer := range d.ResourceSyncers(ctx) {
registered = append(registered, syncer.ResourceType(ctx).GetId())
}
- for _, want := range []string{metastoreResourceType.Id, catalogResourceType.Id} {
+ for _, want := range []string{metastoreResourceType.Id, catalogResourceType.Id, schemaResourceType.Id} {
if !slices.Contains(registered, want) {
t.Errorf("registered syncers = %v, want them to include %s", registered, want)
}
diff --git a/pkg/connector/metastore_helpers.go b/pkg/connector/metastore_helpers.go
index c9b72176..79b0f8d1 100644
--- a/pkg/connector/metastore_helpers.go
+++ b/pkg/connector/metastore_helpers.go
@@ -467,6 +467,126 @@ func ownPrincipalScimID(
return id, nil
}
+// managePrivilege is what a trust rule looks for when ownership did not settle
+// it. ALL_PRIVILEGES is deliberately not here: Databricks leaves MANAGE out of
+// it, so its holder still reads a partial privilege list.
+// https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges
+var managePrivilege = []string{privilegeManage}
+
+// errSecurableGone reports that the securable a trust read addressed no longer
+// exists. Only a level that names its gone codes can raise it.
+var errSecurableGone = errors.New("securable no longer exists")
+
+// holdsPrivilegeOn reports whether the connector holds one of wanted. A refusal leaves it unproven. The read is not cached.
+//
+// goneCodes are the error_code values that prove the securable is gone. A level
+// that names them can tell an absence from a routing miss, so a 404 carrying one
+// reports errSecurableGone and any other 404 refuses the read instead of passing
+// as unproven. A level that names none keeps every 404 unproven, because it has
+// no way to tell the two apart.
+func holdsPrivilegeOn(
+ ctx context.Context,
+ client *databricks.Client,
+ trust securableTrust,
+ securableType, fullName string,
+ wanted []string,
+ goneCodes []string,
+ annos *annotations.Annotations,
+) (bool, error) {
+ if trust.ownPrincipal == "" || trust.workspace == "" {
+ return false, nil
+ }
+
+ var holds bool
+ rateLimit, err := client.ForEachUncachedPermissionsPage(ctx, trust.workspace, securableType, fullName, trust.ownPrincipal,
+ func(page []databricks.PrivilegeAssignment) (bool, error) {
+ for _, assignment := range page {
+ for _, privilege := range assignment.Privileges {
+ if slices.Contains(wanted, privilege) {
+ holds = true
+
+ return true, nil
+ }
+ }
+ }
+
+ return false, nil
+ })
+ noteRateLimit(annos, rateLimit)
+ if err != nil {
+ if databricks.IsSecurableGone(err, goneCodes...) {
+ return false, errSecurableGone
+ }
+ if len(goneCodes) > 0 && apiStatus(err) == http.StatusNotFound {
+ return false, refuseUnreadable(fmt.Sprintf(
+ "databricks-connector: failed to read the connector's own privileges on %s %s", securableType, fullName), err)
+ }
+ if !deniesTrust(err) {
+ return false, fmt.Errorf("databricks-connector: failed to read the connector's own privileges on %s %s: %w", securableType, fullName, err)
+ }
+ ctxzap.Extract(ctx).Debug("databricks-connector: the connector's own privileges on the securable cannot be read, so they stay unproven",
+ zap.String("securable_type", securableType),
+ zap.String("securable", fullName),
+ zap.Error(err))
+
+ return false, nil
+ }
+
+ return holds, nil
+}
+
+// errTrustRead404 marks a trust read that answered 404 and still has to be
+// classified by the level, which is the only holder of the codes that prove
+// the securable is gone.
+var errTrustRead404 = errors.New("trust read answered 404")
+
+// holdsEffectivePrivilegeOn reports whether the connector holds one of wanted on
+// the securable or any parent, which one uncached read answers. A refusal leaves
+// it unproven, and a 404 is left to the level, which owns the gone codes.
+func holdsEffectivePrivilegeOn(
+ ctx context.Context,
+ client *databricks.Client,
+ trust securableTrust,
+ securableType, fullName string,
+ wanted []string,
+ annos *annotations.Annotations,
+) (bool, error) {
+ if trust.ownPrincipal == "" || trust.workspace == "" {
+ return false, nil
+ }
+
+ var holds bool
+ rateLimit, err := client.ForEachUncachedEffectivePermissionsPage(ctx, trust.workspace, securableType, fullName, trust.ownPrincipal,
+ func(page []databricks.EffectivePrivilegeAssignment) (bool, error) {
+ // The walk stops on the first page that holds one, so this never
+ // overwrites a hit with a later miss.
+ holds = slices.ContainsFunc(page, func(assignment databricks.EffectivePrivilegeAssignment) bool {
+ return assignment.HoldsAny(wanted)
+ })
+
+ return holds, nil
+ })
+ noteRateLimit(annos, rateLimit)
+ if err != nil {
+ if apiStatus(err) == http.StatusNotFound {
+ return false, fmt.Errorf("%w: %w", errTrustRead404, err)
+ }
+ if !deniesTrust(err) {
+ return false, fmt.Errorf(
+ "databricks-connector: failed to read the connector's own effective privileges on %s %s: %w", securableType, fullName, err)
+ }
+ ctxzap.Extract(ctx).Debug(
+ "databricks-connector: the connector's own effective privileges on the securable cannot be read, so they stay unproven",
+ zap.String("securable_type", securableType),
+ zap.String("securable", fullName),
+ zap.Error(err))
+
+ return false, nil
+ }
+
+ return holds, nil
+}
+
// assignmentListError explains a failed read of the workspaces a metastore is
// assigned to, which decides which workspaces its securables are read through.
// A 404 is not an empty assignment list: the SDK would skip the child List and
@@ -481,17 +601,32 @@ func assignmentListError(metastoreID string, err error) error {
fmt.Sprintf("databricks-connector: failed to list the workspaces assigned to metastore %s", metastoreID), err)
}
-// workspaceForCatalog returns the first in-scope workspace whose catalog listing
-// contains catalogName. None listing it is an error, never an absence: a catalog
-// bound to a workspace outside the sync, or one the connector lost USE_CATALOG
-// on, is not listed either and still exists. Reporting it as gone would delete
-// its subtree on a sync, and confirm a revoke that never happened.
+// catalogAccept decides whether a workspace that serves the catalog is the one
+// to route through. It runs only after catalogThrough answered, so a gone answer
+// from it is the catalog disappearing between two reads rather than a workspace
+// the catalog is not bound to. A nil predicate accepts the first workspace that
+// serves the catalog.
+type catalogAccept func(ctx context.Context, workspace databricks.Workspace, catalog *databricks.Catalog) (bool, error)
+
+// errCatalogNotAccepted reports that the catalog was served but no workspace
+// passed the caller's acceptance check.
+var errCatalogNotAccepted = errors.New("no workspace serving the catalog passed the acceptance check")
+
+// workspaceForCatalog returns the workspace to route the catalog through and the
+// catalog as that workspace read it. No workspace serving it is an error, never
+// an absence: a catalog bound to a workspace outside the sync, or one the
+// connector lost USE_CATALOG on, is not served either and still exists, so
+// reporting it as gone would delete its subtree and confirm a revoke that never
+// happened. It reports errCatalogGone only when every answer said gone and none
+// refused, and errCatalogNotAccepted when the catalog was served but accept
+// turned every workspace down.
func workspaceForCatalog(
ctx context.Context,
client *databricks.Client,
metastoreID, catalogName string,
usable []databricks.Workspace,
probe catalogProbe,
+ accept catalogAccept,
annos *annotations.Annotations,
) (*databricks.Workspace, *databricks.Catalog, error) {
lastDeny := probe.deny
@@ -502,6 +637,7 @@ func workspaceForCatalog(
if probe.workspace != "" && !probe.gone {
allGone = false
}
+ var served, namedGone bool
for _, workspace := range usable {
if workspace.DeploymentName == probe.workspace {
continue
@@ -518,14 +654,36 @@ func workspaceForCatalog(
}
return nil, nil, err
}
- if catalog != nil {
+ if catalog == nil {
+ allGone = false
+ continue
+ }
+ if accept == nil {
return &workspace, catalog, nil
}
+ // The reads run in order, so a workspace serving the catalog now supersedes
+ // a gone answer an earlier acceptance check gave.
+ namedGone = false
+ ok, err := accept(ctx, workspace, catalog)
+ if err != nil {
+ if errors.Is(err, errCatalogGone) {
+ namedGone = true
+ continue
+ }
+ return nil, nil, err
+ }
allGone = false
+ served = true
+ if ok {
+ return &workspace, catalog, nil
+ }
}
- if allGone {
+ if allGone || (namedGone && lastDeny == nil) {
return nil, nil, errCatalogGone
}
+ if served {
+ return nil, nil, errCatalogNotAccepted
+ }
msg := fmt.Sprintf("databricks-connector: no workspace in sync scope lists catalog %s of metastore %s, so whether it still exists is unknown",
catalogName, metastoreID)
diff --git a/pkg/connector/raw_id_test.go b/pkg/connector/raw_id_test.go
index 536e10f0..d0552e9d 100644
--- a/pkg/connector/raw_id_test.go
+++ b/pkg/connector/raw_id_test.go
@@ -77,6 +77,13 @@ func TestResourcesHaveRawId(t *testing.T) {
&v2.ResourceId{ResourceType: metastoreResourceType.Id, Resource: "ms1"}, catalogRoute{})),
"ms1::cat",
},
+ {
+ // The schema extends its catalog's id with the dotted full name.
+ "schema",
+ build(schemaResource(&databricks.Schema{Name: "sch"}, "ms1", "cat",
+ &v2.ResourceId{ResourceType: catalogResourceType.Id, Resource: "ms1::cat"}, schemaRoute{})),
+ "ms1::cat.sch",
+ },
}
for _, tc := range cases {
diff --git a/pkg/connector/resource_types.go b/pkg/connector/resource_types.go
index 22c94445..fab13dfd 100644
--- a/pkg/connector/resource_types.go
+++ b/pkg/connector/resource_types.go
@@ -17,6 +17,7 @@ const (
permissionAccountAdmin = "Account admin"
permissionWorkspaceAdmin = "Workspace admin"
permissionUseCatalog = "USE_CATALOG"
+ permissionUseSchema = "USE_SCHEMA"
)
var securableScopes = []string{
@@ -93,4 +94,12 @@ var (
Traits: []v2.ResourceType_Trait{v2.ResourceType_TRAIT_APP},
Annotations: annotationsForStaticSecurableResourceType(securablePermissions(permissionUseCatalog)...),
}
+
+ schemaResourceType = &v2.ResourceType{
+ Id: "schema",
+ DisplayName: "Schema",
+ Traits: []v2.ResourceType_Trait{v2.ResourceType_TRAIT_APP},
+ Annotations: annotationsForStaticSecurableResourceType(
+ securablePermissions(permissionUseCatalog, permissionUseSchema, privilegeManage)...),
+ }
)
diff --git a/pkg/connector/schema.go b/pkg/connector/schema.go
new file mode 100644
index 00000000..483e4778
--- /dev/null
+++ b/pkg/connector/schema.go
@@ -0,0 +1,574 @@
+package connector
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/conductorone/baton-databricks/pkg/databricks"
+ v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2"
+ "github.com/conductorone/baton-sdk/pkg/annotations"
+ "github.com/conductorone/baton-sdk/pkg/connectorbuilder"
+ "github.com/conductorone/baton-sdk/pkg/pagination"
+ ent "github.com/conductorone/baton-sdk/pkg/types/entitlement"
+ rs "github.com/conductorone/baton-sdk/pkg/types/resource"
+ "github.com/conductorone/baton-sdk/pkg/uhttp"
+ "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap"
+ "go.uber.org/zap"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+)
+
+var _ connectorbuilder.StaticEntitlementSyncerV2 = (*schemaBuilder)(nil)
+
+const (
+ securableTypeSchema = "SCHEMA"
+
+ // informationSchema is the read-only schema Databricks puts in every catalog.
+ // Its privileges are not grantable, so it is left out of the sync.
+ informationSchema = "information_schema"
+
+ // schemaNameSeparator joins the catalog and the schema into the dotted full
+ // name the permissions endpoint addresses a schema by. Databricks rejects a
+ // name holding a period, so splitting on it is unambiguous.
+ schemaNameSeparator = "."
+
+ profileKeySchemaName = "schema_name"
+
+ // profileKeyCatalogOwner carries the parent catalog's owner, which is one of
+ // the things that makes a schema's privilege read complete. Grants is handed
+ // only the schema, so List writes it down.
+ profileKeyCatalogOwner = "catalog_owner"
+
+ schemaWriteRemedy = "the connector must own the metastore, the parent catalog or the schema, or hold MANAGE on the schema or the parent catalog"
+
+ schemaTrustRemedy = "the connector's service principal must own the metastore, the parent catalog or the schema, hold MANAGE on the schema or " +
+ "on the parent catalog, or be assigned Admin directly on the workspace whose admins group owns the parent catalog"
+
+ schemaListRemedy = "the connector's service principal must own the metastore or the catalog, hold MANAGE, USE_SCHEMA or ALL_PRIVILEGES on the catalog, " +
+ "or be assigned Admin directly on the workspace whose admins group owns the catalog"
+
+ errorCodeSchemaGone = "SCHEMA_DOES_NOT_EXIST"
+)
+
+// schemaPrivileges is the catalog set minus the three that stop at the catalog.
+// https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges
+var schemaPrivileges = slices.DeleteFunc(slices.Clone(catalogPrivileges), func(privilege string) bool {
+ return slices.Contains([]string{"BROWSE", "CREATE_SCHEMA", "USE_CATALOG"}, privilege)
+})
+
+// schemaListingPrivileges each make ListSchemas return every schema in the
+// catalog. A complete listing does not need MANAGE: USE_SCHEMA and ALL_PRIVILEGES
+// carry it too, and neither of those makes a privilege read complete.
+var schemaListingPrivileges = []string{privilegeManage, "USE_SCHEMA", "ALL_PRIVILEGES"}
+
+var schemaLevel = securableLevel{
+ securableType: databricks.SecurableSchema,
+ noun: "schema",
+ privileges: schemaPrivileges,
+ writeRemedy: schemaWriteRemedy,
+ trustRemedy: schemaTrustRemedy,
+ permissionsName: schemaPermissionsName,
+ trusts: schemaGrantsAreTrustworthy,
+ // A permissions read names the leaf; the GET and the listings name the parent.
+ goneErrorCodes: []string{errorCodeSchemaGone, errorCodeCatalogGone},
+}
+
+type schemaBuilder struct {
+ securableOps
+ workspaces map[string]struct{}
+}
+
+func newSchemaBuilder(client *databricks.Client, clientID string, workspaces map[string]struct{}, sync syncPrincipals) *schemaBuilder {
+ return &schemaBuilder{
+ securableOps: securableOps{client: client, clientID: clientID, sync: sync, level: schemaLevel},
+ workspaces: workspaces,
+ }
+}
+
+func (b *schemaBuilder) ResourceType(_ context.Context) *v2.ResourceType {
+ return schemaResourceType
+}
+
+func schemaResourceID(metastoreID, catalogName, name string) string {
+ return metastoreID + securableKeySeparator + catalogName + schemaNameSeparator + name
+}
+
+func parseSchemaID(resourceID string) (string, string, string, error) {
+ metastoreID, fullName, ok := strings.Cut(resourceID, securableKeySeparator)
+ if !ok {
+ return "", "", "", status.Errorf(codes.InvalidArgument, "databricks-connector: invalid schema resource id %q", resourceID)
+ }
+
+ catalogName, name, ok := strings.Cut(fullName, schemaNameSeparator)
+ if !ok || metastoreID == "" || catalogName == "" || name == "" {
+ return "", "", "", status.Errorf(codes.InvalidArgument, "databricks-connector: invalid schema resource id %q", resourceID)
+ }
+
+ return metastoreID, catalogName, name, nil
+}
+
+// schemaPermissionsName: the permissions endpoint addresses a schema by its
+// dotted full name. The metastore is carried by the host.
+func schemaPermissionsName(resourceID string) (string, error) {
+ _, catalogName, name, err := parseSchemaID(resourceID)
+ if err != nil {
+ return "", err
+ }
+
+ return catalogName + schemaNameSeparator + name, nil
+}
+
+func schemaResource(
+ schema *databricks.Schema,
+ metastoreID, catalogName string,
+ parent *v2.ResourceId,
+ route schemaRoute,
+) (*v2.Resource, error) {
+ fullName := catalogName + schemaNameSeparator + schema.Name
+ profile := map[string]any{
+ profileKeyMetastoreID: metastoreID,
+ profileKeyMetastoreOwner: route.MetastoreOwner,
+ profileKeyFullName: fullName,
+ profileKeyCatalogName: catalogName,
+ profileKeyCatalogOwner: route.CatalogOwner,
+ profileKeySchemaName: schema.Name,
+ profileKeyOwner: schema.Owner,
+ profileKeySecurableType: securableTypeSchema,
+ profileKeyWorkspace: route.Workspace,
+ profileKeyWorkspaceID: route.WorkspaceID,
+ profileKeyWorkspaceName: route.WorkspaceName,
+ }
+
+ resourceID := schemaResourceID(metastoreID, catalogName, schema.Name)
+
+ // The full name is the display name: main.sales and finance.sales would
+ // otherwise be two rows both reading "sales" in C1.
+ return rs.NewAppResource(
+ fullName,
+ schemaResourceType,
+ resourceID,
+ nil,
+ rs.WithResourceProfile(profile),
+ rs.WithParentResourceID(parent),
+ rs.WithAnnotation(&v2.RawId{Id: resourceID}),
+ )
+}
+
+// schemaRoute is the workspace a catalog's schemas are listed through, carried
+// in the page token so later pages neither re-resolve it nor prove the listing
+// complete again. It is the catalog's route plus the catalog's owner, which a
+// schema's trust check needs and a catalog's does not.
+type schemaRoute struct {
+ catalogRoute
+ CatalogOwner string `json:"c"`
+}
+
+func schemaRouteOn(route catalogRoute, catalog *databricks.Catalog) schemaRoute {
+ return schemaRoute{catalogRoute: route, CatalogOwner: catalog.Owner}
+}
+
+// List pages a catalog's schemas through a workspace that can see every schema.
+// Databricks answers a caller without catalog-wide visibility with a short list
+// at 200, so a listing that cannot be proved complete stops the sync.
+func (b *schemaBuilder) List(ctx context.Context, parentResourceID *v2.ResourceId, attr rs.SyncOpAttrs) ([]*v2.Resource, *rs.SyncOpResults, error) {
+ ctx = context.WithValue(ctx, syncSessionKey{}, attr.Session)
+ if parentResourceID.GetResourceType() != catalogResourceType.Id {
+ return nil, nil, nil
+ }
+
+ metastoreID, catalogName, err := parseCatalogID(parentResourceID.GetResource())
+ if err != nil {
+ return nil, nil, err
+ }
+
+ annos := annotations.Annotations{}
+ bag := &pagination.Bag{}
+ if err := bag.Unmarshal(attr.PageToken.Token); err != nil {
+ return nil, nil, status.Errorf(codes.InvalidArgument, "databricks-connector: invalid schema page token: %v", err)
+ }
+
+ if bag.Current() == nil {
+ if err := b.pushRoute(ctx, metastoreID, catalogName, bag, &annos); err != nil {
+ return nil, &rs.SyncOpResults{Annotations: annos}, err
+ }
+ if bag.Current() == nil {
+ ctxzap.Extract(ctx).Debug("databricks-connector: no workspace in sync scope lists the catalog; listing no schemas",
+ zap.String("metastore", metastoreID),
+ zap.String("catalog", catalogName))
+
+ return nil, &rs.SyncOpResults{Annotations: annos}, nil
+ }
+ }
+
+ var route schemaRoute
+ if err := json.Unmarshal([]byte(bag.ResourceID()), &route); err != nil {
+ return nil, nil, status.Errorf(codes.Internal, "databricks-connector: invalid schema page token: %v", err)
+ }
+
+ schemas, next, rateLimit, err := b.client.ListSchemas(ctx, route.Workspace, catalogName, bag.PageToken(), ResourcesPageSize)
+ noteRateLimit(&annos, rateLimit)
+ if err != nil {
+ return nil, &rs.SyncOpResults{Annotations: annos}, schemaListingError(catalogName, route.Workspace, err)
+ }
+
+ var rv []*v2.Resource
+ for _, schema := range schemas {
+ if schema.Name == "" || schema.Name == informationSchema {
+ continue
+ }
+
+ built, err := schemaResource(&schema, metastoreID, catalogName, parentResourceID, route)
+ if err != nil {
+ return nil, &rs.SyncOpResults{Annotations: annos}, fmt.Errorf(
+ "databricks-connector: failed to build the resource for schema %s.%s: %w", catalogName, schema.Name, err)
+ }
+ rv = append(rv, built)
+ }
+
+ if next != "" && next == bag.PageToken() {
+ return nil, &rs.SyncOpResults{Annotations: annos}, status.Errorf(codes.Internal,
+ "databricks-connector: listing the schemas of catalog %s repeated page token %q", catalogName, next)
+ }
+
+ nextToken, err := bag.NextToken(next)
+ if err != nil {
+ return nil, &rs.SyncOpResults{Annotations: annos}, err
+ }
+
+ return rv, &rs.SyncOpResults{Annotations: annos, NextPageToken: nextToken}, nil
+}
+
+// pushRoute records the first running in-scope workspace that both lists the
+// catalog and can read every schema, and refuses when none can: returning no
+// schemas would make C1 delete them.
+func (b *schemaBuilder) pushRoute(
+ ctx context.Context,
+ metastoreID, catalogName string,
+ bag *pagination.Bag,
+ annos *annotations.Annotations,
+) error {
+ scope, err := scopedWorkspaces(ctx, b.client, b.workspaces, annos)
+ if err != nil {
+ return err
+ }
+
+ usable, inScope, err := scope.attached(ctx, b.client, metastoreID, annos)
+ if err != nil {
+ return assignmentListError(metastoreID, err)
+ }
+ if len(usable) == 0 {
+ if inScope {
+ return status.Errorf(codes.FailedPrecondition,
+ "databricks-connector: metastore %s has no running workspace in sync scope", metastoreID)
+ }
+
+ return nil
+ }
+
+ owner, err := metastoreOwner(ctx, b.client, metastoreID, annos)
+ // The metastore syncer removes the parent in the same sync.
+ if errors.Is(err, errMetastoreGone) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+
+ accept := func(ctx context.Context, workspace databricks.Workspace, catalog *databricks.Catalog) (bool, error) {
+ return schemaListingIsComplete(ctx, b.client, securableTrust{
+ ownPrincipal: b.clientID,
+ metastoreOwner: owner,
+ parentOwner: catalog.Owner,
+ fullName: catalogName,
+ workspace: workspace.DeploymentName,
+ workspaceID: strconv.Itoa(workspace.ID),
+ }, annos)
+ }
+
+ workspace, catalog, err := workspaceForCatalog(ctx, b.client, metastoreID, catalogName, usable, catalogProbe{}, accept, annos)
+ if err != nil {
+ switch {
+ // A catalog proved gone holds no schemas, and the catalog syncer drops the
+ // parent in the same sync.
+ case errors.Is(err, errCatalogGone):
+ return nil
+ case errors.Is(err, errCatalogNotAccepted):
+ return status.Errorf(codes.PermissionDenied,
+ "databricks-connector: cannot list every schema in catalog %s; %s",
+ catalogName, schemaListRemedy)
+ default:
+ return err
+ }
+ }
+
+ encoded, err := json.Marshal(schemaRouteOn(catalogRoute{
+ Workspace: workspace.DeploymentName,
+ WorkspaceID: strconv.Itoa(workspace.ID),
+ WorkspaceName: workspace.Name,
+ MetastoreOwner: owner,
+ }, catalog))
+ if err != nil {
+ return err
+ }
+ bag.Push(pagination.PageState{ResourceTypeID: schemaResourceType.Id, ResourceID: string(encoded)})
+
+ return nil
+}
+
+// schemaListingError returns NotFound only when Databricks names the missing
+// catalog; any other refusal leaves the schema listing unknown.
+func schemaListingError(catalogName, workspace string, err error) error {
+ if databricks.IsSecurableGone(err, errorCodeCatalogGone) {
+ return uhttp.WrapErrors(codes.NotFound,
+ fmt.Sprintf("databricks-connector: catalog %s no longer exists", catalogName), err)
+ }
+
+ switch apiStatus(err) {
+ case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound:
+ return uhttp.WrapErrors(codes.FailedPrecondition,
+ fmt.Sprintf("databricks-connector: the schemas of catalog %s cannot be listed through workspace %s, "+
+ "so which schemas are in scope is unknown; %s, or leave that workspace out with workspaces or databricks-exclude-workspaces",
+ catalogName, workspace, schemaListRemedy),
+ err)
+ }
+
+ return fmt.Errorf("databricks-connector: failed to list the schemas of catalog %s through workspace %s: %w",
+ catalogName, workspace, err)
+}
+
+// schemaListingIsComplete is true when ListSchemas returns every schema of the
+// catalog: ownership, a direct Admin of the owning admins group's workspace,
+// MANAGE, USE_SCHEMA or ALL_PRIVILEGES each settle it. It reports errCatalogGone
+// when Databricks names the catalog missing.
+func schemaListingIsComplete(
+ ctx context.Context,
+ client *databricks.Client,
+ trust securableTrust,
+ annos *annotations.Annotations,
+) (bool, error) {
+ // An owner sees everything below it, and the metastore's owner is its admin.
+ if ownsPrincipal(trust.ownPrincipal, trust.metastoreOwner) || ownsPrincipal(trust.ownPrincipal, trust.parentOwner) {
+ return true, nil
+ }
+
+ // The workspace admins group acts as the owner for a direct Admin of its workspace.
+ if ownerWorkspaceID, ok := catalogAdminWorkspaceID(trust.parentOwner); ok {
+ admin, err := isWorkspaceAdmin(ctx, client, trust.ownPrincipal, ownerWorkspaceID, annos)
+ if err != nil || admin {
+ return admin, err
+ }
+ }
+
+ complete, err := holdsPrivilegeOn(ctx, client, trust, databricks.SecurableCatalog, trust.fullName,
+ schemaListingPrivileges, []string{errorCodeCatalogGone}, annos)
+ if errors.Is(err, errSecurableGone) {
+ return false, errCatalogGone
+ }
+
+ return complete, err
+}
+
+// schemaGrantsAreTrustworthy is true for an owner of the schema, catalog, or
+// metastore, a holder of MANAGE on the schema or catalog, or a direct Admin
+// when the workspace admins group owns the catalog.
+func schemaGrantsAreTrustworthy(
+ ctx context.Context,
+ client *databricks.Client,
+ trust securableTrust,
+ annos *annotations.Annotations,
+) (bool, error) {
+ // An owner holds every privilege implicitly, which is never reported as a grant.
+ if ownsPrincipal(trust.ownPrincipal, trust.metastoreOwner) ||
+ ownsPrincipal(trust.ownPrincipal, trust.parentOwner) ||
+ ownsPrincipal(trust.ownPrincipal, trust.owner) {
+ return true, nil
+ }
+
+ if ownerWorkspaceID, ok := catalogAdminWorkspaceID(trust.parentOwner); ok {
+ admin, err := isWorkspaceAdmin(ctx, client, trust.ownPrincipal, ownerWorkspaceID, annos)
+ if err != nil || admin {
+ return admin, err
+ }
+ }
+
+ // One effective read reports MANAGE on the schema and on the catalog above it.
+ return holdsEffectivePrivilegeOn(ctx, client, trust, databricks.SecurableSchema, trust.fullName, managePrivilege, annos)
+}
+
+func (b *schemaBuilder) StaticEntitlements(_ context.Context, _ rs.SyncOpAttrs) ([]*v2.Entitlement, *rs.SyncOpResults, error) {
+ grantable := ent.WithGrantableTo(userResourceType, groupResourceType, servicePrincipalResourceType)
+ rv := make([]*v2.Entitlement, 0, len(schemaPrivileges)+1)
+ for _, privilege := range schemaPrivileges {
+ rv = append(rv, ent.NewPermissionEntitlement(nil, privilege,
+ grantable,
+ ent.WithDescription(fmt.Sprintf("%s privilege on a schema in Databricks", privilege)),
+ ))
+ }
+
+ rv = append(rv, ent.NewOwnershipEntitlement(nil, ownerEntitlement,
+ ent.WithDescription("Owns a schema in Databricks"),
+ ))
+
+ return rv, nil, nil
+}
+
+func (b *schemaBuilder) Entitlements(context.Context, *v2.Resource, rs.SyncOpAttrs) ([]*v2.Entitlement, *rs.SyncOpResults, error) {
+ return nil, nil, nil
+}
+
+// Grants carries the sync session so the workspace-Admin check behind the trust
+// rule is read once per workspace per sync rather than once per schema.
+func (b *schemaBuilder) Grants(ctx context.Context, resource *v2.Resource, attr rs.SyncOpAttrs) ([]*v2.Grant, *rs.SyncOpResults, error) {
+ ctx = context.WithValue(ctx, syncSessionKey{}, attr.Session)
+
+ return b.syncGrants(ctx, resource, attr)
+}
+
+func (b *schemaBuilder) Grant(ctx context.Context, principal *v2.Resource, entitlement *v2.Entitlement) (annotations.Annotations, error) {
+ ctx = databricks.WithoutCache(ctx)
+ annos := annotations.Annotations{}
+ routed, err := b.entitlementOnLiveRoute(ctx, entitlement, &annos)
+ if err != nil {
+ if isSecurableGoneSentinel(err) {
+ return annos, status.Errorf(codes.NotFound, "databricks-connector: schema %s no longer exists",
+ entitlement.GetResource().GetId().GetResource())
+ }
+
+ return annos, err
+ }
+
+ return b.grant(ctx, principal.GetId(), routed)
+}
+
+func (b *schemaBuilder) Revoke(ctx context.Context, revoked *v2.Grant) (annotations.Annotations, error) {
+ ctx = databricks.WithoutCache(ctx)
+ annos := annotations.Annotations{}
+ routed, err := b.entitlementOnLiveRoute(ctx, revoked.GetEntitlement(), &annos)
+ if err != nil {
+ if isSecurableGoneSentinel(err) {
+ annos.Update(&v2.GrantAlreadyRevoked{})
+
+ return annos, nil
+ }
+
+ return annos, err
+ }
+
+ return b.revoke(ctx, revoked.GetPrincipal().GetId(), routed)
+}
+
+// entitlementOnLiveRoute rebuilds the entitlement's schema from what Databricks
+// reports now: the three owners the trust check short-circuits on ride on the
+// profile, where they can be hours old, so a transfer away from the connector
+// would otherwise let a truncated privilege list decide the write.
+func (b *schemaBuilder) entitlementOnLiveRoute(
+ ctx context.Context,
+ entitlement *v2.Entitlement,
+ annos *annotations.Annotations,
+) (*v2.Entitlement, error) {
+ resource := entitlement.GetResource()
+ metastoreID, catalogName, schemaName, err := parseSchemaID(resource.GetId().GetResource())
+ if err != nil {
+ return nil, err
+ }
+
+ owner, err := metastoreOwner(ctx, b.client, metastoreID, annos)
+ if err != nil {
+ return nil, err
+ }
+
+ route, catalog, err := b.liveCatalogRoute(ctx, resource, metastoreID, catalogName, owner, annos)
+ if err != nil {
+ return nil, err
+ }
+
+ fullName := catalogName + schemaNameSeparator + schemaName
+ schema, rateLimit, err := b.client.GetSchema(ctx, route.Workspace, fullName)
+ noteRateLimit(annos, rateLimit)
+ if err != nil {
+ // Only Databricks naming the securable proves it gone; an unbound workspace
+ // refuses with 403, and reading that as an absence would report a false revoke.
+ if databricks.IsSecurableGone(err, errorCodeSchemaGone, errorCodeCatalogGone) {
+ return nil, errSecurableGone
+ }
+
+ return nil, refuseUnreadable(fmt.Sprintf(
+ "databricks-connector: failed to read schema %s through workspace %s", fullName, route.Workspace), err)
+ }
+
+ route.CatalogOwner = catalog.Owner
+ routed, err := schemaResource(schema, metastoreID, catalogName, resource.GetParentResourceId(), route)
+ if err != nil {
+ return nil, err
+ }
+
+ return entitlementOnResource(entitlement, routed)
+}
+
+// liveCatalogRoute picks the workspace the write goes through: the recorded one
+// when this sync still admits it and it still serves the catalog, otherwise the
+// first running in-scope workspace that does. A catalog no workspace serves is
+// not proof of deletion, so that case is settled against the metastore's
+// unbound listing.
+func (b *schemaBuilder) liveCatalogRoute(
+ ctx context.Context,
+ resource *v2.Resource,
+ metastoreID, catalogName, metastoreOwner string,
+ annos *annotations.Annotations,
+) (schemaRoute, *databricks.Catalog, error) {
+ var probe catalogProbe
+ if route, ok := profileCatalogRoute(b.client, b.workspaces, resource, metastoreOwner); ok {
+ catalog, err := catalogThrough(ctx, b.client, route.Workspace, metastoreID, catalogName, annos)
+ switch {
+ case err == nil:
+ case errors.Is(err, errCatalogGone):
+ probe = catalogProbe{workspace: route.Workspace, gone: true}
+ case deniesTrust(err):
+ probe = catalogProbe{workspace: route.Workspace, deny: err}
+ }
+ switch {
+ case catalog != nil && catalog.MetastoreID == metastoreID:
+ return schemaRouteOn(route, catalog), catalog, nil
+ case catalog != nil:
+ case err == nil:
+ probe = catalogProbe{workspace: route.Workspace}
+ }
+ }
+
+ scope, err := scopedWorkspaces(ctx, b.client, b.workspaces, annos)
+ if err != nil {
+ return schemaRoute{}, nil, err
+ }
+ usable, _, err := scope.attached(ctx, b.client, metastoreID, annos)
+ if err != nil {
+ return schemaRoute{}, nil, assignmentListError(metastoreID, err)
+ }
+ if len(usable) == 0 {
+ return schemaRoute{}, nil, status.Errorf(codes.FailedPrecondition,
+ "databricks-connector: metastore %s has no running workspace in sync scope to write catalog %s through",
+ metastoreID, catalogName)
+ }
+
+ workspace, catalog, err := workspaceForCatalog(ctx, b.client, metastoreID, catalogName, usable, probe, nil, annos)
+ if err != nil {
+ if errors.Is(err, errCatalogGone) {
+ return schemaRoute{}, nil, confirmCatalogGone(
+ ctx, b.client, b.clientID, metastoreID, catalogName, usable[0].DeploymentName, metastoreOwner, annos)
+ }
+
+ return schemaRoute{}, nil, err
+ }
+
+ return schemaRouteOn(catalogRoute{
+ Workspace: workspace.DeploymentName,
+ WorkspaceID: strconv.Itoa(workspace.ID),
+ WorkspaceName: workspace.Name,
+ MetastoreOwner: metastoreOwner,
+ }, catalog), catalog, nil
+}
diff --git a/pkg/connector/securable_helpers.go b/pkg/connector/securable_helpers.go
index 888ddcd2..f2c51513 100644
--- a/pkg/connector/securable_helpers.go
+++ b/pkg/connector/securable_helpers.go
@@ -88,6 +88,8 @@ type securableTrust struct {
// metastoreOwner is empty on a metastore, whose own owner is in owner.
metastoreOwner string
+ parentOwner string
+
fullName string
workspace string
workspaceID string
@@ -109,17 +111,19 @@ func ensureGrantsAreTrustworthy(
owner, _ := rs.GetProfileStringValue(profile, profileKeyOwner)
metastoreOwner, _ := rs.GetProfileStringValue(profile, profileKeyMetastoreOwner)
workspaceID, _ := rs.GetProfileStringValue(profile, profileKeyWorkspaceID)
+ parentOwner, _ := rs.GetProfileStringValue(profile, profileKeyCatalogOwner)
trustworthy, err := level.trusts(ctx, client, securableTrust{
ownPrincipal: clientID,
owner: owner,
metastoreOwner: metastoreOwner,
+ parentOwner: parentOwner,
fullName: fullName,
workspace: workspace,
workspaceID: workspaceID,
}, annos)
if err != nil {
- return err
+ return trustReadError(level, fullName, workspace, err)
}
if !trustworthy {
return status.Errorf(codes.PermissionDenied,
@@ -130,6 +134,22 @@ func ensureGrantsAreTrustworthy(
return nil
}
+// trustReadError classifies the 404 a trust read left for the level. A proven
+// absence reports errSecurableGone; an unproven one is refused, because read as
+// an empty result C1 deletes everything the securable held.
+func trustReadError(level securableLevel, fullName, workspace string, err error) error {
+ if !errors.Is(err, errTrustRead404) {
+ return err
+ }
+ if databricks.IsSecurableGone(err, level.goneErrorCodes...) {
+ return errSecurableGone
+ }
+
+ return refuseUnreadable(fmt.Sprintf(
+ "databricks-connector: cannot read whether every privilege on %s %s is visible through workspace %s",
+ level.noun, fullName, workspace), err)
+}
+
// syncGrants emits the privileges held on one securable, plus its owner.
// The workspace comes off the profile the last List wrote: every Unity Catalog
// read is addressed to a workspace host, and resolving one here would be an
@@ -158,6 +178,12 @@ func (o securableOps) syncGrants(
pageToken := attr.PageToken.Token
if pageToken == "" && !level.listProvesTrust {
if err := ensureGrantsAreTrustworthy(ctx, client, clientID, level, resource, fullName, workspace, &annos); err != nil {
+ // The permissions read below answers a deletion the same way, so failing here
+ // would fail the sync on the earlier of two reads that see it.
+ if isSecurableGoneSentinel(err) {
+ return nil, &rs.SyncOpResults{Annotations: annos}, nil
+ }
+
return nil, &rs.SyncOpResults{Annotations: annos}, err
}
}
@@ -334,7 +360,7 @@ func (c change) updateError(verb string, err error) error {
// grant adds one privilege. Databricks no-ops a PATCH it cannot apply,
// so the pre-read decides GrantAlreadyExists and the echo is the only proof the
-// change landed.
+// change landed. A securable the trust check proves gone answers NotFound.
func (o securableOps) grant(
ctx context.Context,
principal *v2.ResourceId,
@@ -344,6 +370,11 @@ func (o securableOps) grant(
annos := annotations.Annotations{}
change, err := resolveChange(ctx, client, clientID, level, principal, entitlement, true, &annos)
if err != nil {
+ if isSecurableGoneSentinel(err) {
+ return annos, status.Errorf(codes.NotFound, "databricks-connector: %s %s no longer exists",
+ level.noun, entitlement.GetResource().GetId().GetResource())
+ }
+
return annos, err
}
@@ -381,7 +412,8 @@ func (o securableOps) grant(
// revoke removes one privilege. Databricks no-ops a privilege already
// absent, so the pre-read decides GrantAlreadyRevoked and the echo confirms the
-// removal.
+// removal. A securable the trust check proves gone holds nothing to revoke, so
+// it reports the grant already revoked rather than an unreadable securable.
func (o securableOps) revoke(
ctx context.Context,
principal *v2.ResourceId,
@@ -391,6 +423,12 @@ func (o securableOps) revoke(
annos := annotations.Annotations{}
change, err := resolveChange(ctx, client, clientID, level, principal, entitlement, false, &annos)
if err != nil {
+ if isSecurableGoneSentinel(err) {
+ annos.Update(&v2.GrantAlreadyRevoked{})
+
+ return annos, nil
+ }
+
return annos, err
}
@@ -442,3 +480,12 @@ func (o securableOps) revoke(
return annos, nil
}
+
+// isSecurableGoneSentinel reports whether err is one of the sentinels for a
+// securable Databricks named as missing: the shared one a trust read raises, or
+// a per-level one naming the securable itself or a parent. Callers that need
+// only the shared sentinel, because they translate it into a per-level one,
+// compare against errSecurableGone directly.
+func isSecurableGoneSentinel(err error) bool {
+ return errors.Is(err, errSecurableGone) || errors.Is(err, errCatalogGone) || errors.Is(err, errMetastoreGone)
+}
diff --git a/pkg/databricks/models.go b/pkg/databricks/models.go
index fc8edf26..c139c5a6 100644
--- a/pkg/databricks/models.go
+++ b/pkg/databricks/models.go
@@ -1,6 +1,9 @@
package databricks
-import "encoding/json"
+import (
+ "encoding/json"
+ "slices"
+)
type BaseResponse struct {
ID string `json:"id"`
@@ -182,6 +185,14 @@ type Catalog struct {
IsolationMode string `json:"isolation_mode"`
}
+type Schema struct {
+ Name string `json:"name"`
+ Owner string `json:"owner"`
+ // FullName is the dotted "catalog.schema" Databricks addresses the schema
+ // by. The listing fills it in; it is empty when the field is absent.
+ FullName string `json:"full_name"`
+}
+
type PrivilegeAssignment struct {
Principal string `json:"principal"`
PrincipalID json.Number `json:"principal_id"`
@@ -223,7 +234,42 @@ type catalogsResponse struct {
NextPageToken string `json:"next_page_token"`
}
+type schemasResponse struct {
+ Schemas []Schema `json:"schemas"`
+ NextPageToken string `json:"next_page_token"`
+}
+
type permissionsResponse struct {
PrivilegeAssignments []PrivilegeAssignment `json:"privilege_assignments"`
NextPageToken string `json:"next_page_token"`
}
+
+// EffectivePrivilege is one privilege an effective-permissions answer reports.
+// The inherited fields are empty when it is held on the securable itself, and
+// otherwise name the parent that grants it.
+type EffectivePrivilege struct {
+ Privilege string `json:"privilege"`
+ InheritedFromType string `json:"inherited_from_type,omitempty"`
+ InheritedFromName string `json:"inherited_from_name,omitempty"`
+}
+
+// EffectivePrivilegeAssignment is what one principal holds on a securable once
+// inheritance is applied. It carries no principal_id: this endpoint names a
+// principal only.
+type EffectivePrivilegeAssignment struct {
+ Principal string `json:"principal"`
+ Privileges []EffectivePrivilege `json:"privileges"`
+}
+
+// HoldsAny reports whether the assignment carries one of wanted, counting a
+// privilege a parent grants the same as one held directly.
+func (a EffectivePrivilegeAssignment) HoldsAny(wanted []string) bool {
+ return slices.ContainsFunc(a.Privileges, func(held EffectivePrivilege) bool {
+ return slices.Contains(wanted, held.Privilege)
+ })
+}
+
+type effectivePermissionsResponse struct {
+ PrivilegeAssignments []EffectivePrivilegeAssignment `json:"privilege_assignments"`
+ NextPageToken string `json:"next_page_token"`
+}
diff --git a/pkg/databricks/unity_catalog.go b/pkg/databricks/unity_catalog.go
index ea8703dc..cbe7b831 100644
--- a/pkg/databricks/unity_catalog.go
+++ b/pkg/databricks/unity_catalog.go
@@ -23,15 +23,24 @@ const (
// https://docs.databricks.com/api/workspace/catalogs/list
unityCatalogCatalogsEndpoint = "/api/2.1/unity-catalog/catalogs"
+ // https://docs.databricks.com/api/workspace/schemas/list
+ unityCatalogSchemasEndpoint = "/api/2.1/unity-catalog/schemas"
+
// GET https://docs.databricks.com/api/workspace/grants/get
// PATCH https://docs.databricks.com/api/workspace/grants/update
unityCatalogPermissionsEndpoint = "/api/2.1/unity-catalog/permissions"
+ // GET https://docs.databricks.com/api/workspace/grants/geteffective
+ // Same securable paths and same error codes as the permissions endpoint,
+ // plus the privileges a parent grants, naming where each comes from.
+ unityCatalogEffectivePermissionsEndpoint = "/api/2.1/unity-catalog/effective-permissions"
+
// Path segments for the permissions endpoint, not interchangeable with the
// uppercase securable_type a listed securable carries. A metastore is
// addressed by its UUID: its name is rejected.
SecurableMetastore = "metastore"
SecurableCatalog = "catalog"
+ SecurableSchema = "schema"
// The permissions endpoint rejects any max_results from 1 to 149 with a 400.
// Zero selects the paginated response that replaces the unpaginated form.
@@ -154,6 +163,70 @@ func (c *Client) GetCatalog(
return &res, ratelimitData, nil
}
+// ListSchemas (GET /api/2.1/unity-catalog/schemas?catalog_name=) reads one page of
+// the schemas of catalogName, through workspaceId, which is a deployment name.
+// Unlike the catalogs listing, this one pages, so the cursor is passed through.
+func (c *Client) ListSchemas(
+ ctx context.Context,
+ workspaceId, catalogName, pageToken string,
+ maxResults uint,
+) (
+ []Schema,
+ string,
+ *v2.RateLimitDescription,
+ error,
+) {
+ var res schemasResponse
+
+ u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogSchemasEndpoint)
+ ratelimitData, err := c.Get(ctx, u, &res, &unityCatalogVars{
+ catalogName: catalogName,
+ maxResults: &maxResults,
+ pageToken: pageToken,
+ })
+ if err != nil {
+ return nil, "", ratelimitData, nameWorkspace403Remedy(workspaceId,
+ fmt.Errorf("failed to list schemas in catalog %s: %w", catalogName, err))
+ }
+
+ return res.Schemas, res.NextPageToken, ratelimitData, nil
+}
+
+// GetSchema (GET /api/2.1/unity-catalog/schemas/{full_name}) reads one schema
+// through workspaceId, which is a deployment name. The full name is dotted,
+// and a deleted schema or catalog is named in error_code while a workspace the
+// catalog is not bound to answers 403.
+func (c *Client) GetSchema(
+ ctx context.Context,
+ workspaceId, fullName string,
+) (
+ *Schema,
+ *v2.RateLimitDescription,
+ error,
+) {
+ var res Schema
+
+ if fullName == "" {
+ return nil, nil, invalidArgument("schema full name is required")
+ }
+
+ u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogSchemasEndpoint, fullName)
+ if !addressesSecurable(u, "/"+fullName) {
+ return nil, nil, invalidArgument("cannot address schema %q: the name does not survive URL assembly", fullName)
+ }
+
+ ratelimitData, err := c.Get(ctx, u, &res)
+ if err != nil {
+ return nil, ratelimitData, nameWorkspace403Remedy(workspaceId, fmt.Errorf("failed to read schema %s: %w", fullName, err))
+ }
+
+ if res.FullName != "" && res.FullName != fullName {
+ return nil, ratelimitData, invalidArgument("asked Databricks for schema %q and it answered with %q", fullName, res.FullName)
+ }
+
+ return &res, ratelimitData, nil
+}
+
// ListPermissions (GET /api/2.1/unity-catalog/permissions/{securable_type}/{full_name}).
// The principal query filters effectively, not literally: an inherited assignment
// comes back naming the group it is inherited through, so a caller must read every
@@ -180,7 +253,7 @@ func (c *Client) listPermissions(
*v2.RateLimitDescription,
error,
) {
- u, err := c.permissionsUrl(workspaceId, securableType, fullName)
+ u, err := c.permissionsUrl(unityCatalogPermissionsEndpoint, workspaceId, securableType, fullName)
if err != nil {
return nil, "", nil, err
}
@@ -238,6 +311,56 @@ func (c *Client) ForEachUncachedPermissionsPage(
}, visit)
}
+// ForEachUncachedEffectivePermissionsPage walks the effective-permissions
+// endpoint past the cache, without retaining the pages. One read covers the
+// securable and every parent, so a caller does not walk the hierarchy itself.
+func (c *Client) ForEachUncachedEffectivePermissionsPage(
+ ctx context.Context,
+ workspaceId, securableType, fullName, principal string,
+ visit func([]EffectivePrivilegeAssignment) (bool, error),
+) (*v2.RateLimitDescription, error) {
+ return forEachPageFrom(ctx, "", func(pageToken string) ([]EffectivePrivilegeAssignment, string, *v2.RateLimitDescription, error) {
+ return c.listEffectivePermissions(ctx, workspaceId, securableType, fullName, principal, pageToken)
+ }, visit)
+}
+
+// listEffectivePermissions (GET /api/2.1/unity-catalog/effective-permissions/{type}/{full_name}).
+// The principal query filters effectively, not literally, so a caller reads every
+// row's privileges. Never cached: a stale page would answer for a changed grant.
+func (c *Client) listEffectivePermissions(
+ ctx context.Context,
+ workspaceId, securableType, fullName, principal, pageToken string,
+) (
+ []EffectivePrivilegeAssignment,
+ string,
+ *v2.RateLimitDescription,
+ error,
+) {
+ u, err := c.permissionsUrl(unityCatalogEffectivePermissionsEndpoint, workspaceId, securableType, fullName)
+ if err != nil {
+ return nil, "", nil, err
+ }
+
+ var res effectivePermissionsResponse
+
+ maxResults := permissionsMaxResults
+ ratelimitData, err := c.GetUncached(ctx, u, &res, &unityCatalogVars{
+ principal: principal,
+ maxResults: &maxResults,
+ pageToken: pageToken,
+ })
+ if err != nil {
+ if principal != "" {
+ return nil, "", ratelimitData, fmt.Errorf("failed to list effective permissions for principal %s on %s %s: %w",
+ principal, securableType, fullName, err)
+ }
+
+ return nil, "", ratelimitData, fmt.Errorf("failed to list effective permissions on %s %s: %w", securableType, fullName, err)
+ }
+
+ return res.PrivilegeAssignments, res.NextPageToken, ratelimitData, nil
+}
+
// UpdatePermissions (PATCH /api/2.1/unity-catalog/permissions/{securable_type}/{full_name}).
// Databricks no-ops a privilege already held or already absent, so the echoed
// assignments are the only confirmation the change landed — and that echo is
@@ -290,7 +413,7 @@ func (c *Client) updatePermissions(
}
}
- u, err := c.permissionsUrl(workspaceId, securableType, fullName)
+ u, err := c.permissionsUrl(unityCatalogPermissionsEndpoint, workspaceId, securableType, fullName)
if err != nil {
return nil, err
}
@@ -349,12 +472,12 @@ func (c *Client) updatePermissions(
// A name that does not survive URL assembly addresses a different securable,
// which on a PATCH writes someone else's permissions.
-func (c *Client) permissionsUrl(workspaceId, securableType, fullName string) (*url.URL, error) {
+func (c *Client) permissionsUrl(endpoint, workspaceId, securableType, fullName string) (*url.URL, error) {
if securableType == "" || fullName == "" {
return nil, invalidArgument("securable type and full name are required, got %q and %q", securableType, fullName)
}
- u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogPermissionsEndpoint, securableType, fullName)
+ u := c.workspaceUrl(workspaceId).JoinPath(endpoint, securableType, fullName)
if !addressesSecurable(u, "/"+securableType+"/"+fullName) {
return nil, invalidArgument("cannot address %s %q: the name does not survive URL assembly", securableType, fullName)
}
diff --git a/pkg/databricks/vars.go b/pkg/databricks/vars.go
index 7525e62a..6fac93ad 100644
--- a/pkg/databricks/vars.go
+++ b/pkg/databricks/vars.go
@@ -173,6 +173,7 @@ func NewNameVars(name string, etag string) *NameVars {
// while an absent max_results asks for the deprecated unpaginated response, so
// maxResults is a pointer: its presence is the signal.
type unityCatalogVars struct {
+ catalogName string
principal string
maxResults *uint
pageToken string
@@ -180,6 +181,10 @@ type unityCatalogVars struct {
}
func (v *unityCatalogVars) Apply(params *url.Values) {
+ if v.catalogName != "" {
+ params.Add("catalog_name", v.catalogName)
+ }
+
if v.principal != "" {
params.Add("principal", v.principal)
}