diff --git a/README.md b/README.md index c5f3cecd..4cfadb6b 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,9 @@ baton resources - Roles - Metastores - Catalogs (under their metastore) +- Schemas (under their catalog) +- Tables (under their schema) +- Volumes (under their schema) The connector fetches all resources from the account and every workspace the service principal can access. To limit the scope, pass a comma-separated list of @@ -95,9 +98,14 @@ other metastores and their grants from ConductorOne. Catalogs must also be visible through a listed workspace. A list that names no workspace on the account is rejected during credential validation, before any sync runs. -Metastores and catalogs are opt-in: each resource type stays off until enabled -for the connector in ConductorOne. Catalog sync uses the existing OAuth -credentials and configuration fields. +Metastores, catalogs, schemas, tables, and volumes are Unity Catalog securables +and are opt-in: each type stays off until it is enabled for the connector in +ConductorOne. They use the existing OAuth credentials and configuration fields. + +The opt-in is a ConductorOne setting, so it does not apply to the CLI. A local +run with no selection syncs every type, and it fails on a service principal that +cannot list every table and volume. Pass `--sync-resource-types` to limit it, for +example `--sync-resource-types account,user,group,metastore,catalog,schema`. ## Authentication @@ -238,6 +246,8 @@ account └── metastore └── catalog └── schema + ├── table + └── volume ``` A metastore exposes its privileges as entitlements (`CREATE_CATALOG`, @@ -285,11 +295,11 @@ or `databricks-exclude-workspaces`. ## Unity Catalog provisioning -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. +A privilege on a metastore, catalog, schema, table or volume 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 +If a securable becomes unreachable, provisioning must distinguish deletion from a workspace binding or visibility change. Requests can fail with `FailedPrecondition` when deletion cannot be proved. @@ -320,6 +330,17 @@ 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. +For a table's or a volume's full grants list, and to grant or revoke one of +their privileges, the service principal must own the metastore, the catalog, the +schema or the object itself, hold `MANAGE` on the object, its schema or its +catalog, or have Admin assigned directly on the workspace whose admins group +owns the catalog. Listing them is a separate right, and a stricter one than +listing the schemas: ownership of the metastore, the catalog or the schema, that +same Admin standing, or `ALL_PRIVILEGES` on the catalog. `USE_SCHEMA` and +`MANAGE` return every schema and neither returns every table or volume, so a +service principal holding only one of them syncs the schemas and then fails on +their children. + 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 fbee54d9..83db9ba1 100644 --- a/baton_capabilities.json +++ b/baton_capabilities.json @@ -383,6 +383,79 @@ ] } }, + { + "resourceType": { + "id": "table", + "displayName": "Table", + "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" + } + ] + } + ] + }, + "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" + } + ] + }, + "optInRequired": true + }, { "resourceType": { "id": "user", @@ -424,6 +497,82 @@ ] } }, + { + "resourceType": { + "id": "volume", + "displayName": "Volume", + "annotations": [ + { + "@type": "type.googleapis.com/c1.connector.v2.OptInRequired" + }, + { + "@type": "type.googleapis.com/c1.connector.v2.SkipEntitlements" + }, + { + "@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" + } + ] + } + ] + }, + "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" + } + ] + }, + "optInRequired": true + }, { "resourceType": { "id": "workspace", diff --git a/docs/connector.mdx b/docs/connector.mdx index d9c5cfe1..d7321be7 100644 --- a/docs/connector.mdx +++ b/docs/connector.mdx @@ -17,7 +17,9 @@ sidebarTitle: "Databricks" | Roles | | | | Schemas | | | | Service principals | | | +| Tables | | | | Users | | | +| Volumes | | | | Workspaces | | | The Databricks connector supports [automatic account provisioning and deprovisioning](/product/admin/account-provisioning). @@ -30,25 +32,25 @@ 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, catalog and schema access in C1 +## Metastore, catalog, schema, table and volume access in C1 The connector syncs Databricks [Unity Catalog](https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges) -metastores, the catalogs in them, and the schemas in those catalogs as C1 resources. Each privilege Databricks +metastores, the catalogs in them, the schemas in those catalogs, and the tables and volumes in those schemas as C1 resources. Each privilege Databricks records on one of them (`CREATE_CATALOG` on a metastore, `USE_CATALOG` or -`SELECT` on a catalog, `USE_SCHEMA` on a schema, and so on) becomes an entitlement in C1, so you can +`SELECT` on a catalog, `USE_SCHEMA` on a schema, `SELECT` on a table, `READ_VOLUME` on a volume, 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. +entitlement — it cannot be granted or revoked through C1. Views, materialized views, metric views and streaming tables are tables; `table_type` picks which privileges can be requested. `ALL_PRIVILEGES` on a view, and `MODIFY` on a streaming table, are shown when they already exist and cannot be requested. -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. +The Metastores, Catalogs, Schemas, Tables and Volumes resource types are turned off by default. Turn on the ones you want from the connector's configuration page in C1. Each level syncs under its parent securable, so turn on every level above the one you want; turning on Catalogs alone, or Tables without Schemas, syncs nothing. They all use the same OAuth credentials; no additional configuration fields are needed. **Notes on Unity Catalog access in C1:** -- 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. +- Ownership is shown but cannot be provisioned. An owner that is not an account identity, such as `System user`, is not shown. A workspace admins group is shown when it resolves as an account group. - **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. Their schemas are not synced either. @@ -238,6 +240,8 @@ Workspace **Admin** replaces all of this only when the catalog is owned by that 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. +Listing every table or volume needs more than **USE SCHEMA** or **MANAGE**. The service principal must own the metastore, the catalog, or the schema, be a direct Admin when the workspace admins group owns the catalog, or hold **ALL PRIVILEGES** on the catalog. Otherwise the sync fails. + **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 c8c6d939..73bd0bae 100644 --- a/docs/docs-info.md +++ b/docs/docs-info.md @@ -6,7 +6,7 @@ While developing the connector, please fill out this form. This information is n > The connector syncs the Databricks account, workspaces, users, groups, service principals, and roles. > - > It also syncs Unity Catalog metastores and their catalogs. Both resource types are opt-in — each stays off until enabled per resource type in C1. + > It also syncs Unity Catalog metastores, catalogs, schemas, tables, and volumes. Those resource types are opt-in — each stays off until enabled per resource type in C1. 2. Can the connector provision any resources? If so, which ones? @@ -14,7 +14,7 @@ While developing the connector, please fill out this form. This information is n > > - **User accounts**: create and delete account users. > - **Entitlements**: grant and revoke role and membership assignments on accounts, workspaces, groups, service principals, and roles. - > - **Unity Catalog privileges**: grant and revoke a metastore or catalog privilege for a user, group or service principal. The `owner` entitlement is read-only and cannot be granted or revoked. + > - **Unity Catalog privileges**: grant and revoke a privilege on a metastore, catalog, schema, table, or volume for a user, group or service principal. The `owner` entitlement is read-only and cannot be granted or revoked. ## Connector credentials @@ -57,7 +57,7 @@ While developing the connector, please fill out this form. This information is n - **Direct grants only.** Databricks inherits privileges downward. The connector reports the assignments stored on the object. The inheritance endpoint does not return principal IDs. - **Full grants visibility is required.** Metastore ownership or direct workspace Admin permits metastore reads. Catalog reads require one of the catalog permissions listed above; workspace Admin applies only when that workspace's admins group owns the catalog. Admin inherited through a group does not count. The sync fails instead of reporting a partial list, so C1 keeps the grants it already has. -- **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. +- **Ownership is read-only.** It is shown and cannot be granted or revoked. An owner that does not resolve to an account identity, such as `System user`, is not shown. A workspace admins group is shown when it resolves as an account group. - **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 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. @@ -70,4 +70,8 @@ While developing the connector, please fill out this form. This information is n - **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. +- **Tables and volumes are opt-in and hang from a schema.** Each is off until it is turned on in C1, and syncs nothing unless Schemas, Catalogs and Metastores are on as well. +- **A table and a volume are keyed by their full name.** Neither exposes an immutable id, so the resource id extends the schema key: `::..`. A rename re-keys the resource and its grants, as it does for a catalog and a schema. +- **One `table` securable covers more than tables.** Views, materialized views, metric views and streaming tables are all `table`. `table_type` picks the privilege set, so a table's entitlements are built per instance. `ALL_PRIVILEGES` on a view, `MODIFY` on a streaming table, and `REFRESH` on a type whose grants API refuses it are reported when already held and cannot be requested. +- **Listing a schema's tables or volumes is stricter than listing its schemas.** `USE_SCHEMA` and `ALL_PRIVILEGES` on the catalog each list every schema; only `ALL_PRIVILEGES` lists every table and volume, alongside ownership of the metastore, the catalog or the schema, or direct workspace Admin where the admins group owns the catalog. Reading one table's or one volume's privileges needs ownership of the metastore, the catalog, the schema or the object itself, or `MANAGE` on the object, its schema or its catalog. +- **Not synced yet:** 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 5d4d5c15..03ced15b 100644 --- a/pkg/connector/catalog.go +++ b/pkg/connector/catalog.go @@ -123,7 +123,6 @@ var errCatalogGone = errors.New("catalog no longer exists") type catalogBuilder struct { securableOps - // workspaces is the configured allowlist, empty when none was given. workspaces map[string]struct{} } diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index f06c4efc..45d0ca84 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -45,6 +45,8 @@ func (d *Databricks) ResourceSyncers(_ context.Context) []connectorbuilder.Resou newMetastoreBuilder(d.client, d.clientID, workspaces, principals), newCatalogBuilder(d.client, d.clientID, workspaces, principals), newSchemaBuilder(d.client, d.clientID, workspaces, principals), + newTableBuilder(d.client, d.clientID, workspaces, principals), + newVolumeBuilder(d.client, d.clientID, workspaces, principals), } } @@ -76,7 +78,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, catalogs and schemas — and the privileges granted on them", + "along with Unity Catalog data assets — metastores, catalogs, schemas, tables and volumes — 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 b2d96dcb..e5e41cbc 100644 --- a/pkg/connector/connector_test.go +++ b/pkg/connector/connector_test.go @@ -87,7 +87,10 @@ 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, schemaResourceType.Id} { + for _, want := range []string{ + metastoreResourceType.Id, catalogResourceType.Id, schemaResourceType.Id, + tableResourceType.Id, volumeResourceType.Id, + } { if !slices.Contains(registered, want) { t.Errorf("registered syncers = %v, want them to include %s", registered, want) } diff --git a/pkg/connector/metastore.go b/pkg/connector/metastore.go index 775be68a..4d68d54a 100644 --- a/pkg/connector/metastore.go +++ b/pkg/connector/metastore.go @@ -26,7 +26,6 @@ var _ connectorbuilder.StaticEntitlementSyncerV2 = (*metastoreBuilder)(nil) type metastoreBuilder struct { securableOps - // workspaces is the configured allowlist, empty when none was given. workspaces map[string]struct{} } diff --git a/pkg/connector/raw_id_test.go b/pkg/connector/raw_id_test.go index d0552e9d..c28a39db 100644 --- a/pkg/connector/raw_id_test.go +++ b/pkg/connector/raw_id_test.go @@ -84,6 +84,19 @@ func TestResourcesHaveRawId(t *testing.T) { &v2.ResourceId{ResourceType: catalogResourceType.Id, Resource: "ms1::cat"}, schemaRoute{})), "ms1::cat.sch", }, + { + // A table and a volume extend the schema's id with their own name. + "table", + build(tableResource(&databricks.Table{Name: "orders"}, "ms1", "cat", "sch", + &v2.ResourceId{ResourceType: schemaResourceType.Id, Resource: "ms1::cat.sch"}, schemaChildRoute{})), + "ms1::cat.sch.orders", + }, + { + "volume", + build(volumeResource(&databricks.Volume{Name: "files"}, "ms1", "cat", "sch", + &v2.ResourceId{ResourceType: schemaResourceType.Id, Resource: "ms1::cat.sch"}, schemaChildRoute{})), + "ms1::cat.sch.files", + }, } for _, tc := range cases { diff --git a/pkg/connector/resource_types.go b/pkg/connector/resource_types.go index fab13dfd..609dc99c 100644 --- a/pkg/connector/resource_types.go +++ b/pkg/connector/resource_types.go @@ -102,4 +102,20 @@ var ( Annotations: annotationsForStaticSecurableResourceType( securablePermissions(permissionUseCatalog, permissionUseSchema, privilegeManage)...), } + + tableResourceType = &v2.ResourceType{ + Id: "table", + DisplayName: "Table", + Annotations: annotationsForSecurableResourceType(securablePermissions(permissionUseCatalog, permissionUseSchema)...), + } + + volumeResourceType = &v2.ResourceType{ + Id: "volume", + DisplayName: "Volume", + Annotations: annotations.New( + &v2.OptInRequired{}, + &v2.SkipEntitlements{}, + capabilityPermissions(securablePermissions(permissionUseCatalog, permissionUseSchema)...), + ), + } ) diff --git a/pkg/connector/schema.go b/pkg/connector/schema.go index 483e4778..9f336d61 100644 --- a/pkg/connector/schema.go +++ b/pkg/connector/schema.go @@ -156,7 +156,11 @@ func schemaResource( nil, rs.WithResourceProfile(profile), rs.WithParentResourceID(parent), - rs.WithAnnotation(&v2.RawId{Id: resourceID}), + rs.WithAnnotation( + &v2.ChildResourceType{ResourceTypeId: tableResourceType.Id}, + &v2.ChildResourceType{ResourceTypeId: volumeResourceType.Id}, + &v2.RawId{Id: resourceID}, + ), ) } @@ -321,8 +325,41 @@ func (b *schemaBuilder) pushRoute( return nil } +// errSchemaGone marks a schema Databricks named as missing. +var errSchemaGone = errors.New("schema no longer exists") + +// schemaThrough reads one schema through workspace. It reports errSchemaGone +// when Databricks names the schema itself missing, which proves nothing on its +// own, so the caller decides what that absence means. Every other refusal leaves +// the schema unknown: read as empty, C1 would delete its tables and volumes. +func schemaThrough( + ctx context.Context, + client *databricks.Client, + workspace, catalogName, schemaName string, + annos *annotations.Annotations, +) (*databricks.Schema, error) { + fullName := catalogName + schemaNameSeparator + schemaName + schema, rateLimit, err := client.GetSchema(ctx, workspace, fullName) + noteRateLimit(annos, rateLimit) + switch { + case err == nil: + case databricks.IsSecurableGone(err, errorCodeSchemaGone): + return nil, errSchemaGone + case status.Code(err) == codes.InvalidArgument: + // The answer does not describe the schema asked for. + return nil, err + default: + return nil, refuseUnreadable(fmt.Sprintf( + "databricks-connector: schema %s cannot be read through workspace %s, "+ + "so its tables and volumes are unknown", fullName, workspace), err) + } + + return schema, nil +} + // schemaListingError returns NotFound only when Databricks names the missing -// catalog; any other refusal leaves the schema listing unknown. +// catalog. Any other refusal leaves the listing unknown rather than empty: a +// short list would read as deletions in C1. func schemaListingError(catalogName, workspace string, err error) error { if databricks.IsSecurableGone(err, errorCodeCatalogGone) { return uhttp.WrapErrors(codes.NotFound, @@ -483,7 +520,7 @@ func (b *schemaBuilder) entitlementOnLiveRoute( return nil, err } - route, catalog, err := b.liveCatalogRoute(ctx, resource, metastoreID, catalogName, owner, annos) + route, catalog, err := liveCatalogRoute(ctx, b.client, b.clientID, b.workspaces, resource, metastoreID, catalogName, owner, annos) if err != nil { return nil, err } @@ -516,15 +553,18 @@ func (b *schemaBuilder) entitlementOnLiveRoute( // 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( +func liveCatalogRoute( ctx context.Context, + client *databricks.Client, + clientID string, + workspaces map[string]struct{}, 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) + if route, ok := profileCatalogRoute(client, workspaces, resource, metastoreOwner); ok { + catalog, err := catalogThrough(ctx, client, route.Workspace, metastoreID, catalogName, annos) switch { case err == nil: case errors.Is(err, errCatalogGone): @@ -541,11 +581,11 @@ func (b *schemaBuilder) liveCatalogRoute( } } - scope, err := scopedWorkspaces(ctx, b.client, b.workspaces, annos) + scope, err := scopedWorkspaces(ctx, client, workspaces, annos) if err != nil { return schemaRoute{}, nil, err } - usable, _, err := scope.attached(ctx, b.client, metastoreID, annos) + usable, _, err := scope.attached(ctx, client, metastoreID, annos) if err != nil { return schemaRoute{}, nil, assignmentListError(metastoreID, err) } @@ -555,11 +595,11 @@ func (b *schemaBuilder) liveCatalogRoute( metastoreID, catalogName) } - workspace, catalog, err := workspaceForCatalog(ctx, b.client, metastoreID, catalogName, usable, probe, nil, annos) + workspace, catalog, err := workspaceForCatalog(ctx, 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) + ctx, client, clientID, metastoreID, catalogName, usable[0].DeploymentName, metastoreOwner, annos) } return schemaRoute{}, nil, err diff --git a/pkg/connector/schema_child.go b/pkg/connector/schema_child.go new file mode 100644 index 00000000..2f395c1b --- /dev/null +++ b/pkg/connector/schema_child.go @@ -0,0 +1,561 @@ +package connector + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "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/pagination" + 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" + "google.golang.org/protobuf/proto" +) + +// profileKeySchemaOwner carries the parent schema's owner, which is one of the +// things that makes a table's or a volume's privilege read complete. Grants is +// handed only the table, so List writes it down. +const profileKeySchemaOwner = "schema_owner" + +// schemaChildRoute is the workspace a schema's tables or volumes are listed +// through, carried in the page token so later pages neither re-resolve the route +// nor prove again that the parent listing is complete. The owners ride along so +// each resource's profile can carry them. See profileKeySchemaOwner. +type schemaChildRoute struct { + Workspace string `json:"w"` + WorkspaceID string `json:"i"` + WorkspaceName string `json:"n"` + MetastoreOwner string `json:"o"` + CatalogOwner string `json:"c"` + SchemaOwner string `json:"s"` +} + +// listSchemaChildren pages one level that hangs from a schema — a table or a +// volume — through a workspace proved to list every one of them, calling fetch +// for each page. The owners that proof learns are written onto each resource, +// so Grants does not run it again. +func listSchemaChildren( + ctx context.Context, + client *databricks.Client, + clientID string, + workspaces map[string]struct{}, + resourceType *v2.ResourceType, + noun string, + parentResourceID *v2.ResourceId, + attr rs.SyncOpAttrs, + fetch func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, pageToken string) ( + []*v2.Resource, string, *v2.RateLimitDescription, error), +) ([]*v2.Resource, *rs.SyncOpResults, error) { + ctx = context.WithValue(ctx, syncSessionKey{}, attr.Session) + if parentResourceID.GetResourceType() != schemaResourceType.Id { + return nil, nil, nil + } + + metastoreID, catalogName, schemaName, err := parseSchemaID(parentResourceID.GetResource()) + if err != nil { + return nil, nil, err + } + // The schema syncer leaves Databricks' own read-only schema out, so nothing + // under it is ever synced either. + if schemaName == informationSchema { + return nil, nil, nil + } + + 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 %s page token: %v", noun, err) + } + + if bag.Current() == nil { + if err := pushSchemaChildRoute(ctx, client, clientID, workspaces, resourceType, noun, + metastoreID, catalogName, schemaName, 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 schema; listing none of its children", + zap.String("resource_type", resourceType.Id), + zap.String("schema", parentResourceID.GetResource())) + + return nil, &rs.SyncOpResults{Annotations: annos}, nil + } + } + + var route schemaChildRoute + if err := json.Unmarshal([]byte(bag.ResourceID()), &route); err != nil { + return nil, nil, status.Errorf(codes.InvalidArgument, "databricks-connector: invalid %s page token: %v", noun, err) + } + + rv, next, rateLimit, err := fetch(ctx, route, metastoreID, catalogName, schemaName, bag.PageToken()) + noteRateLimit(&annos, rateLimit) + if err != nil { + return nil, &rs.SyncOpResults{Annotations: annos}, + schemaChildListingError(noun, catalogName+schemaNameSeparator+schemaName, route.Workspace, err) + } + + if next != "" && next == bag.PageToken() { + return nil, &rs.SyncOpResults{Annotations: annos}, status.Errorf(codes.Internal, + "databricks-connector: listing the %ss of schema %s.%s repeated page token %q", noun, catalogName, schemaName, 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 +} + +// childListRemedy is what a refusal to sync a schema whose table or volume +// listing is partial tells the operator to fix. USE_SCHEMA and MANAGE list +// schemas; they do not list every table or volume. +const childListRemedy = "the connector's service principal must own the metastore, the catalog or the schema, " + + "or hold ALL_PRIVILEGES on the catalog" + +// pushSchemaChildRoute records a workspace that can list every table or volume +// of the schema, walking the running in-scope workspaces until one serves the +// catalog, serves the schema and proves the child listing complete. A workspace +// that answers neither is skipped and the walk goes on. Pushing nothing empties +// the listing, so that is reserved for a parent every workspace named as gone +// with none refusing a read; any refusal left standing is an error instead. +func pushSchemaChildRoute( + ctx context.Context, + client *databricks.Client, + clientID string, + workspaces map[string]struct{}, + resourceType *v2.ResourceType, + noun string, + metastoreID, catalogName, schemaName string, + bag *pagination.Bag, + annos *annotations.Annotations, +) error { + scope, err := scopedWorkspaces(ctx, client, workspaces, annos) + if err != nil { + return err + } + + usable, inScope, err := scope.attached(ctx, 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, 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 + } + + fullName := catalogName + schemaNameSeparator + schemaName + var sawCatalog, sawGone, provenGone, sawForeign bool + var lastDeny error + for i := range usable { + workspace := usable[i] + catalog, err := catalogThrough(ctx, client, workspace.DeploymentName, metastoreID, catalogName, annos) + if err != nil { + // A 404 carrying no code reaches the SDK as NotFound, which it reads as + // a warning: the children would be emitted as none and C1 would delete + // them. A workspace that does not serve the catalog says nothing about + // the schema below it, so the walk goes on instead. + if errors.Is(err, errCatalogGone) { + sawGone = true + + continue + } + if deniesTrust(err) { + lastDeny = err + + continue + } + + return err + } + if catalog == nil { + // A catalog of another metastore is an answer, not an absence, so it + // cannot stand in for proof that this metastore's catalog is gone. + sawForeign = true + + continue + } + sawCatalog = true + // The reads run in order, so a workspace serving the catalog now supersedes a + // gone answer an earlier one gave. + provenGone = false + + route := schemaChildRoute{ + Workspace: workspace.DeploymentName, + WorkspaceID: strconv.Itoa(workspace.ID), + WorkspaceName: workspace.Name, + MetastoreOwner: owner, + CatalogOwner: catalog.Owner, + } + trust := securableTrust{ + ownPrincipal: clientID, + metastoreOwner: owner, + parentOwner: catalog.Owner, + fullName: catalogName, + workspace: route.Workspace, + workspaceID: route.WorkspaceID, + } + schemasComplete, err := schemaListingIsComplete(ctx, client, trust, annos) + if err != nil { + // A workspace the catalog is not bound to refuses with 403, which + // deniesTrust takes above, so this read names it missing only when it is. + if errors.Is(err, errCatalogGone) { + provenGone = true + + continue + } + + return err + } + + schema, err := schemaThrough(ctx, client, route.Workspace, catalogName, schemaName, annos) + // A schema named as missing is read like one absent from the listing: + // proof of deletion only for a caller that sees the whole catalog. + if errors.Is(err, errSchemaGone) { + schema, err = nil, nil + } + if err != nil { + // A workspace that refuses the schema read says nothing about the ones + // that have not been asked yet, so the walk goes on as it does for the + // catalog read above. + if deniesTrust(err) { + lastDeny = err + + continue + } + + return err + } + if schemasComplete && schema == nil { + ctxzap.Extract(ctx).Debug("databricks-connector: the schema is no longer there; listing none of its children", + zap.String("resource_type", resourceType.Id), + zap.String("schema", fullName), + zap.String("workspace", route.Workspace)) + + return nil + } + // Owning the schema is enough to list its children. Anything else a + // partial list hides cannot be told from a schema that is gone. + if schema == nil || (!schemasComplete && !ownsPrincipal(clientID, schema.Owner)) { + continue + } + + trust.schemaOwner = schema.Owner + childrenComplete, err := childListingIsComplete(ctx, client, trust, annos) + if err != nil { + if errors.Is(err, errCatalogGone) { + provenGone = true + + continue + } + + return err + } + if !childrenComplete { + continue + } + route.SchemaOwner = schema.Owner + + encoded, err := json.Marshal(route) + if err != nil { + return err + } + bag.Push(pagination.PageState{ResourceTypeID: resourceType.Id, ResourceID: string(encoded)}) + + return nil + } + // A catalog proved gone holds no tables or volumes, and the catalog syncer + // drops the parent in the same sync. A refusal anywhere leaves the picture mixed. + if provenGone && lastDeny == nil { + return nil + } + if !sawCatalog { + // A workspace that does not serve the catalog answers like a gone one. + if sawGone && lastDeny == nil && !sawForeign { + return nil + } + msg := fmt.Sprintf("databricks-connector: no workspace in sync scope lists catalog %s of metastore %s", catalogName, metastoreID) + if lastDeny != nil { + msg = fmt.Sprintf("%s: %s", msg, lastDeny.Error()) + } + + return status.Errorf(codes.FailedPrecondition, "%s", msg) + } + + return status.Errorf(codes.PermissionDenied, + "databricks-connector: cannot list every %s in schema %s; %s", noun, fullName, childListRemedy) +} + +// childListingIsComplete is true when ListTables or ListVolumes returns every +// child of the schema. USE_SCHEMA and MANAGE make the schema list complete. +// They do not make the table or volume list complete. +func childListingIsComplete( + ctx context.Context, + client *databricks.Client, + trust securableTrust, + annos *annotations.Annotations, +) (bool, error) { + if ownsPrincipal(trust.ownPrincipal, trust.metastoreOwner) || + ownsPrincipal(trust.ownPrincipal, trust.parentOwner) || + ownsPrincipal(trust.ownPrincipal, trust.schemaOwner) { + 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 + } + } + + complete, err := holdsPrivilegeOn(ctx, client, trust, databricks.SecurableCatalog, trust.fullName, + []string{privilegeAllPrivileges}, []string{errorCodeCatalogGone}, annos) + if errors.Is(err, errSecurableGone) { + return false, errCatalogGone + } + + return complete, err +} + +// schemaChildListingError reads a workspace that refuses the listing as unknown, +// not as listing nothing: a short list would read as deletions in C1, and the SDK +// reads a NotFound as a securable with no children. +func schemaChildListingError(noun, schemaFullName, workspace string, err error) error { + switch apiStatus(err) { + case http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound: + return uhttp.WrapErrors(codes.FailedPrecondition, + fmt.Sprintf("databricks-connector: the %ss of schema %s cannot be listed through workspace %s, "+ + "so which of them are in scope is unknown; %s", noun, schemaFullName, workspace, childListRemedy), + err) + } + + return fmt.Errorf("databricks-connector: failed to list the %ss of schema %s through workspace %s: %w", + noun, schemaFullName, workspace, err) +} + +// schemaChildResourceID keys a table or a volume by its metastore and its dotted +// full name, which extends the schema's "{metastore_id}::{catalog}.{schema}". +func schemaChildResourceID(metastoreID, catalogName, schemaName, name string) string { + return metastoreID + securableKeySeparator + + strings.Join([]string{catalogName, schemaName, name}, schemaNameSeparator) +} + +// parseSchemaChildID reads a table or volume resource id, +// "{metastore_id}::{catalog}.{schema}.{name}". +func parseSchemaChildID(resourceID, noun string) (string, string, string, string, error) { + invalid := status.Errorf(codes.InvalidArgument, "databricks-connector: invalid %s resource id %q", noun, resourceID) + + metastoreID, fullName, ok := strings.Cut(resourceID, securableKeySeparator) + if !ok { + return "", "", "", "", invalid + } + + parts := strings.Split(fullName, schemaNameSeparator) + if len(parts) != 3 || metastoreID == "" || parts[0] == "" || parts[1] == "" || parts[2] == "" { + return "", "", "", "", invalid + } + + return metastoreID, parts[0], parts[1], parts[2], nil +} + +// schemaChildProfile is what every table and volume carries, before the level +// adds its own name and type. +func schemaChildProfile(metastoreID, catalogName, schemaName, fullName, owner, securableType string, route schemaChildRoute) map[string]any { + return map[string]any{ + profileKeyMetastoreID: metastoreID, + profileKeyMetastoreOwner: route.MetastoreOwner, + profileKeyFullName: fullName, + profileKeyCatalogName: catalogName, + profileKeyCatalogOwner: route.CatalogOwner, + profileKeySchemaName: schemaName, + profileKeySchemaOwner: route.SchemaOwner, + profileKeyOwner: owner, + profileKeySecurableType: securableType, + profileKeyWorkspace: route.Workspace, + profileKeyWorkspaceID: route.WorkspaceID, + profileKeyWorkspaceName: route.WorkspaceName, + } +} + +// schemaChildGrantsAreTrustworthy is true for an owner of the table or volume, +// its schema, its catalog or the metastore, for a holder of MANAGE on any of +// those, or for a direct Admin when the workspace admins group owns the catalog. +func schemaChildGrantsAreTrustworthy( + ctx context.Context, + client *databricks.Client, + trust securableTrust, + securableType string, + annos *annotations.Annotations, +) (bool, error) { + // An owner holds every privilege implicitly, which is not reported as a grant. + if ownsPrincipal(trust.ownPrincipal, trust.metastoreOwner) || + ownsPrincipal(trust.ownPrincipal, trust.parentOwner) || + ownsPrincipal(trust.ownPrincipal, trust.schemaOwner) || + ownsPrincipal(trust.ownPrincipal, trust.owner) { + 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 + } + } + + // MANAGE on the securable, its schema or its catalog makes the privilege + // list complete, and one effective read reports all three. + return holdsEffectivePrivilegeOn(ctx, client, trust, securableType, trust.fullName, managePrivilege, annos) +} + +// liveChildRoute rebuilds the route and the owners above a table or a volume +// from what Databricks reports now. The metastore owner comes from a live +// listing, the catalog from the recorded workspace when this sync still admits +// it and otherwise from the first running in-scope workspace that serves it, +// and the schema from a read through that workspace. +func liveChildRoute( + ctx context.Context, + client *databricks.Client, + clientID string, + workspaces map[string]struct{}, + resource *v2.Resource, + metastoreID, catalogName, schemaName string, + annos *annotations.Annotations, +) (schemaChildRoute, error) { + owner, err := metastoreOwner(ctx, client, metastoreID, annos) + if err != nil { + return schemaChildRoute{}, err + } + + route, catalog, err := liveCatalogRoute(ctx, client, clientID, workspaces, resource, metastoreID, catalogName, owner, annos) + if err != nil { + return schemaChildRoute{}, err + } + + fullName := catalogName + schemaNameSeparator + schemaName + schema, rateLimit, err := 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 schemaChildRoute{}, errSecurableGone + } + + return schemaChildRoute{}, refuseUnreadable(fmt.Sprintf( + "databricks-connector: failed to read schema %s through workspace %s", fullName, route.Workspace), err) + } + + return schemaChildRoute{ + Workspace: route.Workspace, + WorkspaceID: route.WorkspaceID, + WorkspaceName: route.WorkspaceName, + MetastoreOwner: owner, + CatalogOwner: catalog.Owner, + SchemaOwner: schema.Owner, + }, nil +} + +// childEntitlementOnLiveRoute rebuilds the entitlement's table or volume from +// what Databricks reports now: the four owners the trust check short-circuits +// on — metastore, catalog, schema and the securable itself — 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. read is the +// level's own leaf read, which also answers whether the securable is gone. +func childEntitlementOnLiveRoute( + ctx context.Context, + client *databricks.Client, + clientID string, + workspaces map[string]struct{}, + noun string, + entitlement *v2.Entitlement, + annos *annotations.Annotations, + read func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, name string, + parent *v2.ResourceId, annos *annotations.Annotations) (*v2.Resource, error), +) (*v2.Entitlement, error) { + resource := entitlement.GetResource() + metastoreID, catalogName, schemaName, name, err := parseSchemaChildID(resource.GetId().GetResource(), noun) + if err != nil { + return nil, err + } + + route, err := liveChildRoute(ctx, client, clientID, workspaces, resource, metastoreID, catalogName, schemaName, annos) + if err != nil { + return nil, err + } + + routed, err := read(ctx, route, metastoreID, catalogName, schemaName, name, resource.GetParentResourceId(), annos) + if err != nil { + return nil, err + } + + copyEntitlement, ok := proto.Clone(entitlement).(*v2.Entitlement) + if !ok { + return nil, status.Errorf(codes.Internal, "databricks-connector: cannot copy the %s entitlement", noun) + } + copyEntitlement.Resource = routed + + return copyEntitlement, nil +} + +// schemaChildIsGone settles a 404 that a missing table or volume and a workspace +// that cannot serve its catalog both answer with. The parent is read first +// through that same workspace: only a schema it answers 200 for makes the +// securable's own 404 proof of deletion. Any other answer leaves the absence +// unproven, which is what keeps C1 from removing what it already has. +func schemaChildIsGone( + ctx context.Context, + client *databricks.Client, + noun, fullName, workspace string, + annos *annotations.Annotations, + readSecurable func(ctx context.Context, workspace, fullName string) (*v2.RateLimitDescription, error), +) (bool, error) { + cut := strings.LastIndex(fullName, schemaNameSeparator) + if cut <= 0 { + return false, status.Errorf(codes.InvalidArgument, + "databricks-connector: %s %s has no parent schema in its name", noun, fullName) + } + schemaFullName := fullName[:cut] + + _, rateLimit, err := client.GetSchema(ctx, workspace, schemaFullName) + noteRateLimit(annos, rateLimit) + if err != nil { + return false, fmt.Errorf( + "databricks-connector: workspace %s does not answer for schema %s, so a %s missing there cannot be told from one it cannot serve: %w", + workspace, schemaFullName, noun, err) + } + + rateLimit, err = readSecurable(ctx, workspace, fullName) + noteRateLimit(annos, rateLimit) + switch { + case err == nil: + return false, nil + case apiStatus(err) == http.StatusNotFound: + // The workspace serves the parent and still has no such securable. + return true, nil + } + + return false, err +} diff --git a/pkg/connector/schema_child_gone_test.go b/pkg/connector/schema_child_gone_test.go new file mode 100644 index 00000000..3ba20c3e --- /dev/null +++ b/pkg/connector/schema_child_gone_test.go @@ -0,0 +1,126 @@ +package connector + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/conductorone/baton-databricks/pkg/databricks" + "github.com/conductorone/baton-sdk/pkg/annotations" +) + +// TestSchemaChildGoneNeedsTheParentServed pins the rule that decides whether C1 +// keeps or removes a table's and a volume's grants: a 404 is proof of deletion +// only from a workspace that has just answered 200 for the parent schema. A +// workspace that cannot serve the catalog answers the same codes, so believing +// one of those empties a securable that still exists. +func TestSchemaChildGoneNeedsTheParentServed(t *testing.T) { + t.Setenv("BATON_HTTP_CACHE_TTL", "0") + + const ( + schemaPath = "/api/2.1/unity-catalog/schemas/main.sales" + tablePath = "/api/2.1/unity-catalog/tables/main.sales.orders" + volumePath = "/api/2.1/unity-catalog/volumes/main.sales.files" + ) + + leafBodies := map[string]string{ + tablePath: `{"name":"orders","full_name":"main.sales.orders","owner":"eng","table_type":"MANAGED"}`, + volumePath: `{"name":"files","full_name":"main.sales.files","owner":"eng","volume_type":"MANAGED"}`, + } + + for _, tc := range []struct { + name string + schemaStatus int + leafStatus int + wantGone bool + wantErr bool + }{ + {name: "parent served and the securable is absent", schemaStatus: 200, leafStatus: 404, wantGone: true}, + {name: "parent served and the securable answers", schemaStatus: 200, leafStatus: 200, wantGone: false}, + {name: "parent not served, so the absence is unproven", schemaStatus: 404, leafStatus: 404, wantGone: false, wantErr: true}, + {name: "parent refused, so the absence is unproven", schemaStatus: 403, leafStatus: 404, wantGone: false, wantErr: true}, + {name: "parent served and the securable read fails", schemaStatus: 200, leafStatus: 500, wantGone: false, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var leafReads int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case schemaPath: + if tc.schemaStatus != http.StatusOK { + w.WriteHeader(tc.schemaStatus) + _, _ = io.WriteString(w, `{"error_code":"CATALOG_DOES_NOT_EXIST","message":"no"}`) + + return + } + _, _ = io.WriteString(w, `{"name":"sales","full_name":"main.sales","owner":"eng"}`) + case tablePath, volumePath: + leafReads++ + if tc.leafStatus != http.StatusOK { + w.WriteHeader(tc.leafStatus) + _, _ = io.WriteString(w, `{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"no"}`) + + return + } + _, _ = io.WriteString(w, leafBodies[r.URL.Path]) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + + client := newGoneCheckClient(t, srv.URL) + annos := annotations.Annotations{} + + for _, probe := range []struct { + noun string + fn func(context.Context, *databricks.Client, string, string, *annotations.Annotations) (bool, error) + full string + }{ + {"table", tableIsGone, "main.sales.orders"}, + {"volume", volumeIsGone, "main.sales.files"}, + } { + gone, err := probe.fn(context.Background(), client, probe.full, testWorkspaceId, &annos) + if gone != tc.wantGone { + t.Errorf("%s: gone = %v, want %v", probe.noun, gone, tc.wantGone) + } + if (err != nil) != tc.wantErr { + t.Errorf("%s: err = %v, want error %v", probe.noun, err, tc.wantErr) + } + } + + if tc.schemaStatus != http.StatusOK && leafReads != 0 { + t.Errorf("read the securable %d times without the parent served, want 0", leafReads) + } + }) + } +} + +// TestTableGoneCodeNamingTheTableNeedsNoConfirmation keeps the one unambiguous +// code cheap: it names the table, so no extra read runs. +func TestTableGoneCodeNamingTheTableNeedsNoConfirmation(t *testing.T) { + if got := tableLevel(tablePrivileges).goneErrorCodes; len(got) != 1 || got[0] != errorCodeTableGone { + t.Fatalf("table goneErrorCodes = %v, want only %q", got, errorCodeTableGone) + } + if got := volumeLevel.goneErrorCodes; len(got) != 0 { + t.Fatalf("volume goneErrorCodes = %v, want none: Databricks never names a missing volume", got) + } +} + +func newGoneCheckClient(t *testing.T, serverURL string) *databricks.Client { + t.Helper() + target, err := url.Parse(serverURL) + if err != nil { + t.Fatalf("parse server url: %v", err) + } + httpClient := &http.Client{Transport: &hostRewriter{target: target}} + client, err := databricks.NewClient(context.Background(), httpClient, + testHostname, testAccountHost, testAccountId, "", &databricks.NoAuth{}, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + + return client +} diff --git a/pkg/connector/securable_helpers.go b/pkg/connector/securable_helpers.go index f2c51513..02000a08 100644 --- a/pkg/connector/securable_helpers.go +++ b/pkg/connector/securable_helpers.go @@ -36,6 +36,15 @@ type securableOps struct { level securableLevel } +// withLevel returns the ops addressed at another level. A table's privilege set +// follows its table_type, so that level is decided per resource rather than once +// on the builder. +func (o securableOps) withLevel(level securableLevel) securableOps { + o.level = level + + return o +} + // securableLevel is the only thing the permissions endpoint needs to tell one // Unity Catalog level from another: how a resource id addresses the securable, // what it can be granted, and what a refusal tells the operator. @@ -65,6 +74,16 @@ type securableLevel struct { // of absence: an unbound or unprivileged workspace answers 404 too. goneErrorCodes []string + // ambiguousGoneCodes are codes a missing securable shares with a workspace + // that cannot serve it, so on their own they prove nothing. A level that + // names any must also set confirmGone. + ambiguousGoneCodes []string + + // confirmGone reads the securable itself to settle an ambiguous code. A + // level whose codes are all unambiguous leaves it nil. + confirmGone func(ctx context.Context, client *databricks.Client, fullName, workspace string, + annos *annotations.Annotations) (bool, error) + // trusts reports whether the connector reads every privilege assignment on // the securable. What proves that differs per level, so the rule travels // with the level rather than being decided by the shared path. @@ -90,6 +109,8 @@ type securableTrust struct { parentOwner string + schemaOwner string + fullName string workspace string workspaceID string @@ -112,18 +133,20 @@ func ensureGrantsAreTrustworthy( metastoreOwner, _ := rs.GetProfileStringValue(profile, profileKeyMetastoreOwner) workspaceID, _ := rs.GetProfileStringValue(profile, profileKeyWorkspaceID) parentOwner, _ := rs.GetProfileStringValue(profile, profileKeyCatalogOwner) + schemaOwner, _ := rs.GetProfileStringValue(profile, profileKeySchemaOwner) trustworthy, err := level.trusts(ctx, client, securableTrust{ ownPrincipal: clientID, owner: owner, metastoreOwner: metastoreOwner, parentOwner: parentOwner, + schemaOwner: schemaOwner, fullName: fullName, workspace: workspace, workspaceID: workspaceID, }, annos) if err != nil { - return trustReadError(level, fullName, workspace, err) + return trustReadError(ctx, client, level, fullName, workspace, err, annos) } if !trustworthy { return status.Errorf(codes.PermissionDenied, @@ -137,11 +160,20 @@ func ensureGrantsAreTrustworthy( // 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 { +func trustReadError( + ctx context.Context, + client *databricks.Client, + level securableLevel, + fullName, workspace string, + err error, + annos *annotations.Annotations, +) error { if !errors.Is(err, errTrustRead404) { return err } - if databricks.IsSecurableGone(err, level.goneErrorCodes...) { + // A volume names the generic code, which a workspace that cannot serve it + // returns too, so absence is confirmed by reading the securable itself. + if securableIsGone(ctx, client, level, fullName, workspace, err, annos) { return errSecurableGone } @@ -191,10 +223,7 @@ func (o securableOps) syncGrants( assignments, nextPageToken, rateLimit, err := client.ListPermissions(ctx, workspace, level.securableType, fullName, "", pageToken) noteRateLimit(&annos, rateLimit) if err != nil { - // A securable deleted between List and this read is not a failed sync. - // Only a level that names its gone codes can reach this: with none, - // IsSecurableGone is false and every 404 still refuses the read. - if databricks.IsSecurableGone(err, level.goneErrorCodes...) { + if securableIsGone(ctx, client, level, fullName, workspace, err, &annos) { return nil, &rs.SyncOpResults{Annotations: annos}, nil } return nil, &rs.SyncOpResults{Annotations: annos}, refuseUnreadable(fmt.Sprintf( @@ -223,9 +252,6 @@ func (o securableOps) syncGrants( options := groupSecurableGrantOptions(principalId) for _, privilege := range assignment.Privileges { if !slices.Contains(level.privileges, privilege) { - // A privilege Databricks added after this connector shipped is not - // an entitlement, so it cannot be emitted. Say so rather than - // dropping it without a trace. l.Debug("databricks-connector: the securable reports a privilege this connector does not model", zap.String("securable", resourceID), zap.String("privilege", privilege)) @@ -442,10 +468,7 @@ func (o securableOps) revoke( }) noteRateLimit(&annos, rateLimit) if err != nil { - // Databricks names the missing securable in error_code. That is the only - // answer that proves it is gone, so there is nothing left to revoke: a - // bare 404 also comes back from a workspace the securable is not bound to. - if databricks.IsSecurableGone(err, level.goneErrorCodes...) { + if securableIsGone(ctx, client, level, change.fullName, change.workspace, err, &annos) { annos.Update(&v2.GrantAlreadyRevoked{}) return annos, nil @@ -489,3 +512,35 @@ func (o securableOps) revoke( func isSecurableGoneSentinel(err error) bool { return errors.Is(err, errSecurableGone) || errors.Is(err, errCatalogGone) || errors.Is(err, errMetastoreGone) } + +// securableIsGone reports whether err proves the securable no longer exists. An +// unambiguous code settles it alone. A code a missing securable shares with a +// workspace that cannot serve it is settled by reading the securable, and a read +// that does not answer leaves the absence unproven rather than assuming it. +func securableIsGone( + ctx context.Context, + client *databricks.Client, + level securableLevel, + fullName, workspace string, + err error, + annos *annotations.Annotations, +) bool { + if databricks.IsSecurableGone(err, level.goneErrorCodes...) { + return true + } + if level.confirmGone == nil || !databricks.IsSecurableGone(err, level.ambiguousGoneCodes...) { + return false + } + + gone, confirmErr := level.confirmGone(ctx, client, fullName, workspace, annos) + if confirmErr != nil { + ctxzap.Extract(ctx).Debug("databricks-connector: could not confirm whether the securable is gone", + zap.String("securable", fullName), + zap.String("workspace", workspace), + zap.Error(confirmErr)) + + return false + } + + return gone +} diff --git a/pkg/connector/table.go b/pkg/connector/table.go new file mode 100644 index 00000000..c840379e --- /dev/null +++ b/pkg/connector/table.go @@ -0,0 +1,439 @@ +package connector + +import ( + "context" + "errors" + "fmt" + "slices" + "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" + ent "github.com/conductorone/baton-sdk/pkg/types/entitlement" + rs "github.com/conductorone/baton-sdk/pkg/types/resource" + "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.ResourceSyncerV2 = (*tableBuilder)(nil) + +const ( + securableTypeTable = "TABLE" + + errorCodeTableGone = "TABLE_DOES_NOT_EXIST" + + // The canonical UPPER_SNAKE form the API answers with. + privilegeAllPrivileges = "ALL_PRIVILEGES" + privilegeRefresh = "REFRESH" + + // A view and a materialized view are both securable_type "table", so + // table_type is the only field that says which privileges apply. + tableTypeManaged = "MANAGED" + tableTypeExternal = "EXTERNAL" + tableTypeManagedShallowClone = "MANAGED_SHALLOW_CLONE" + tableTypeExternalShallowClone = "EXTERNAL_SHALLOW_CLONE" + tableTypeForeign = "FOREIGN" + tableTypeView = "VIEW" + tableTypeMaterializedView = "MATERIALIZED_VIEW" + tableTypeStreamingTable = "STREAMING_TABLE" + tableTypeMetricView = "METRIC_VIEW" + + profileKeyTableName = "table_name" + profileKeyTableType = "table_type" + + tableWriteRemedy = "the connector must own the metastore, the parent catalog, the parent schema or the table, " + + "or hold MANAGE on the table, the parent schema or the parent catalog" + + tableTrustRemedy = "the connector's service principal must own the metastore, the parent catalog, the parent schema or the table, " + + "hold MANAGE on the table, the parent schema or the parent catalog, or be assigned Admin directly on the workspace whose " + + "admins group owns the parent catalog" +) + +// tablePrivileges is the set a real table takes. BROWSE, and everything that +// creates a securable, stop higher up. +// https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges +var tablePrivileges = []string{ + privilegeAllPrivileges, + "APPLY_TAG", + "DELETE", + "INSERT", + privilegeManage, + "MODIFY", + "READ_METADATA", + "SELECT", + "UPDATE", +} + +// viewPrivileges matches the privileges reference, ALL_PRIVILEGES included. The +// REST grants API still answers an added ALL_PRIVILEGES on a view with a 400, so +// Grant rejects that write while Grants still reports one SQL already granted. +var viewPrivileges = []string{ + privilegeAllPrivileges, + "APPLY_TAG", + privilegeManage, + "READ_METADATA", + "SELECT", +} + +// A materialized view accepts ALL_PRIVILEGES, and a permissions read answers +// with only it, not the SELECT and REFRESH it implies. +var materializedViewPrivileges = append(slices.Clone(viewPrivileges), privilegeRefresh) + +// A streaming table takes SELECT and REFRESH. MODIFY is reported when a +// principal already holds it and is not offered: the streaming-tables reference +// lists SELECT and REFRESH only, and a grant of MODIFY has not been seen to succeed. +var streamingTablePrivileges = []string{ + privilegeAllPrivileges, + "APPLY_TAG", + privilegeManage, + "MODIFY", + "READ_METADATA", + privilegeRefresh, + "SELECT", +} + +// A foreign table is read-only: its rows live in the federated source, so the +// DML trio and MODIFY cannot be granted on one. +// https://docs.databricks.com/aws/en/data-governance/unity-catalog/access-control/privileges-reference +var foreignTablePrivileges = slices.DeleteFunc(slices.Clone(tablePrivileges), func(privilege string) bool { + return slices.Contains([]string{"DELETE", "INSERT", "MODIFY", "UPDATE"}, privilege) +}) + +// anyTablePrivileges is for a table whose variant is not knowable. REFRESH is in +// it so a held one is not dropped, and Grant still refuses to ask for it: only a +// materialized view or a streaming table accepts that write. +var anyTablePrivileges = append(slices.Clone(tablePrivileges), privilegeRefresh) + +type tableBuilder struct { + securableOps + workspaces map[string]struct{} +} + +func newTableBuilder(client *databricks.Client, clientID string, workspaces map[string]struct{}, sync syncPrincipals) *tableBuilder { + return &tableBuilder{ + securableOps: securableOps{client: client, clientID: clientID, sync: sync, level: tableLevel(privilegesForTableType(""))}, + workspaces: workspaces, + } +} + +func (b *tableBuilder) ResourceType(_ context.Context) *v2.ResourceType { + return tableResourceType +} + +// tablePermissionsName: the permissions endpoint addresses a table by its dotted +// full name. The metastore is carried by the host. +func tablePermissionsName(resourceID string) (string, error) { + _, catalogName, schemaName, name, err := parseSchemaChildID(resourceID, "table") + if err != nil { + return "", err + } + + return strings.Join([]string{catalogName, schemaName, name}, schemaNameSeparator), nil +} + +func tableGrantsAreTrustworthy( + ctx context.Context, + client *databricks.Client, + trust securableTrust, + annos *annotations.Annotations, +) (bool, error) { + return schemaChildGrantsAreTrustworthy(ctx, client, trust, databricks.SecurableTable, annos) +} + +// tableLevel is built per table rather than declared once: table_type decides +// which privileges this one reports and accepts. See privilegesForTableType. +func tableLevel(privileges []string) securableLevel { + return securableLevel{ + securableType: databricks.SecurableTable, + noun: "table", + privileges: privileges, + writeRemedy: tableWriteRemedy, + trustRemedy: tableTrustRemedy, + permissionsName: tablePermissionsName, + trusts: tableGrantsAreTrustworthy, + // Only a code naming the table itself is proof. Dropping a parent does drop + // the table with it, but a workspace that cannot serve the catalog answers + // with the parent's code too, so those two are settled by reading the parent + // and then the table through that same workspace. + goneErrorCodes: []string{errorCodeTableGone}, + ambiguousGoneCodes: []string{errorCodeSchemaGone, errorCodeCatalogGone}, + confirmGone: tableIsGone, + } +} + +// tableIsGone confirms the parent schema through the same workspace before it +// believes a 404 that named a parent rather than the table. +func tableIsGone( + ctx context.Context, + client *databricks.Client, + fullName, workspace string, + annos *annotations.Annotations, +) (bool, error) { + return schemaChildIsGone(ctx, client, "table", fullName, workspace, annos, + func(ctx context.Context, workspace, fullName string) (*v2.RateLimitDescription, error) { + _, rateLimit, err := client.GetTable(ctx, workspace, fullName) + + return rateLimit, err + }) +} + +func tableResource( + table *databricks.Table, + metastoreID, catalogName, schemaName string, + parent *v2.ResourceId, + route schemaChildRoute, +) (*v2.Resource, error) { + fullName := strings.Join([]string{catalogName, schemaName, table.Name}, schemaNameSeparator) + profile := schemaChildProfile(metastoreID, catalogName, schemaName, fullName, table.Owner, securableTypeTable, route) + profile[profileKeyTableName] = table.Name + profile[profileKeyTableType] = table.TableType + + resourceID := schemaChildResourceID(metastoreID, catalogName, schemaName, table.Name) + + // The display name is the full name rather than the leaf: main.sales.orders + // and main.finance.orders would otherwise both read "orders" in C1. + return rs.NewResource( + fullName, + tableResourceType, + resourceID, + rs.WithResourceProfile(profile), + rs.WithParentResourceID(parent), + rs.WithAnnotation(&v2.RawId{Id: resourceID}), + ) +} + +// List pages the tables, views and materialized views of one schema. +func (b *tableBuilder) List(ctx context.Context, parentResourceID *v2.ResourceId, attr rs.SyncOpAttrs) ([]*v2.Resource, *rs.SyncOpResults, error) { + return listSchemaChildren(ctx, b.client, b.clientID, b.workspaces, tableResourceType, "table", parentResourceID, attr, + func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, pageToken string) ( + []*v2.Resource, string, *v2.RateLimitDescription, error) { + tables, next, rateLimit, err := b.client.ListTables(ctx, route.Workspace, catalogName, schemaName, pageToken, ResourcesPageSize) + if err != nil { + return nil, "", rateLimit, err + } + + var rv []*v2.Resource + for _, table := range tables { + if table.Name == "" { + continue + } + + built, err := tableResource(&table, metastoreID, catalogName, schemaName, parentResourceID, route) + if err != nil { + return nil, "", rateLimit, fmt.Errorf( + "databricks-connector: failed to build the resource for table %s.%s.%s: %w", catalogName, schemaName, table.Name, err) + } + rv = append(rv, built) + } + + return rv, next, rateLimit, nil + }) +} + +// isViewLike reports a view or a metric view. Both reject the table DML set, and +// the grants API rejects adding ALL_PRIVILEGES on either. +func isViewLike(tableType string) bool { + switch strings.ToUpper(strings.TrimSpace(tableType)) { + case tableTypeView, tableTypeMetricView: + return true + default: + return false + } +} + +// refreshIsRequestable reports the table types whose grants API accepts REFRESH. +// The privileges reference lists it on a materialized view, and a streaming table +// takes it too. On every other type, including one this connector does not name, +// a held REFRESH is still reported and the grant is not offered. +func refreshIsRequestable(tableType string) bool { + switch strings.ToUpper(strings.TrimSpace(tableType)) { + case tableTypeMaterializedView, tableTypeStreamingTable: + return true + default: + return false + } +} + +// privilegesForTableType returns the set for a known table_type. MANAGED, +// EXTERNAL and both shallow clones stay on the table set. A foreign table is +// read-only. Anything else, including a type Databricks adds later, gets the +// union, so a privilege already held is reported rather than dropped. +func privilegesForTableType(tableType string) []string { + if isViewLike(tableType) { + return viewPrivileges + } + + switch strings.ToUpper(strings.TrimSpace(tableType)) { + case tableTypeMaterializedView: + return materializedViewPrivileges + case tableTypeStreamingTable: + return streamingTablePrivileges + case tableTypeManaged, tableTypeExternal, tableTypeManagedShallowClone, tableTypeExternalShallowClone: + return tablePrivileges + case tableTypeForeign: + return foreignTablePrivileges + default: + return anyTablePrivileges + } +} + +// privilegesForTable is the set this table reports. A missing table_type falls +// back to the union rather than to one variant. +func privilegesForTable(ctx context.Context, resource *v2.Resource) []string { + variant, _ := rs.GetProfileStringValue(rs.GetProfile(resource), profileKeyTableType) + if variant == "" { + ctxzap.Extract(ctx).Debug("databricks-connector: table has no table_type; reporting every variant's privileges", + zap.String("table", resource.GetId().GetResource())) + + return anyTablePrivileges + } + + return privilegesForTableType(variant) +} + +// Entitlements are per table, not static: the privilege set follows table_type, +// and a privilege the grants API refuses must not be offered as requestable. +// C1 would otherwise advertise requests that always fail. +func (b *tableBuilder) Entitlements(ctx context.Context, resource *v2.Resource, _ rs.SyncOpAttrs) ([]*v2.Entitlement, *rs.SyncOpResults, error) { + variant, _ := rs.GetProfileStringValue(rs.GetProfile(resource), profileKeyTableType) + grantable := ent.WithGrantableTo(userResourceType, groupResourceType, servicePrincipalResourceType) + + privileges := privilegesForTable(ctx, resource) + rv := make([]*v2.Entitlement, 0, len(privileges)+1) + for _, privilege := range privileges { + options := []ent.EntitlementOption{ + ent.WithDisplayName(fmt.Sprintf("%s %s", resource.GetDisplayName(), privilege)), + ent.WithDescription(fmt.Sprintf("%s privilege on table %s in Databricks", privilege, resource.GetDisplayName())), + } + // Databricks rejects adding these three, so they are reported where a + // principal already holds them and are never requestable. + reportOnly := (privilege == privilegeAllPrivileges && isViewLike(variant)) || + (privilege == privilegeRefresh && !refreshIsRequestable(variant)) || + (privilege == "MODIFY" && strings.EqualFold(strings.TrimSpace(variant), tableTypeStreamingTable)) + if !reportOnly { + options = append([]ent.EntitlementOption{grantable}, options...) + } + rv = append(rv, ent.NewPermissionEntitlement(resource, privilege, options...)) + } + + rv = append(rv, ent.NewOwnershipEntitlement(resource, ownerEntitlement, + ent.WithDisplayName(fmt.Sprintf("%s owner", resource.GetDisplayName())), + ent.WithDescription(fmt.Sprintf("Owns table %s in Databricks", resource.GetDisplayName())), + )) + + return rv, 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 table. +func (b *tableBuilder) Grants(ctx context.Context, resource *v2.Resource, attr rs.SyncOpAttrs) ([]*v2.Grant, *rs.SyncOpResults, error) { + ctx = context.WithValue(ctx, syncSessionKey{}, attr.Session) + + return b.withLevel(tableLevel(privilegesForTable(ctx, resource))).syncGrants(ctx, resource, attr) +} + +func (b *tableBuilder) 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) || errors.Is(err, errSecurableGone) { + return annos, status.Errorf(codes.NotFound, "databricks-connector: table %s no longer exists", + entitlement.GetResource().GetId().GetResource()) + } + + return annos, err + } + + // The live table_type decides this, not the one the last sync wrote: a view + // replaced by a table takes privileges the recorded variant refuses. + resource := routed.GetResource() + if err := refuseUngrantableTablePrivilege(resource, routed); err != nil { + return annos, err + } + + writeAnnos, err := b.withLevel(tableLevel(privilegesForTable(ctx, resource))).grant(ctx, principal.GetId(), routed) + + return append(annos, writeAnnos...), err +} + +// refuseUngrantableTablePrivilege rejects the two privileges a table reports but +// the grants API refuses to add, before any PATCH goes out. Revoke is not held to +// this: a privilege SQL granted still has to be removable. +func refuseUngrantableTablePrivilege(resource *v2.Resource, entitlement *v2.Entitlement) error { + privilege, err := parseEntitlementPrivilege(entitlement.GetId()) + if err != nil { + return err + } + + variant, _ := rs.GetProfileStringValue(rs.GetProfile(resource), profileKeyTableType) + normalized := strings.ToUpper(strings.TrimSpace(variant)) + switch { + case privilege == privilegeAllPrivileges && isViewLike(variant): + return status.Errorf(codes.InvalidArgument, + "databricks-connector: the grants API rejects ALL_PRIVILEGES on a %s; grant SELECT or MANAGE instead", normalized) + case privilege == privilegeRefresh && !refreshIsRequestable(variant): + return status.Errorf(codes.InvalidArgument, + "databricks-connector: REFRESH can be granted on a materialized view or a streaming table, not on table type %q", normalized) + case privilege == "MODIFY" && normalized == tableTypeStreamingTable: + return status.Errorf(codes.InvalidArgument, + "databricks-connector: MODIFY on a streaming table is reported when already held; the grants API reference does not list it as grantable") + } + + return nil +} + +func (b *tableBuilder) 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) || errors.Is(err, errSecurableGone) { + annos.Update(&v2.GrantAlreadyRevoked{}) + + return annos, nil + } + + return annos, err + } + + writeAnnos, err := b.withLevel(tableLevel(privilegesForTable(ctx, routed.GetResource()))). + revoke(ctx, revoked.GetPrincipal().GetId(), routed) + + return append(annos, writeAnnos...), err +} + +// entitlementOnLiveRoute reads the table itself after its parents, because the +// owner decides whether the privilege list is complete and table_type decides +// which privileges the write may ask for. +func (b *tableBuilder) entitlementOnLiveRoute( + ctx context.Context, + entitlement *v2.Entitlement, + annos *annotations.Annotations, +) (*v2.Entitlement, error) { + return childEntitlementOnLiveRoute(ctx, b.client, b.clientID, b.workspaces, "table", entitlement, annos, + func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, name string, + parent *v2.ResourceId, annos *annotations.Annotations, + ) (*v2.Resource, error) { + fullName := strings.Join([]string{catalogName, schemaName, name}, schemaNameSeparator) + table, rateLimit, err := b.client.GetTable(ctx, route.Workspace, fullName) + noteRateLimit(annos, rateLimit) + if err != nil { + // liveChildRoute has just had this workspace serve the catalog and + // answer 200 for the schema, so a parent code here is a deletion + // between the two reads rather than a workspace that cannot route. + if databricks.IsSecurableGone(err, errorCodeTableGone, errorCodeSchemaGone, errorCodeCatalogGone) { + return nil, errSecurableGone + } + + return nil, refuseUnreadable(fmt.Sprintf( + "databricks-connector: failed to read table %s through workspace %s", fullName, route.Workspace), err) + } + + return tableResource(table, metastoreID, catalogName, schemaName, parent, route) + }) +} diff --git a/pkg/connector/volume.go b/pkg/connector/volume.go new file mode 100644 index 00000000..80e7ddb5 --- /dev/null +++ b/pkg/connector/volume.go @@ -0,0 +1,268 @@ +package connector + +import ( + "context" + "errors" + "fmt" + "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" + ent "github.com/conductorone/baton-sdk/pkg/types/entitlement" + rs "github.com/conductorone/baton-sdk/pkg/types/resource" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +var _ connectorbuilder.StaticEntitlementSyncerV2 = (*volumeBuilder)(nil) + +const ( + securableTypeVolume = "VOLUME" + + // errorCodeGenericGone is Databricks' generic 404 code, which a missing + // volume and a workspace that cannot serve one both answer with. + errorCodeGenericGone = "RESOURCE_DOES_NOT_EXIST" + + profileKeyVolumeName = "volume_name" + profileKeyVolumeType = "volume_type" + + volumeWriteRemedy = "the connector must own the metastore, the parent catalog, the parent schema or the volume, " + + "or hold MANAGE on the volume, the parent schema or the parent catalog" + + volumeTrustRemedy = "the connector's service principal must own the metastore, the parent catalog, the parent schema or the volume, " + + "hold MANAGE on the volume, the parent schema or the parent catalog, or be assigned Admin directly on the workspace whose " + + "admins group owns the parent catalog" +) + +// volumePrivileges is the set a volume takes: its files are read and written +// rather than queried, so none of the table DML applies. +// https://docs.databricks.com/aws/en/data-governance/unity-catalog/manage-privileges/privileges +var volumePrivileges = []string{ + privilegeAllPrivileges, + "APPLY_TAG", + privilegeManage, + "READ_METADATA", + "READ_VOLUME", + "WRITE_VOLUME", +} + +var volumeLevel = securableLevel{ + securableType: databricks.SecurableVolume, + noun: "volume", + privileges: volumePrivileges, + writeRemedy: volumeWriteRemedy, + trustRemedy: volumeTrustRemedy, + permissionsName: volumePermissionsName, + trusts: volumeGrantsAreTrustworthy, + // No code names a missing volume: Databricks never returns + // VOLUME_DOES_NOT_EXIST, and the generic code and both parent codes all come + // back from a workspace that cannot serve the catalog too. None of them is + // proof on its own, so every one is confirmed before it is believed. + ambiguousGoneCodes: []string{errorCodeGenericGone, errorCodeSchemaGone, errorCodeCatalogGone}, + confirmGone: volumeIsGone, +} + +// volumeIsGone confirms the parent schema through the same workspace and then +// reads the volume itself. The volume endpoint answers 200 while the volume +// exists, so a 404 from a workspace that has just served the parent is the +// volume being gone rather than one it cannot reach. +func volumeIsGone( + ctx context.Context, + client *databricks.Client, + fullName, workspace string, + annos *annotations.Annotations, +) (bool, error) { + return schemaChildIsGone(ctx, client, "volume", fullName, workspace, annos, + func(ctx context.Context, workspace, fullName string) (*v2.RateLimitDescription, error) { + _, rateLimit, err := client.GetVolume(ctx, workspace, fullName) + + return rateLimit, err + }) +} + +type volumeBuilder struct { + securableOps + workspaces map[string]struct{} +} + +func newVolumeBuilder(client *databricks.Client, clientID string, workspaces map[string]struct{}, sync syncPrincipals) *volumeBuilder { + return &volumeBuilder{ + securableOps: securableOps{client: client, clientID: clientID, sync: sync, level: volumeLevel}, + workspaces: workspaces, + } +} + +func (b *volumeBuilder) ResourceType(_ context.Context) *v2.ResourceType { + return volumeResourceType +} + +// volumePermissionsName: the permissions endpoint addresses a volume by its +// dotted full name. The metastore is carried by the host. +func volumePermissionsName(resourceID string) (string, error) { + _, catalogName, schemaName, name, err := parseSchemaChildID(resourceID, "volume") + if err != nil { + return "", err + } + + return strings.Join([]string{catalogName, schemaName, name}, schemaNameSeparator), nil +} + +func volumeGrantsAreTrustworthy( + ctx context.Context, + client *databricks.Client, + trust securableTrust, + annos *annotations.Annotations, +) (bool, error) { + return schemaChildGrantsAreTrustworthy(ctx, client, trust, databricks.SecurableVolume, annos) +} + +func volumeResource( + volume *databricks.Volume, + metastoreID, catalogName, schemaName string, + parent *v2.ResourceId, + route schemaChildRoute, +) (*v2.Resource, error) { + fullName := strings.Join([]string{catalogName, schemaName, volume.Name}, schemaNameSeparator) + profile := schemaChildProfile(metastoreID, catalogName, schemaName, fullName, volume.Owner, securableTypeVolume, route) + profile[profileKeyVolumeName] = volume.Name + profile[profileKeyVolumeType] = volume.VolumeType + + resourceID := schemaChildResourceID(metastoreID, catalogName, schemaName, volume.Name) + + // The display name is the full name rather than the leaf: main.sales.files + // and main.finance.files would otherwise both read "files" in C1. + return rs.NewResource( + fullName, + volumeResourceType, + resourceID, + rs.WithResourceProfile(profile), + rs.WithParentResourceID(parent), + rs.WithAnnotation(&v2.RawId{Id: resourceID}), + ) +} + +// List pages the volumes of one schema. +func (b *volumeBuilder) List(ctx context.Context, parentResourceID *v2.ResourceId, attr rs.SyncOpAttrs) ([]*v2.Resource, *rs.SyncOpResults, error) { + return listSchemaChildren(ctx, b.client, b.clientID, b.workspaces, volumeResourceType, "volume", parentResourceID, attr, + func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, pageToken string) ( + []*v2.Resource, string, *v2.RateLimitDescription, error) { + volumes, next, rateLimit, err := b.client.ListVolumes(ctx, route.Workspace, catalogName, schemaName, pageToken, ResourcesPageSize) + if err != nil { + return nil, "", rateLimit, err + } + + var rv []*v2.Resource + for _, volume := range volumes { + if volume.Name == "" { + continue + } + + built, err := volumeResource(&volume, metastoreID, catalogName, schemaName, parentResourceID, route) + if err != nil { + return nil, "", rateLimit, fmt.Errorf( + "databricks-connector: failed to build the resource for volume %s.%s.%s: %w", catalogName, schemaName, volume.Name, err) + } + rv = append(rv, built) + } + + return rv, next, rateLimit, nil + }) +} + +func (b *volumeBuilder) StaticEntitlements(_ context.Context, _ rs.SyncOpAttrs) ([]*v2.Entitlement, *rs.SyncOpResults, error) { + grantable := ent.WithGrantableTo(userResourceType, groupResourceType, servicePrincipalResourceType) + rv := make([]*v2.Entitlement, 0, len(volumePrivileges)+1) + for _, privilege := range volumePrivileges { + rv = append(rv, ent.NewPermissionEntitlement(nil, privilege, + grantable, + ent.WithDescription(fmt.Sprintf("%s privilege on a volume in Databricks", privilege)), + )) + } + + rv = append(rv, ent.NewOwnershipEntitlement(nil, ownerEntitlement, + ent.WithDescription("Owns a volume in Databricks"), + )) + + return rv, nil, nil +} + +func (b *volumeBuilder) 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 volume. +func (b *volumeBuilder) 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 *volumeBuilder) 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) || errors.Is(err, errSecurableGone) { + return annos, status.Errorf(codes.NotFound, "databricks-connector: volume %s no longer exists", + entitlement.GetResource().GetId().GetResource()) + } + + return annos, err + } + + writeAnnos, err := b.grant(ctx, principal.GetId(), routed) + + return append(annos, writeAnnos...), err +} + +func (b *volumeBuilder) 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) || errors.Is(err, errSecurableGone) { + annos.Update(&v2.GrantAlreadyRevoked{}) + + return annos, nil + } + + return annos, err + } + + writeAnnos, err := b.revoke(ctx, revoked.GetPrincipal().GetId(), routed) + + return append(annos, writeAnnos...), err +} + +// entitlementOnLiveRoute reads the volume itself after its parents, because its +// owner is one of the four the trust check short-circuits on. liveChildRoute has +// just had this workspace serve the catalog and answer 200 for the schema, so a +// 404 here — generic or naming a parent — is the volume being gone rather than a +// workspace that cannot route to it. +func (b *volumeBuilder) entitlementOnLiveRoute( + ctx context.Context, + entitlement *v2.Entitlement, + annos *annotations.Annotations, +) (*v2.Entitlement, error) { + return childEntitlementOnLiveRoute(ctx, b.client, b.clientID, b.workspaces, "volume", entitlement, annos, + func(ctx context.Context, route schemaChildRoute, metastoreID, catalogName, schemaName, name string, + parent *v2.ResourceId, annos *annotations.Annotations, + ) (*v2.Resource, error) { + fullName := strings.Join([]string{catalogName, schemaName, name}, schemaNameSeparator) + volume, rateLimit, err := b.client.GetVolume(ctx, route.Workspace, fullName) + noteRateLimit(annos, rateLimit) + if err != nil { + if databricks.IsSecurableGone(err, errorCodeGenericGone, errorCodeSchemaGone, errorCodeCatalogGone) { + return nil, errSecurableGone + } + + return nil, refuseUnreadable(fmt.Sprintf( + "databricks-connector: failed to read volume %s through workspace %s", fullName, route.Workspace), err) + } + + return volumeResource(volume, metastoreID, catalogName, schemaName, parent, route) + }) +} diff --git a/pkg/databricks/models.go b/pkg/databricks/models.go index c139c5a6..b2107798 100644 --- a/pkg/databricks/models.go +++ b/pkg/databricks/models.go @@ -193,6 +193,24 @@ type Schema struct { FullName string `json:"full_name"` } +type Table struct { + Name string `json:"name"` + Owner string `json:"owner"` + TableType string `json:"table_type"` + // FullName is the dotted "catalog.schema.table" Databricks addresses the + // table by. A single read is checked against it. + FullName string `json:"full_name"` +} + +type Volume struct { + Name string `json:"name"` + Owner string `json:"owner"` + VolumeType string `json:"volume_type"` + // FullName is the dotted "catalog.schema.volume" Databricks addresses the + // volume by. A single read is checked against it. + FullName string `json:"full_name"` +} + type PrivilegeAssignment struct { Principal string `json:"principal"` PrincipalID json.Number `json:"principal_id"` @@ -239,6 +257,16 @@ type schemasResponse struct { NextPageToken string `json:"next_page_token"` } +type tablesResponse struct { + Tables []Table `json:"tables"` + NextPageToken string `json:"next_page_token"` +} + +type volumesResponse struct { + Volumes []Volume `json:"volumes"` + NextPageToken string `json:"next_page_token"` +} + type permissionsResponse struct { PrivilegeAssignments []PrivilegeAssignment `json:"privilege_assignments"` NextPageToken string `json:"next_page_token"` diff --git a/pkg/databricks/unity_catalog.go b/pkg/databricks/unity_catalog.go index cbe7b831..1931d5ed 100644 --- a/pkg/databricks/unity_catalog.go +++ b/pkg/databricks/unity_catalog.go @@ -26,6 +26,12 @@ const ( // https://docs.databricks.com/api/workspace/schemas/list unityCatalogSchemasEndpoint = "/api/2.1/unity-catalog/schemas" + // https://docs.databricks.com/api/workspace/tables/list + unityCatalogTablesEndpoint = "/api/2.1/unity-catalog/tables" + + // https://docs.databricks.com/api/workspace/volumes/list + unityCatalogVolumesEndpoint = "/api/2.1/unity-catalog/volumes" + // 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" @@ -41,10 +47,15 @@ const ( SecurableMetastore = "metastore" SecurableCatalog = "catalog" SecurableSchema = "schema" + SecurableTable = "table" + SecurableVolume = "volume" // The permissions endpoint rejects any max_results from 1 to 149 with a 400. // Zero selects the paginated response that replaces the unpaginated form. permissionsMaxResults uint = 0 + + // The tables endpoint rejects a max_results above this ceiling. + unityCatalogTablesMaxResults uint = 50 ) // ListMetastores (GET /api/2.0/accounts/{account_id}/metastores). Not paginated. @@ -124,6 +135,80 @@ func (c *Client) ListCatalogs( return res.Catalogs, res.NextPageToken, ratelimitData, nil } +// GetVolume (GET /api/2.1/unity-catalog/volumes/{full_name}) reads one volume +// through workspaceId, which is a deployment name. The permissions endpoint +// answers a missing volume with the generic RESOURCE_DOES_NOT_EXIST, which an +// unreachable workspace also answers, so this read is what separates the two: +// measured on a live tenant it returns 200 for a volume that exists and 404 for +// one that does not, and it names SCHEMA_DOES_NOT_EXIST when the parent is what +// is missing. +func (c *Client) GetVolume( + ctx context.Context, + workspaceId, fullName string, +) ( + *Volume, + *v2.RateLimitDescription, + error, +) { + var res Volume + + if fullName == "" { + return nil, nil, invalidArgument("volume full name is required") + } + + u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogVolumesEndpoint, fullName) + if !addressesSecurable(u, "/"+fullName) { + return nil, nil, invalidArgument("cannot address volume %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 volume %s: %w", fullName, err)) + } + + if res.FullName != fullName { + return nil, ratelimitData, invalidArgument("asked Databricks for volume %q and it answered with %q", fullName, res.FullName) + } + + return &res, ratelimitData, nil +} + +// GetTable (GET /api/2.1/unity-catalog/tables/{full_name}) reads one table +// through workspaceId, which is a deployment name. It answers the two things a +// write needs and the listing cannot be trusted to still hold: the owner, which +// decides whether the privilege list is complete, and table_type, which decides +// which privileges the table takes. +func (c *Client) GetTable( + ctx context.Context, + workspaceId, fullName string, +) ( + *Table, + *v2.RateLimitDescription, + error, +) { + var res Table + + if fullName == "" { + return nil, nil, invalidArgument("table full name is required") + } + + u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogTablesEndpoint, fullName) + if !addressesSecurable(u, "/"+fullName) { + return nil, nil, invalidArgument("cannot address table %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 table %s: %w", fullName, err)) + } + + if res.FullName != fullName { + return nil, ratelimitData, invalidArgument("asked Databricks for table %q and it answered with %q", fullName, res.FullName) + } + + return &res, ratelimitData, nil +} + // GetCatalog (GET /api/2.1/unity-catalog/catalogs/{name}) reads one catalog // through workspaceId, which is a deployment name. It answers what draining // ListCatalogs cannot: a 404 naming CATALOG_DOES_NOT_EXIST is the catalog not @@ -193,9 +278,13 @@ func (c *Client) ListSchemas( } // 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. +// through workspaceId, which is a deployment name. The full name is dotted. It +// separates the two answers draining ListSchemas runs together: a 404 naming +// SCHEMA_DOES_NOT_EXIST is Databricks naming the schema missing, and any other +// refusal, 403 among them, is this workspace not serving it. Which of the two a +// named 404 is belongs to the caller. An answer that names another schema, or +// none at all, is refused: its owner would otherwise be read as this schema's, +// and that owner decides whether a privilege list is complete. func (c *Client) GetSchema( ctx context.Context, workspaceId, fullName string, @@ -220,13 +309,78 @@ func (c *Client) GetSchema( return nil, ratelimitData, nameWorkspace403Remedy(workspaceId, fmt.Errorf("failed to read schema %s: %w", fullName, err)) } - if res.FullName != "" && res.FullName != fullName { + if res.FullName != fullName { return nil, ratelimitData, invalidArgument("asked Databricks for schema %q and it answered with %q", fullName, res.FullName) } return &res, ratelimitData, nil } +// ListTables (GET /api/2.1/unity-catalog/tables?catalog_name=&schema_name=) pages +// the tables, views and materialized views in a schema. schema_name is mandatory, +// and a max_results above the endpoint's ceiling of 50 is clamped rather than sent. +func (c *Client) ListTables( + ctx context.Context, + workspaceId, catalogName, schemaName, pageToken string, + maxResults uint, +) ( + []Table, + string, + *v2.RateLimitDescription, + error, +) { + if maxResults > unityCatalogTablesMaxResults { + maxResults = unityCatalogTablesMaxResults + } + + var res tablesResponse + + u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogTablesEndpoint) + ratelimitData, err := c.Get(ctx, u, &res, &unityCatalogVars{ + catalogName: catalogName, + schemaName: schemaName, + maxResults: &maxResults, + pageToken: pageToken, + // Without this the listing carries every column and property of every + // table, which is the bulk of the response and none of it is read here. + omitTablePayload: true, + }) + if err != nil { + return nil, "", ratelimitData, nameWorkspace403Remedy(workspaceId, + fmt.Errorf("failed to list tables in schema %s.%s: %w", catalogName, schemaName, err)) + } + + return res.Tables, res.NextPageToken, ratelimitData, nil +} + +// ListVolumes (GET /api/2.1/unity-catalog/volumes?catalog_name=&schema_name=) pages a schema's volumes. +func (c *Client) ListVolumes( + ctx context.Context, + workspaceId, catalogName, schemaName, pageToken string, + maxResults uint, +) ( + []Volume, + string, + *v2.RateLimitDescription, + error, +) { + var res volumesResponse + + u := c.workspaceUrl(workspaceId).JoinPath(unityCatalogVolumesEndpoint) + ratelimitData, err := c.Get(ctx, u, &res, &unityCatalogVars{ + catalogName: catalogName, + schemaName: schemaName, + maxResults: &maxResults, + pageToken: pageToken, + }) + if err != nil { + return nil, "", ratelimitData, nameWorkspace403Remedy(workspaceId, + fmt.Errorf("failed to list volumes in schema %s.%s: %w", catalogName, schemaName, err)) + } + + return res.Volumes, res.NextPageToken, 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 diff --git a/pkg/databricks/unity_catalog_test.go b/pkg/databricks/unity_catalog_test.go index 856771a3..a0783b18 100644 --- a/pkg/databricks/unity_catalog_test.go +++ b/pkg/databricks/unity_catalog_test.go @@ -6,6 +6,9 @@ import ( "io" "net/http" "net/http/httptest" + "net/url" + "reflect" + "strconv" "testing" v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" @@ -95,6 +98,43 @@ func TestUpdatePermissionsDrainsFromPatchToken(t *testing.T) { } } +// omit_username is deliberately absent: it also drops owner, and the drop is +// silent — the response still parses and every owner simply becomes empty. The +// exact-set assertion is what makes adding it fail here. +func TestListTablesSendsOnlyTheOmitColumnsAndPropertiesPayloadVars(t *testing.T) { + t.Setenv("BATON_HTTP_CACHE_TTL", "0") + + var query url.Values + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + query = r.URL.Query() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(tablesResponse{Tables: []Table{{Name: "t"}}}) + })) + t.Cleanup(srv.Close) + + client := srv.Client() + client.Transport = rewriteHost(srv.Listener.Addr().String(), client.Transport) + c, err := NewClient(context.Background(), client, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acc-1", srv.URL, &NoAuth{}, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + + if _, _, _, err := c.ListTables(context.Background(), "ws", "main", "default", "", unityCatalogTablesMaxResults); err != nil { + t.Fatalf("ListTables: %v", err) + } + + want := url.Values{ + "catalog_name": []string{"main"}, + "schema_name": []string{"default"}, + "max_results": []string{strconv.FormatUint(uint64(unityCatalogTablesMaxResults), 10)}, + "omit_columns": []string{"true"}, + "omit_properties": []string{"true"}, + } + if !reflect.DeepEqual(query, want) { + t.Fatalf("query = %v, want exactly %v", query, want) + } +} + func TestListCatalogsCanIncludeUnboundCatalogs(t *testing.T) { t.Setenv("BATON_HTTP_CACHE_TTL", "0") var includeUnbound string @@ -180,6 +220,63 @@ func TestGetCatalogRefusesAMismatchedAnswer(t *testing.T) { } } +// A schema read addresses one securable by its dotted full name. The same URL +// check GetCatalog makes applies: a name holding "?", "#" or "%" would address +// a different schema, and its owner is what decides whether the connector can +// list every table and volume under it. +func TestGetSchemaRefusesANameThatChangesTheURLOrAMismatchedAnswer(t *testing.T) { + t.Setenv("BATON_HTTP_CACHE_TTL", "0") + + var requested []string + var answer any = Schema{Name: "other", FullName: "main.other", Owner: "eng"} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requested = append(requested, r.URL.Path) + _ = json.NewEncoder(w).Encode(answer) + })) + t.Cleanup(srv.Close) + + client := srv.Client() + client.Transport = rewriteHost(srv.Listener.Addr().String(), client.Transport) + c, err := NewClient(context.Background(), client, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acc-1", srv.URL, &NoAuth{}, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + + for _, fullName := range []string{"main.sales?x", "main.sales#x", "main.sales%x", ""} { + got, _, err := c.GetSchema(context.Background(), "ws", fullName) + if err == nil { + t.Fatalf("GetSchema(%q) returned schema %+v, want an error", fullName, got) + } + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("GetSchema(%q) returned %v, want InvalidArgument", fullName, status.Code(err)) + } + } + if len(requested) != 0 { + t.Fatalf("GetSchema sent %v, want no request at all", requested) + } + + // An answer about another schema does not describe the one asked for. Neither + // does one that names no schema at all: its owner would still be read as this + // schema's, and that owner decides whether the children listing is complete. + for _, body := range []any{ + Schema{Name: "other", FullName: "main.other", Owner: "eng"}, + map[string]any{"name": "sales", "owner": "eng"}, + } { + answer = body + requested = nil + got, _, err := c.GetSchema(context.Background(), "ws", "main.sales") + if err == nil { + t.Fatalf("GetSchema returned schema %+v for answer %+v, want an error", got, body) + } + if status.Code(err) != codes.InvalidArgument { + t.Fatalf("GetSchema returned %v for answer %+v, want InvalidArgument", status.Code(err), body) + } + if want := []string{"/api/2.1/unity-catalog/schemas/main.sales"}; !reflect.DeepEqual(requested, want) { + t.Fatalf("GetSchema requested %v, want %v", requested, want) + } + } +} + type hostRewriter struct { host http.RoundTripper addr string diff --git a/pkg/databricks/vars.go b/pkg/databricks/vars.go index 6fac93ad..04634dcd 100644 --- a/pkg/databricks/vars.go +++ b/pkg/databricks/vars.go @@ -174,10 +174,15 @@ func NewNameVars(name string, etag string) *NameVars { // maxResults is a pointer: its presence is the signal. type unityCatalogVars struct { catalogName string + schemaName string principal string maxResults *uint pageToken string includeUnbound bool + + // omit_username is deliberately not sent alongside these: it also removes + // owner, which every securable's profile and its owner grant depend on. + omitTablePayload bool } func (v *unityCatalogVars) Apply(params *url.Values) { @@ -185,6 +190,10 @@ func (v *unityCatalogVars) Apply(params *url.Values) { params.Add("catalog_name", v.catalogName) } + if v.schemaName != "" { + params.Add("schema_name", v.schemaName) + } + if v.principal != "" { params.Add("principal", v.principal) } @@ -199,4 +208,9 @@ func (v *unityCatalogVars) Apply(params *url.Values) { if v.includeUnbound { params.Set("include_unbound", "true") } + + if v.omitTablePayload { + params.Add("omit_columns", "true") + params.Add("omit_properties", "true") + } }