diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ddd90691..89aab7da 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -72,3 +72,61 @@ jobs: run: | ./baton-databricks --invoke-action=enable_user \ --invoke-action-args="$(jq -nc --arg id "${TEST_ACTION_USER_ID}" '{user_id: $id}')" + # Runs the incremental sync event feed against the local test server (test-server/), so it + # needs no Databricks account or secrets and also runs on pull requests from forks. + test-server: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + - name: Install Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + - name: Build connector and test server + run: | + go build -o baton-databricks ./cmd/baton-databricks + go build -o /tmp/databricks-test-server ./test-server + - name: Start test server + run: | + /tmp/databricks-test-server --ca-out /tmp/test-server-ca.pem > test-server.log 2>&1 & + for i in $(seq 1 30); do + if curl -sf --cacert /tmp/test-server-ca.pem https://localhost:8765/health > /dev/null; then + echo "test server is up"; exit 0 + fi + sleep 1 + done + echo "test server did not come up in time"; cat test-server.log; exit 1 + - name: Run incremental sync against the test server + env: + SSL_CERT_FILE: /tmp/test-server-ca.pem + run: | + ./baton-databricks \ + --hostname localhost:8765 --account-hostname localhost:8765 \ + --account-id test-account \ + --databricks-client-id test-client --databricks-client-secret test-secret \ + --sql-warehouse-id wh-serverless \ + --event-feed true --event-feed-id databricks_audit_log \ + --event-feed-start-at "$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%SZ)" \ + > events.jsonl + - name: Compare events with the expected output + run: | + normalize() { jq -c -S 'del(.occurredAt)' "$1" | sort; } + diff <(normalize test-server/testdata/expected-events.jsonl) <(normalize events.jsonl) + - name: Check the cold-start timeout message + env: + SSL_CERT_FILE: /tmp/test-server-ca.pem + run: | + if ./baton-databricks \ + --hostname localhost:8765 --account-hostname localhost:8765 \ + --account-id test-account \ + --databricks-client-id test-client --databricks-client-secret test-secret \ + --sql-warehouse-id wh-broken \ + --event-feed true --event-feed-id databricks_audit_log \ + --event-feed-start-at "$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%SZ)" 2> err.log; then + echo "expected the event feed to fail with a broken warehouse"; exit 1 + fi + grep -q "has not started" err.log + - name: Show test server log on failure + if: failure() + run: cat test-server.log diff --git a/.gitignore b/.gitignore index b2118062..e9ac02eb 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ # Dependency directories (remove the comment below to include it) # vendor/ dist/ + +# CA certificate written by the local test server (test-server/) +test-server-ca.pem diff --git a/README.md b/README.md index 371bbe5e..edb311fa 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,87 @@ To instead exclude specific workspaces from the sync, pass them to the list. Each entry can be a workspace name, deployment name, or numeric workspace ID. Excluded workspaces and their roles are skipped entirely. +## Incremental sync + +By default, `baton-databricks` does a full resync of every resource on every run. +You can opt into an additional, cheap pathway that polls a Databricks audit log +between full syncs to pick up access changes early. Full syncs still run as the +correctness backstop. Incremental sync picks up added and removed group +memberships, but deleted users, groups and service principals are only caught +by the next full sync. + +Role assignments that Databricks stores in access-control rule sets (group roles +such as `roles/group.manager`, service principal roles, and the account +`marketplace.admin` role) are also only caught by the next full sync: the +connector does not read the audit events Databricks writes for rule-set +changes. A `roles/group.manager` change, for example, is logged as +`updateRuleSet` under the `accountsAccessControl` audit service, which the +connector does not query. + +**Incremental sync is enabled by setting `--sql-warehouse-id` (or +`BATON_SQL_WAREHOUSE_ID`) and disabled by leaving it unset or empty.** There is +no separate on/off flag. The incremental-sync setup (warehouse found, +`system.access.audit` queryable, at least one workspace in sync scope) is not +checked at startup, so a misconfiguration never blocks full syncs or +provisioning. Instead, each event-feed poll fails with an error naming the +problem until it is fixed. + +Incremental sync requires a reachable Account API to resolve audit events back +to synced resources, same as the rest of the connector. Audit events are only +resolved for workspaces in sync scope, so `--workspaces` and +`--databricks-exclude-workspaces` apply to incremental sync the same way they +apply to full syncs. + +### Requirements + +Incremental sync works only when all of the following are true: + +- **Unity Catalog.** The SQL warehouse is in a workspace enabled for Unity + Catalog, and the metastore is on Unity Catalog Privilege Model Version 1.0 + ([system tables + requirements](https://docs.databricks.com/aws/en/admin/system-tables/)). +- **System tables.** The connector queries the `system.access.audit` system + table, which Databricks currently offers as a Public Preview. +- **A SQL warehouse, preferably serverless.** Pass its ID with + `--sql-warehouse-id`. Any warehouse works, including the **Starter + Warehouse** Databricks creates in each workspace, so you don't need to create + one. +- **Grants for the service principal** the connector authenticates as, on top of + the Account admin role it already needs: + - `USE CATALOG` on the `system` catalog + - `USE SCHEMA` and `SELECT` on the `system.access` schema + - `CAN USE` on the SQL warehouse + + For example, run as a metastore admin, replacing `` with the + service principal's application (client) ID: + + ```sql + GRANT USE CATALOG ON CATALOG system TO ``; + GRANT USE SCHEMA, SELECT ON SCHEMA system.access TO ``; + ``` + +**We recommend a serverless SQL warehouse.** It starts in seconds, while a pro +or classic warehouse can take several minutes. Each statement gets up to 30 +seconds on the initial request, including warehouse startup, then up to 5 more +minutes of polling. A statement still unfinished after that is cancelled, so a +poll can take close to 6 minutes before it fails with a `DeadlineExceeded` +error and is retried on the next poll. Serverless SQL warehouses require the +Premium plan or above. + +**Incremental sync covers one cloud region.** `system.access.audit` holds +workspace-level events only for workspaces in the same cloud region as the +workspace that queries it; account-level events are global ([system tables +reference](https://docs.databricks.com/aws/en/admin/system-tables/)). The +connector finds the warehouse's workspace automatically by checking each +workspace the service principal can access, except those excluded with +`--databricks-exclude-workspaces`; the `--workspaces` allowlist does not limit +this search. It receives +incremental updates only for workspaces in that region. Workspaces in other +regions are still covered by full syncs. + +Audit log entries are delivered with a delay, so the connector reads them about +four hours after they happen. + ## Group provisioning Account groups are provisioned through the OAuth client ID and secret flow. @@ -175,6 +256,7 @@ Flags: -p, --provisioning This must be set in order for provisioning actions to be enabled ($BATON_PROVISIONING) --skip-entitlements-and-grants This must be set to skip syncing of entitlements and grants ($BATON_SKIP_ENTITLEMENTS_AND_GRANTS) --skip-full-sync This must be set to skip a full sync ($BATON_SKIP_FULL_SYNC) + --sql-warehouse-id string Setting this enables incremental sync; leaving it empty disables it. ID of the Databricks SQL warehouse used to query the system.access.audit log between full syncs, so access changes show up before the next full sync (deleted users, groups and service principals are still only caught by full syncs). The warehouse can be in any workspace not excluded by databricks-exclude-workspaces, in the same cloud region as the workspaces to update incrementally; Databricks only exposes workspace-level audit events for that region. The connector discovers the warehouse's workspace automatically. ($BATON_SQL_WAREHOUSE_ID) --storage-engine string The storage engine to use when opening the sync c1z file: sqlite or pebble. Defaults to pebble when unset. ($BATON_STORAGE_ENGINE) --sync-resource-types strings The resource type IDs to sync ($BATON_SYNC_RESOURCE_TYPES) --sync-resources strings The resource IDs to sync ($BATON_SYNC_RESOURCES) diff --git a/baton_capabilities.json b/baton_capabilities.json index 505f375a..e88eb416 100644 --- a/baton_capabilities.json +++ b/baton_capabilities.json @@ -8,6 +8,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -22,6 +23,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -36,6 +38,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -50,6 +53,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -69,6 +73,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_ACCOUNT_PROVISIONING", "CAPABILITY_RESOURCE_DELETE" ], @@ -84,6 +89,7 @@ }, "capabilities": [ "CAPABILITY_SYNC", + "CAPABILITY_TARGETED_SYNC", "CAPABILITY_PROVISION" ], "permissions": {} @@ -94,7 +100,10 @@ "CAPABILITY_SYNC", "CAPABILITY_ACCOUNT_PROVISIONING", "CAPABILITY_RESOURCE_DELETE", - "CAPABILITY_ACTIONS" + "CAPABILITY_ACTIONS", + "CAPABILITY_TARGETED_SYNC", + "CAPABILITY_EVENT_FEED_V2", + "CAPABILITY_SERVICE_MODE_TARGETED_SYNC" ], "credentialDetails": { "capabilityAccountProvisioning": { diff --git a/config_schema.json b/config_schema.json index e387c1ed..65d90702 100644 --- a/config_schema.json +++ b/config_schema.json @@ -151,6 +151,12 @@ "displayName": "Exclude Workspaces", "description": "Workspaces to exclude from sync, identified by workspace name, deployment name, or numeric workspace ID. Mutually exclusive with workspaces.", "stringSliceField": {} + }, + { + "name": "sql-warehouse-id", + "displayName": "SQL Warehouse ID", + "description": "Setting this enables incremental sync; leaving it empty disables it. ID of the Databricks SQL warehouse used to query the system.access.audit log between full syncs, so access changes show up before the next full sync (deleted users, groups and service principals are still only caught by full syncs). The warehouse can be in any workspace not excluded by databricks-exclude-workspaces, in the same cloud region as the workspaces to update incrementally; Databricks only exposes workspace-level audit events for that region. The connector discovers the warehouse's workspace automatically.", + "stringField": {} } ], "constraints": [ diff --git a/docs/connector.mdx b/docs/connector.mdx index ea607b91..cf2f5f51 100644 --- a/docs/connector.mdx +++ b/docs/connector.mdx @@ -48,25 +48,85 @@ These actions act on the account-level user, so disabling a user blocks them in The connector authenticates with **OAuth** — an account-level service principal's client ID and secret. This is the only authentication method the connector supports. +### Optional: faster updates between syncs + +By default, the Databricks connector picks up access changes on its regular sync schedule. You can optionally turn on incremental sync, which checks Databricks' activity log between full syncs so that changes like new group members, new service principals, and admin role changes on service principals show up in C1 sooner. Full syncs still run as usual and remain the source of truth. Removed group memberships are picked up incrementally too, but deleted users, groups, and service principals are only reflected after the next full sync. + +Role assignments that Databricks stores in access-control rule sets are also only reflected after the next full sync. These are group roles such as group manager, service principal roles, and the account `marketplace.admin` role. + +Incremental sync is turned on by providing the ID of a Databricks SQL warehouse (the **SQL Warehouse ID** setting, `BATON_SQL_WAREHOUSE_ID`) and turned off by leaving it empty — there is no separate on/off switch. Ask your connector operator or C1 support contact to enable it for you. + +#### Incremental sync requirements + +Your Databricks account must meet all of the following: + +- **Unity Catalog.** The SQL warehouse must be in a workspace enabled for Unity Catalog, and the metastore must be on Unity Catalog Privilege Model Version 1.0. Databricks enables most workspaces created after November 2023 for Unity Catalog automatically. +- **System tables.** The connector reads Databricks' audit log system table, `system.access.audit`. Databricks currently offers this table as a Public Preview. +- **A SQL warehouse, preferably serverless.** You don't need to create a new one: Databricks creates a **Starter Warehouse** in each workspace automatically, and any SQL warehouse works. See the recommendation below about the warehouse type. +- **Permissions for the connector's service principal**, in addition to the **Account admin** role it already needs: + - `USE CATALOG` on the `system` catalog + - `USE SCHEMA` and `SELECT` on the `system.access` schema + - **Can use** on the SQL warehouse + + +**We recommend a serverless SQL warehouse.** It starts in seconds, while a pro or classic warehouse can take several minutes to start. The connector waits up to about 6 minutes for the warehouse to start and each query to finish, so a slower start can delay updates until the next one. Serverless SQL warehouses require the Premium plan or above. + + + +**Incremental sync covers one cloud region.** Databricks keeps workspace activity in the audit log of the region where each workspace is deployed. The connector only receives incremental updates for workspaces in the same region as the SQL warehouse. Workspaces in other regions are still updated by full syncs. + + +#### Set up incremental sync + + +A Databricks user with the **Account admin** role, and the **Metastore admin** role or the right to grant access to the `system` catalog, must perform this task. + + + + + Choose a SQL warehouse in a Unity Catalog-enabled workspace, in the same region as the workspaces you want to update incrementally. In that workspace, go to **SQL Warehouses**, open the warehouse, and copy its ID. Check its type: if it isn't **Serverless**, switch it to serverless if your plan allows it (see the recommendation above). + + + On the **SQL Warehouses** page, click the kebab menu (three-dot icon) next to the warehouse, click **Permissions**, and give the connector's service principal the **Can use** permission. + + + In the same workspace, run the following in the SQL editor, replacing `` with the service principal's application (client) ID: + + ```sql + GRANT USE CATALOG ON CATALOG system TO ``; + GRANT USE SCHEMA, SELECT ON SCHEMA system.access TO ``; + ``` + + + Enter the warehouse ID in the connector's **SQL Warehouse ID** setting (`BATON_SQL_WAREHOUSE_ID`). + + + +The SQL warehouse can live in any workspace in that region that is not listed in **Exclude Workspaces**, including a workspace outside **Workspaces** — the connector finds it automatically. **Workspaces** and **Exclude Workspaces** also limit which workspaces incremental sync updates, as they do for full syncs. Changes reach C1 roughly four hours after they happen: Databricks delivers audit log entries with a delay, so the connector waits before reading them. + + +The incremental sync setup isn't checked when the connector starts, so a problem with it never blocks full syncs or provisioning. If something is missing, such as a permission or a warehouse that can't be found, every incremental update fails and the connector logs an error that names the cause until you fix it. + + ## Gather Databricks credentials Configuring the connector requires you to pass in credentials generated in Databricks. Gather these credentials before you move on. -A user with the **Account admin** role in each Databricks workspace you want to sync must perform this task. +A user with the **Account admin** role in your Databricks account must perform this task. Account admin is an account-level role, managed in the Databricks account console. ### Look up your Databricks account ID - Ensure that your Databricks user account has the **Account admin** role and is assigned to each Databricks workspace you want to sync to C1. + Log in to the Databricks account console with a user that has the **Account admin** role. In the Databricks account console, open the menu that appears next to your username in the upper right corner. - Carefully and copy and save account ID. + Carefully copy and save the account ID. @@ -81,6 +141,9 @@ The Databricks connector authenticates with OAuth, which syncs info from all Dat Carefully copy and save the OAuth client ID and secret. + + Give the service principal the **Account admin** role: in the account console, go to **User management** > **Service principals**, click the service principal, and on the **Roles** tab select **Account admin**. Databricks requires this role for any service principal that calls account-level APIs, and the connector fails validation without it. + **Done.** Here's the set of credentials you'll need when setting up the connector: @@ -214,7 +277,7 @@ stringData: BATON_CLIENT_ID: BATON_CLIENT_SECRET: - # Databricks account ID (required for both credential options below) + # Databricks account ID (required) BATON_ACCOUNT_ID: # Databricks credentials: OAuth @@ -229,7 +292,11 @@ stringData: # Optional: exclude specific workspaces from the sync # (workspace name, deployment name, or numeric ID). # Mutually exclusive with BATON_WORKSPACES — set one or the other, never both. - BATON_DATABRICKS_EXCLUDE_WORKSPACES: + # BATON_DATABRICKS_EXCLUDE_WORKSPACES: + + # Optional: setting this enables incremental sync; leave it unset to disable it. + # ID of the SQL warehouse used to query the system.access.audit log between full syncs. + # BATON_SQL_WAREHOUSE_ID: # Optional: include if you want C1 to provision access using this connector BATON_PROVISIONING: true diff --git a/go.mod b/go.mod index 552c091e..cd9c2148 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.27.4 require ( github.com/conductorone/baton-sdk v0.46.0 github.com/ennyjfrick/ruleguard-logfatal v0.0.2 + github.com/google/uuid v1.6.0 github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 github.com/quasilyte/go-ruleguard/dsl v0.3.23 github.com/stretchr/testify v1.12.1 @@ -66,7 +67,6 @@ require ( github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/golang/snappy v1.0.0 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.33.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jellydator/ttlcache/v3 v3.4.1 // indirect diff --git a/pkg/config/conf.gen.go b/pkg/config/conf.gen.go index dd2a3bba..7094ed29 100644 --- a/pkg/config/conf.gen.go +++ b/pkg/config/conf.gen.go @@ -12,6 +12,7 @@ type Databricks struct { Workspaces []string `mapstructure:"workspaces"` BaseUrl string `mapstructure:"base-url"` DatabricksExcludeWorkspaces []string `mapstructure:"databricks-exclude-workspaces"` + SqlWarehouseId string `mapstructure:"sql-warehouse-id"` } func (c *Databricks) findFieldByTag(tagValue string) (any, bool) { diff --git a/pkg/config/config.go b/pkg/config/config.go index 35afe969..900f0e8d 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -54,6 +54,20 @@ var ( field.WithDescription("Workspaces to exclude from sync, identified by workspace name, deployment name, or numeric workspace ID. Mutually exclusive with workspaces."), field.WithDisplayName("Exclude Workspaces"), ) + // SQLWarehouseIDField doubles as the incremental-sync switch: set enables it, empty disables it. + // system.access.audit only has workspace-level events from the warehouse's region, so the + // warehouse must share a region with the workspaces incremental sync should cover. + SQLWarehouseIDField = field.StringField( + "sql-warehouse-id", + field.WithDescription( + "Setting this enables incremental sync; leaving it empty disables it. "+ + "ID of the Databricks SQL warehouse used to query the system.access.audit log between full syncs, "+ + "so access changes show up before the next full sync (deleted users, groups and service principals are still only caught by full syncs). "+ + "The warehouse can be in any workspace not excluded by databricks-exclude-workspaces, in the same cloud region as the workspaces to update incrementally; "+ + "Databricks only exposes workspace-level audit events for that region. The connector discovers the warehouse's workspace automatically.", + ), + field.WithDisplayName("SQL Warehouse ID"), + ) configFields = []field.SchemaField{ AccountHostnameField, AccountIdField, @@ -63,6 +77,7 @@ var ( WorkspacesField, BaseURLField, ExcludeWorkspacesField, + SQLWarehouseIDField, } ) diff --git a/pkg/connector/account.go b/pkg/connector/account.go index 3684ed45..c2726501 100644 --- a/pkg/connector/account.go +++ b/pkg/connector/account.go @@ -219,6 +219,20 @@ func (a *accountBuilder) Grant(ctx context.Context, principal *v2.Resource, enti return nil, nil } +// Get returns the singleton account resource, used to re-sync it after a RESOURCE_CHANGE event. +func (a *accountBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + resource, err := a.accountResource(ctx) + if err != nil { + return nil, nil, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed account", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, nil, nil +} + func (a *accountBuilder) Revoke(ctx context.Context, grant *v2.Grant) (annotations.Annotations, error) { l := ctxzap.Extract(ctx) diff --git a/pkg/connector/audit_event_feed.go b/pkg/connector/audit_event_feed.go new file mode 100644 index 00000000..947d9069 --- /dev/null +++ b/pkg/connector/audit_event_feed.go @@ -0,0 +1,1141 @@ +package connector + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net/http" + "slices" + "sort" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "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" + ent "github.com/conductorone/baton-sdk/pkg/types/entitlement" + "github.com/conductorone/baton-sdk/pkg/uhttp" + "github.com/google/uuid" + "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/types/known/timestamppb" +) + +const ( + auditEventFeedId = "databricks_audit_log" + + // Trail the watermark by this much instead of the newest event seen, since slower-indexing + // areas of the audited system could otherwise have events skipped permanently. + auditLogTrailingLag = 4 * time.Hour + + // The first poll looks back this far since there's no prior watermark yet. Must be >= + // auditLogTrailingLag, or the lagCutoff guard in ListEvents skips every poll until it is. + auditLogLookback = auditLogTrailingLag + + auditLogPageLimit = 1000 + + // auditLogRetention caps how far back the feed reads; C1 doesn't request event-feed data + // older than ~30 days, so an older cursor is treated as stale. + auditLogRetention = 30 * 24 * time.Hour + + auditServiceAccounts = "accounts" + auditServiceWorkspace = "workspace" + + // Each member costs up to three Account SCIM GETs, which Databricks rate limits, so rows and + // polls past these caps refresh the group instead of looking members up. + maxAuditMembershipLookups = 50 + maxAuditMemberLookupsPerPoll = 300 +) + +// auditActionMapping describes what an audit log action_name affects: an optional primary +// resource (resourceType + the request_params key holding its native ID), an optional +// account-scoped role, and/or optional workspace-scoped roles/entitlements. grant, when set, +// means the row is an atomic entitlement assignment/revocation rather than a generic change. +type auditActionMapping struct { + resourceType *v2.ResourceType + idParam string + // workspaceIdParam names a request_params key holding the workspace id, for account-level + // actions on a workspace, whose workspace_id column is 0. + workspaceIdParam string + accountRole string + roleNames []string + grant *auditGrantMapping + // resolvePrincipal means idParam names a user, group or service principal; resourceType + // is only the fallback when the id matches none of them. + resolvePrincipal bool +} + +// auditGrantMapping names the principal and direction of a grant-mapped action. The +// entitlement's resource is resourceType/idParam on the enclosing auditActionMapping. +type auditGrantMapping struct { + entitlement string + principalParam string + revoke bool +} + +// auditActionKey identifies an audit log action by (service_name, action_name), since +// action_name alone is ambiguous across services (e.g. "delete" also means "cluster terminated"). +type auditActionKey struct { + Service string + Action string +} + +// auditLogActions maps (service_name, action_name) pairs to the resources they affect, per +// https://docs.databricks.com/aws/en/admin/account-settings/audit-logs. +var auditLogActions = map[auditActionKey]auditActionMapping{ + {auditServiceAccounts, "createGroup"}: {resourceType: groupResourceType, idParam: "targetGroupId"}, + // targetUserId holds the added/removed member's id. The plural actions can carry several ids + // separated by commas, a format the audit log reference doesn't document but Databricks logs. + {auditServiceAccounts, "addPrincipalToGroup"}: { + resourceType: groupResourceType, idParam: "targetGroupId", + grant: &auditGrantMapping{entitlement: groupMemberEntitlement, principalParam: "targetUserId"}, + }, + {auditServiceAccounts, "removePrincipalFromGroup"}: { + resourceType: groupResourceType, idParam: "targetGroupId", + grant: &auditGrantMapping{entitlement: groupMemberEntitlement, principalParam: "targetUserId", revoke: true}, + }, + {auditServiceAccounts, "addPrincipalsToGroup"}: { + resourceType: groupResourceType, idParam: "targetGroupId", + grant: &auditGrantMapping{entitlement: groupMemberEntitlement, principalParam: "targetUserId"}, + }, + {auditServiceAccounts, "removePrincipalsFromGroup"}: { + resourceType: groupResourceType, idParam: "targetGroupId", + grant: &auditGrantMapping{entitlement: groupMemberEntitlement, principalParam: "targetUserId", revoke: true}, + }, + {auditServiceAccounts, "removeGroup"}: {resourceType: groupResourceType, idParam: "targetGroupId"}, + // Workspace entitlements change through two paths that log different rows. The admin UI's + // access toggles log changeDatabricksWorkspaceAcl / changeDatabricksSqlAcl (mapped below to their + // single role). Workspace SCIM writes log only updateUser/updateGroup, with no ACL row and no + // detail about which entitlement changed, so those actions refresh every workspace entitlement role. + // Keep both mappings: each covers a path the other doesn't. + {auditServiceAccounts, "updateGroup"}: { + resourceType: groupResourceType, idParam: "targetGroupId", + roleNames: entitlements, + }, + // "add" is the real principal-lifecycle event; deleteUser is a parameterless PII purge. + // "delete" isn't mapped: a deleted principal can't be fetched, so full sync handles it. + // Databricks logs service principal lifecycle and admin changes under these user action + // names with targetUserId, so the principal type is resolved when the row is mapped. + {auditServiceAccounts, "add"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true}, + {auditServiceAccounts, "updateUser"}: { + resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true, + roleNames: entitlements, + }, + {auditServiceAccounts, "activateUser"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true}, + {auditServiceAccounts, "deactivateUser"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true}, + {auditServiceAccounts, "changeDatabricksWorkspaceAcl"}: {resourceType: workspaceResourceType, roleNames: []string{WorkspaceAccessRole}}, + {auditServiceAccounts, "changeDatabricksSqlAcl"}: {roleNames: []string{SQLAccessRole}}, + // The reference describes setAdmin as account admin but lists it with the workspace-level + // events, so the account-admin role is refreshed too in case it is. + {auditServiceAccounts, "setAdmin"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true, accountRole: AccountAdminRole}, + {auditServiceAccounts, "removeAdmin"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true}, + {auditServiceAccounts, "setAccountAdmin"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true, accountRole: AccountAdminRole}, + {auditServiceAccounts, "removeAccountAdmin"}: {resourceType: userResourceType, idParam: "targetUserId", resolvePrincipal: true, accountRole: AccountAdminRole}, + // Workspace membership (permission assignments). The GCP reference only lists + // updatePermissionAssignment; AWS and Azure list all three. + {auditServiceWorkspace, "addPermissionAssignment"}: {resourceType: workspaceResourceType, workspaceIdParam: "workspace_id"}, + {auditServiceWorkspace, "updatePermissionAssignment"}: {resourceType: workspaceResourceType, workspaceIdParam: "workspace_id"}, + {auditServiceWorkspace, "deletePermissionAssignment"}: {resourceType: workspaceResourceType, workspaceIdParam: "workspace_id"}, +} + +func auditLogActionNames() []string { + seen := make(map[string]struct{}, len(auditLogActions)) + for key := range auditLogActions { + seen[key.Action] = struct{}{} + } + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + sort.Strings(names) + return names +} + +func auditLogServiceNames() []string { + seen := make(map[string]struct{}, len(auditLogActions)) + for key := range auditLogActions { + seen[key.Service] = struct{}{} + } + names := make([]string, 0, len(seen)) + for name := range seen { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// eventPageCursor is the opaque state persisted between ListEvents calls. (StartAt, +// StartAfterEventID) form a composite boundary: unprocessed rows are those with +// event_time > StartAt, or event_time == StartAt AND event_id > StartAfterEventID. This +// keeps the boundary well-ordered even when many rows share the same event_time. +type eventPageCursor struct { + StartAt time.Time `json:"start_at"` + StartAfterEventID string `json:"start_after_event_id"` +} + +func encodeEventCursor(c eventPageCursor) (string, error) { + b, err := json.Marshal(c) + if err != nil { + return "", fmt.Errorf("failed to marshal event cursor: %w", err) + } + return base64.StdEncoding.EncodeToString(b), nil +} + +// decodeEventCursor returns a zero-value cursor (self-healing to the lookback default) when +// missing, corrupt, or stale. All three are skip-and-continue, not connector bugs, so all three +// log at Debug, not Warn (which C1 surfaces as an incident). +func decodeEventCursor(ctx context.Context, s string, now time.Time) eventPageCursor { + l := ctxzap.Extract(ctx) + + if s == "" { + return eventPageCursor{} + } + + raw, err := base64.StdEncoding.DecodeString(s) + if err != nil { + l.Debug("databricks-connector: corrupt event cursor, resetting to lookback default", zap.Error(err)) + return eventPageCursor{} + } + + var c eventPageCursor + if err := json.Unmarshal(raw, &c); err != nil { + l.Debug("databricks-connector: corrupt event cursor, resetting to lookback default", zap.Error(err)) + return eventPageCursor{} + } + + if !c.StartAt.IsZero() && now.Sub(c.StartAt) > auditLogRetention { + l.Debug("databricks-connector: event cursor is older than the audit log retention window, resetting to lookback default", + zap.Time("cursor_start_at", c.StartAt), + ) + return eventPageCursor{} + } + + return c +} + +type auditLogRow struct { + EventID string + EventTime time.Time + WorkspaceID int64 + ActionName string + ServiceName string + RequestParams map[string]string +} + +type auditEventFeed struct { + client *databricks.Client + workspaces []string + // sqlWarehouseID enables the feed when non-empty; empty means incremental sync is off. + sqlWarehouseID string + + // queryWorkspaceID caches which workspace hosts sqlWarehouseID across polls. It's a discovered value, not provided by configs. + queryWorkspaceMu sync.Mutex + queryWorkspaceID string + + lookupFailures atomic.Int64 +} + +func newAuditEventFeed( + client *databricks.Client, + workspaces []string, + sqlWarehouseID string, +) *auditEventFeed { + return &auditEventFeed{ + client: client, + workspaces: workspaces, + sqlWarehouseID: sqlWarehouseID, + } +} + +// resolveQueryWorkspaceID returns which workspace hosts f.sqlWarehouseID, resolving it +// once via resolveWarehouseWorkspace rather than probing on every poll. allWorkspaces +// must be every workspace in the account, not filtered by the --workspaces allowlist: +// the warehouse can live in a workspace outside that scope (in the same region). +func (f *auditEventFeed) resolveQueryWorkspaceID(ctx context.Context, allWorkspaces []databricks.Workspace) (string, *v2.RateLimitDescription, error) { + f.queryWorkspaceMu.Lock() + defer f.queryWorkspaceMu.Unlock() + + l := ctxzap.Extract(ctx) + if f.queryWorkspaceID != "" { + l.Debug("databricks-connector: resolveQueryWorkspaceID: using cached sql warehouse workspace", + zap.String("warehouse_id", f.sqlWarehouseID), + zap.String("workspace_id", f.queryWorkspaceID), + ) + return f.queryWorkspaceID, nil, nil + } + + id, rateLimit, err := resolveWarehouseWorkspace(ctx, f.client, allWorkspaces, f.sqlWarehouseID) + if err != nil { + return "", rateLimit, err + } + + l.Debug("databricks-connector: resolveQueryWorkspaceID: discovered sql warehouse workspace", + zap.String("warehouse_id", f.sqlWarehouseID), + zap.String("workspace_id", id), + zap.Int("candidate_workspace_count", len(allWorkspaces)), + ) + f.queryWorkspaceID = id + return id, rateLimit, nil +} + +// EventFeedMetadata is registered unconditionally; whether sql-warehouse-id is set gates +// behavior inside ListEvents instead, to avoid confusing "feed not found" errors when it's off. +func (f *auditEventFeed) EventFeedMetadata(_ context.Context) *v2.EventFeedMetadata { + return &v2.EventFeedMetadata{ + Id: auditEventFeedId, + SupportedEventTypes: []v2.EventType{ + v2.EventType_EVENT_TYPE_RESOURCE_CHANGE, + v2.EventType_EVENT_TYPE_CREATE_GRANT, + v2.EventType_EVENT_TYPE_CREATE_REVOKE, + }, + } +} + +// bootstrapStartAt picks the watermark for a feed with no prior cursor. A zero-valued +// earliestEvent (unset) is treated like nil; a real one is clamped to auditLogRetention so a +// very old value can't trigger a full-table scan against system.access.audit. +func bootstrapStartAt(now time.Time, earliestEvent *timestamppb.Timestamp) time.Time { + if earliestEvent == nil || earliestEvent.AsTime().Unix() == 0 { + return now.Add(-auditLogLookback) + } + + start := earliestEvent.AsTime() + if floor := now.Add(-auditLogRetention); start.Before(floor) { + return floor + } + return start +} + +func (f *auditEventFeed) ListEvents( + ctx context.Context, + earliestEvent *timestamppb.Timestamp, + pToken *pagination.StreamToken, +) ([]*v2.Event, *pagination.StreamState, annotations.Annotations, error) { + l := ctxzap.Extract(ctx) + annos := annotations.Annotations{} + + if f.sqlWarehouseID == "" { + return nil, &pagination.StreamState{}, nil, nil + } + + now := time.Now() + cursor := decodeEventCursor(ctx, pToken.Cursor, now) + + if cursor.StartAt.IsZero() { + cursor = eventPageCursor{StartAt: bootstrapStartAt(now, earliestEvent)} + } + + // Rows are only ever fetched up to lagCutoff (see queryAuditLog), so slow-indexing rows + // have auditLogTrailingLag to appear before we consider that window done. If the cursor + // is already past it (e.g. right after bootstrap, where the lookback is narrower than the + // lag), there's nothing to query yet. + lagCutoff := now.Add(-auditLogTrailingLag) + l.Debug("databricks-connector: ListEvents: poll started", + zap.Bool("resumed_from_cursor", pToken.Cursor != ""), + zap.Time("window_start", cursor.StartAt), + zap.String("window_start_after_event_id", cursor.StartAfterEventID), + zap.Time("window_end", lagCutoff), + ) + if !cursor.StartAt.Before(lagCutoff) { + l.Debug("databricks-connector: ListEvents: nothing to query yet, window start is within the trailing lag", + zap.Time("window_start", cursor.StartAt), + zap.Time("window_end", lagCutoff), + ) + encoded, err := encodeEventCursor(cursor) + if err != nil { + return nil, nil, nil, fmt.Errorf("databricks-connector: failed to encode event cursor: %w", err) + } + return nil, &pagination.StreamState{Cursor: encoded, HasMore: false}, annos, nil + } + + // ListWorkspaces already applies --databricks-exclude-workspaces. allWorkspaces (not + // narrowed by --workspaces) locates the query warehouse; scopedWorkspaces decides which + // workspaces' audit rows get resolved, so events never surface a workspace a full sync skips. + allWorkspaces, rateLimit, err := f.client.ListWorkspaces(ctx) + if rateLimit != nil { + annos.WithRateLimiting(rateLimit) + } + if err != nil { + return nil, nil, annos, fmt.Errorf("databricks-connector: failed to list workspaces: %w", err) + } + scopedWorkspaces := filterConfiguredWorkspaces(allWorkspaces, f.workspaces) + l.Debug("databricks-connector: ListEvents: listed workspaces", + zap.Int("workspace_count", len(allWorkspaces)), + zap.Int("in_scope_workspace_count", len(scopedWorkspaces)), + ) + if len(scopedWorkspaces) == 0 { + return nil, nil, annos, uhttp.WrapErrors(codes.FailedPrecondition, "databricks-connector: no workspace available to query system.access.audit") + } + + workspaceLookup := make(map[int64]string, len(scopedWorkspaces)) + for _, w := range scopedWorkspaces { + workspaceLookup[int64(w.ID)] = w.DeploymentName + } + + queryWorkspaceId, rateLimit, err := f.resolveQueryWorkspaceID(ctx, allWorkspaces) + if rateLimit != nil { + annos.WithRateLimiting(rateLimit) + } + if err != nil { + return nil, nil, annos, err + } + + rows, rawRowCount, lastRawBoundary, rateLimit, err := f.queryAuditLog(ctx, queryWorkspaceId, cursor, lagCutoff) + if err != nil { + if rateLimit != nil { + annos.WithRateLimiting(rateLimit) + } + return nil, nil, annos, fmt.Errorf("databricks-connector: failed to query audit log: %w", err) + } + + if rateLimit != nil { + annos.WithRateLimiting(rateLimit) + } + + var events []*v2.Event + var unmappedRows, skippedLookupRows, resourceChangeEvents, grantEvents, revokeEvents, duplicateResourceChanges int + lookups := newPrincipalLookups(&f.lookupFailures) + // Keep only the last resource change per resource in a page: each one triggers a full refetch + // (costly for workspace roles). Grant and revoke events are never collapsed. + lastResourceChange := map[string]int{} + for _, row := range rows { + affected, rowRateLimit, err := mapAuditRowToResource(ctx, f.client, lookups, row, f.client.GetAccountId(), workspaceLookup) + if hasRateLimitData(rowRateLimit) { + annos.WithRateLimiting(rowRateLimit) + } + // Unmappable rows come back as no error, so this is a real lookup failure. Transient + // ones are returned so the next poll retries the row; others would block the cursor + // on every poll, so they're skipped and left to the next full sync. + if err != nil { + if isRetryableLookupError(err) { + return nil, nil, annos, fmt.Errorf("databricks-connector: failed to map audit row %s (%s): %w", row.EventID, row.ActionName, err) + } + lookups.warnLookupFailure(ctx, row, err, false) + skippedLookupRows++ + continue + } + if len(affected) == 0 { + unmappedRows++ + l.Debug("databricks-connector: skipping audit row with no resource mapping", + zap.String("action_name", row.ActionName), + zap.String("event_id", row.EventID), + ) + continue + } + + l.Debug("databricks-connector: ListEvents: mapped audit row to events", + zap.String("event_id", row.EventID), + zap.String("service_name", row.ServiceName), + zap.String("action_name", row.ActionName), + zap.Int("event_count", len(affected)), + ) + for i, a := range affected { + event := &v2.Event{ + Id: fmt.Sprintf("%s/%d", row.EventID, i), + OccurredAt: timestamppb.New(row.EventTime), + } + switch { + case a.grant != nil && a.grant.revoke: + revokeEvents++ + event.Event = &v2.Event_CreateRevokeEvent{ + CreateRevokeEvent: &v2.CreateRevokeEvent{Entitlement: a.grant.entitlement, Principal: a.grant.principal}, + } + case a.grant != nil: + grantEvents++ + event.Event = &v2.Event_CreateGrantEvent{ + CreateGrantEvent: &v2.CreateGrantEvent{Entitlement: a.grant.entitlement, Principal: a.grant.principal}, + } + default: + key := resourceChangeKey(a.resourceId, a.parentResourceId) + if prev, seen := lastResourceChange[key]; seen { + events[prev] = nil + duplicateResourceChanges++ + } else { + resourceChangeEvents++ + } + lastResourceChange[key] = len(events) + event.Event = &v2.Event_ResourceChangeEvent{ + ResourceChangeEvent: &v2.ResourceChangeEvent{ResourceId: a.resourceId, ParentResourceId: a.parentResourceId}, + } + } + events = append(events, event) + } + } + + events = slices.DeleteFunc(events, func(e *v2.Event) bool { return e == nil }) + + hasMore := rawRowCount >= auditLogPageLimit + nextCursor, advanced := advanceEventCursor(cursor, rows, lastRawBoundary, hasMore, lagCutoff) + if !advanced { + hasMore = false + } + + encoded, err := encodeEventCursor(nextCursor) + if err != nil { + return nil, nil, annos, fmt.Errorf("databricks-connector: failed to encode event cursor: %w", err) + } + + l.Debug("databricks-connector: ListEvents: poll finished", + zap.Int("audit_rows_fetched", rawRowCount), + zap.Int("audit_rows_parsed", len(rows)), + zap.Int("audit_rows_unmapped", unmappedRows), + zap.Int("audit_rows_skipped_lookup_failure", skippedLookupRows), + zap.Int("audit_members_lookup_failure", lookups.memberFailures), + zap.Int("audit_members_over_lookup_budget", lookups.membersOverBudget), + zap.Int("events_total", len(events)), + zap.Int("events_resource_change", resourceChangeEvents), + zap.Int("events_resource_change_duplicates_dropped", duplicateResourceChanges), + zap.Int("events_create_grant", grantEvents), + zap.Int("events_create_revoke", revokeEvents), + zap.Bool("has_more", hasMore), + zap.Time("next_window_start", nextCursor.StartAt), + zap.String("next_window_start_after_event_id", nextCursor.StartAfterEventID), + ) + return events, &pagination.StreamState{Cursor: encoded, HasMore: hasMore}, annos, nil +} + +// hasRateLimitData reports whether rl was parsed from rate-limit headers, so an empty one +// doesn't overwrite a real one in the annotations. +func hasRateLimitData(rl *v2.RateLimitDescription) bool { + return rl.GetLimit() > 0 || rl.GetRemaining() > 0 || rl.GetStatus() != v2.RateLimitDescription_STATUS_UNSPECIFIED +} + +// resourceChangeKey identifies a resource change by its resource and parent, for dropping +// duplicates within one ListEvents page. +func resourceChangeKey(resourceId, parentResourceId *v2.ResourceId) string { + return fmt.Sprintf("%s\x00%s\x00%s\x00%s", + resourceId.GetResourceType(), resourceId.GetResource(), + parentResourceId.GetResourceType(), parentResourceId.GetResource()) +} + +func isRetryableLookupError(err error) bool { + switch status.Code(err) { + case codes.Unavailable, codes.ResourceExhausted, codes.DeadlineExceeded, codes.Internal, codes.Unknown, codes.Canceled: + return true + default: + return false + } +} + +// advanceEventCursor advances to the last row processed while more of the page remains, or +// to lagCutoff once drained: rows are already bounded by lagCutoff (see queryAuditLog), so a +// drained page proves nothing else exists up to that point. Prefers lastRawBoundary (from the +// raw page, so a page where every row fails to parse still advances), falling back to the last +// successfully parsed row. advanced is false only if neither is available, so the caller can +// avoid reporting HasMore with an unchanged cursor. +func advanceEventCursor(cursor eventPageCursor, rows []auditLogRow, lastRawBoundary eventPageCursor, hasMore bool, lagCutoff time.Time) (eventPageCursor, bool) { + if hasMore { + if !lastRawBoundary.StartAt.IsZero() { + return lastRawBoundary, true + } + if len(rows) > 0 { + last := rows[len(rows)-1] + return eventPageCursor{StartAt: last.EventTime, StartAfterEventID: last.EventID}, true + } + return cursor, false + } + return eventPageCursor{StartAt: lagCutoff}, true +} + +// affectedResource is either one resource a mapped audit row's action changed (RESOURCE_CHANGE), +// or, when grant is set, the entitlement/principal it assigned or revoked (CREATE_GRANT/CREATE_REVOKE). +type affectedResource struct { + resourceId *v2.ResourceId + parentResourceId *v2.ResourceId + grant *affectedGrant +} + +type affectedGrant struct { + entitlement *v2.Entitlement + principal *v2.Resource + revoke bool +} + +// mapAuditRowToResource maps an audit row to every Baton resource its action affects, skipping +// anything unresolvable. Principals are always account-parented, mirroring full sync, regardless +// of the workspace the audit row occurred in. +func mapAuditRowToResource( + ctx context.Context, + client *databricks.Client, + lookups *principalLookups, + row auditLogRow, + accountId string, + workspaceLookup map[int64]string, +) ([]affectedResource, *v2.RateLimitDescription, error) { + mapping, ok := auditLogActions[auditActionKey{Service: row.ServiceName, Action: row.ActionName}] + if !ok { + return nil, nil, nil + } + + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: accountId} + + workspaceId := row.WorkspaceID + if workspaceId == 0 && mapping.workspaceIdParam != "" { + // An unparseable value leaves workspaceId at 0, so the row is skipped below. + if parsed, err := strconv.ParseInt(row.RequestParams[mapping.workspaceIdParam], 10, 64); err == nil { + workspaceId = parsed + } + } + + var workspaceParent *v2.ResourceId + if workspaceId != 0 { + deploymentName, found := workspaceLookup[workspaceId] + if !found { + return nil, nil, nil + } + workspaceParent = &v2.ResourceId{ResourceType: workspaceResourceType.Id, Resource: deploymentName} + } + + var affected []affectedResource + var rateLimit *v2.RateLimitDescription + + switch { + case mapping.resourceType == workspaceResourceType: + if workspaceParent == nil { + return nil, nil, nil + } + affected = append(affected, affectedResource{resourceId: workspaceParent, parentResourceId: accountParent}) + case mapping.resourceType != nil: + nativeId, ok := row.RequestParams[mapping.idParam] + if !ok || nativeId == "" { + return nil, nil, nil + } + + resourceType := mapping.resourceType + if mapping.resolvePrincipal { + resolved, rl, err := resolvePrincipalType(ctx, client, lookups, nativeId, prefersServicePrincipal(row)) + rateLimit = rl + if err != nil { + return nil, rateLimit, fmt.Errorf("databricks-connector: failed to resolve principal for event %s: %w", row.EventID, err) + } + // No match is expected for a deleted principal; keep the fallback so role refreshes still fire. + if resolved != nil { + resourceType = resolved + } + } + + resourceId := &v2.ResourceId{ResourceType: resourceType.Id, Resource: nativeId} + if resourceType == groupResourceType { + resourceId.Resource = groupResourceId(ctx, nativeId, accountParent) + } + + if mapping.grant != nil { + grants, rateLimit, err := buildAffectedGrants(ctx, client, lookups, row, mapping.grant, resourceId, accountParent) + if err != nil { + return nil, rateLimit, fmt.Errorf("databricks-connector: failed to resolve grant principal for event %s: %w", row.EventID, err) + } + return grants, rateLimit, nil + } + + affected = append(affected, affectedResource{resourceId: resourceId, parentResourceId: accountParent}) + } + + if mapping.accountRole != "" { + affected = append(affected, affectedResource{ + resourceId: &v2.ResourceId{ResourceType: roleResourceType.Id, Resource: roleResourceId(mapping.accountRole, accountParent)}, + parentResourceId: accountParent, + }) + } + + if workspaceParent != nil { + for _, roleName := range mapping.roleNames { + affected = append(affected, affectedResource{ + resourceId: &v2.ResourceId{ResourceType: roleResourceType.Id, Resource: roleResourceId(roleName, workspaceParent)}, + parentResourceId: workspaceParent, + }) + } + } + + return affected, rateLimit, nil +} + +// buildAffectedGrants returns a grant or revoke on the entitlement (on entitlementResourceId/parent) +// for each member the row names, plus one refresh of that resource when any member is unmatched, +// fails a non-retryable lookup, or is over the poll's lookup budget. Only retryable errors are returned. +func buildAffectedGrants( + ctx context.Context, + client *databricks.Client, + lookups *principalLookups, + row auditLogRow, + gm *auditGrantMapping, + entitlementResourceId, parent *v2.ResourceId, +) ([]affectedResource, *v2.RateLimitDescription, error) { + refresh := affectedResource{resourceId: entitlementResourceId, parentResourceId: parent} + members := auditGrantMembers(row, gm.principalParam) + + l := ctxzap.Extract(ctx) + if len(members) > 1 { + l.Debug("databricks-connector: buildAffectedGrants: audit row names several members", + zap.String("event_id", row.EventID), + zap.String("action_name", row.ActionName), + zap.Int("member_count", len(members)), + zap.Bool("capped", len(members) > maxAuditMembershipLookups), + ) + } + if len(members) == 0 || len(members) > maxAuditMembershipLookups { + return []affectedResource{refresh}, nil, nil + } + + entitlement := ent.NewAssignmentEntitlement(&v2.Resource{Id: entitlementResourceId, ParentResourceId: parent}, gm.entitlement) + + var rateLimit *v2.RateLimitDescription + affected := make([]affectedResource, 0, len(members)+1) + unresolved := 0 + for _, m := range members { + if _, cached := lookups.types[m.id]; !cached { + if lookups.remainingMemberLookups <= 0 { + lookups.membersOverBudget++ + unresolved++ + continue + } + lookups.remainingMemberLookups-- + } + + principalType, rl, err := resolvePrincipalType(ctx, client, lookups, m.id, m.servicePrincipalFirst) + if rl != nil { + rateLimit = rl + } + if err != nil { + if isRetryableLookupError(err) { + return nil, rateLimit, err + } + lookups.warnLookupFailure(ctx, row, err, true) + lookups.memberFailures++ + unresolved++ + continue + } + if principalType == nil { + unresolved++ + continue + } + + principalResourceId := m.id + if principalType == groupResourceType { + principalResourceId = groupResourceId(ctx, m.id, parent) + } + affected = append(affected, affectedResource{grant: &affectedGrant{ + entitlement: entitlement, + principal: &v2.Resource{Id: &v2.ResourceId{ResourceType: principalType.Id, Resource: principalResourceId}}, + revoke: gm.revoke, + }}) + } + + if unresolved > 0 { + l.Debug("databricks-connector: buildAffectedGrants: refreshing group for unresolved members", + zap.String("event_id", row.EventID), + zap.String("action_name", row.ActionName), + zap.Int("unresolved_member_count", unresolved), + ) + affected = append(affected, refresh) + } + return affected, rateLimit, nil +} + +type auditGrantMember struct { + id string + servicePrincipalFirst bool +} + +// auditGrantMembers splits the row's comma-separated principal ids, dropping blanks and repeats. +// targetUserName only steers the lookup order when it lists one name per id. +func auditGrantMembers(row auditLogRow, principalParam string) []auditGrantMember { + rawIDs := splitAuditList(row.RequestParams[principalParam]) + rawNames := splitAuditList(row.RequestParams["targetUserName"]) + namesAligned := len(rawNames) == len(rawIDs) + + seen := make(map[string]struct{}, len(rawIDs)) + members := make([]auditGrantMember, 0, len(rawIDs)) + for i, id := range rawIDs { + if id == "" { + continue + } + if _, dup := seen[id]; dup { + continue + } + seen[id] = struct{}{} + members = append(members, auditGrantMember{ + id: id, + servicePrincipalFirst: namesAligned && isApplicationId(rawNames[i]), + }) + } + return members +} + +func splitAuditList(v string) []string { + parts := strings.Split(v, ",") + for i, p := range parts { + parts[i] = strings.TrimSpace(p) + } + return parts +} + +// principalLookups is the principal lookup state for one ListEvents call. types memoizes +// resolvePrincipalType, where a nil value means the id matched no principal. +type principalLookups struct { + types map[string]*v2.ResourceType + remainingMemberLookups int + memberFailures int + membersOverBudget int + // failures is the feed's process-wide count, which samples the lookup-failure warning. + failures *atomic.Int64 +} + +func newPrincipalLookups(failures *atomic.Int64) *principalLookups { + if failures == nil { + failures = &atomic.Int64{} + } + return &principalLookups{ + types: map[string]*v2.ResourceType{}, + remainingMemberLookups: maxAuditMemberLookupsPerPoll, + failures: failures, + } +} + +func (p *principalLookups) warnLookupFailure(ctx context.Context, row auditLogRow, err error, groupRefresh bool) { + if count := p.failures.Add(1); count == 1 || count == 10 || count == 100 || count%1000 == 0 { + ctxzap.Extract(ctx).Warn("databricks-connector: principal lookup failed for audit row", + zap.String("action_name", row.ActionName), + zap.String("event_id", row.EventID), + zap.Bool("fallback_to_group_refresh", groupRefresh), + zap.Int64("total_occurrences", count), + zap.Error(err), + ) + } +} + +// resolvePrincipalType finds which resource type nativeId belongs to, trying user, group, then +// service principal in that order via the Account API and stopping at the first match: the audit log's +// targetUserId doesn't record which kind of principal it actually is. Returns a nil type (no +// error) if nativeId doesn't match any of the three. Results, including no match, are cached +// in lookups; errors aren't. servicePrincipalFirst only reorders the lookups. +func resolvePrincipalType( + ctx context.Context, + client *databricks.Client, + lookups *principalLookups, + nativeId string, + servicePrincipalFirst bool, +) (*v2.ResourceType, *v2.RateLimitDescription, error) { + if resourceType, ok := lookups.types[nativeId]; ok { + return resourceType, nil, nil + } + + candidates := []struct { + resourceType *v2.ResourceType + found func() (bool, *v2.RateLimitDescription, error) + }{ + {userResourceType, func() (bool, *v2.RateLimitDescription, error) { + return principalExists(client.GetUser(ctx, "", nativeId)) + }}, + {groupResourceType, func() (bool, *v2.RateLimitDescription, error) { + return principalExists(client.GetGroup(ctx, "", nativeId)) + }}, + {servicePrincipalResourceType, func() (bool, *v2.RateLimitDescription, error) { + return principalExists(client.GetServicePrincipal(ctx, "", nativeId)) + }}, + } + if servicePrincipalFirst { + candidates[0], candidates[2] = candidates[2], candidates[0] + } + + var rateLimit *v2.RateLimitDescription + for _, candidate := range candidates { + found, rl, err := candidate.found() + if rl != nil { + rateLimit = rl + } + if err != nil { + return nil, rateLimit, fmt.Errorf("failed to check principal %s: %w", nativeId, err) + } + if found { + ctxzap.Extract(ctx).Debug("databricks-connector: resolvePrincipalType: resolved audit principal", + zap.String("principal_id", nativeId), + zap.String("resource_type", candidate.resourceType.Id), + ) + lookups.types[nativeId] = candidate.resourceType + return candidate.resourceType, rateLimit, nil + } + } + + ctxzap.Extract(ctx).Debug("databricks-connector: resolvePrincipalType: audit principal matched no user, group or service principal", + zap.String("principal_id", nativeId), + ) + lookups.types[nativeId] = nil + return nil, rateLimit, nil +} + +// prefersServicePrincipal reports whether the row's targetUserName looks like a service +// principal: Databricks logs a service principal's application ID (a UUID) there, and a +// user's username for users. +func prefersServicePrincipal(row auditLogRow) bool { + return isApplicationId(row.RequestParams["targetUserName"]) +} + +func isApplicationId(name string) bool { + _, err := uuid.Parse(name) + return err == nil +} + +// principalExists adapts a client Get* call into a found/not-found result: a 404 means not +// found (not an error), anything else is a real failure. +func principalExists[T any](_ T, rateLimit *v2.RateLimitDescription, err error) (bool, *v2.RateLimitDescription, error) { + if err == nil { + return true, rateLimit, nil + } + var apiErr *databricks.APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound { + return false, rateLimit, nil + } + return false, rateLimit, err +} + +// filterConfiguredWorkspaces narrows workspaces to configuredWorkspaces (the --workspaces +// allowlist), or returns workspaces unchanged when the allowlist is empty. This scopes +// which workspaces' audit rows get resolved to resources — it must NOT be applied before +// locating the query warehouse (resolveWarehouseWorkspace), which can live in any workspace +// in the account regardless of this allowlist. +func filterConfiguredWorkspaces(workspaces []databricks.Workspace, configuredWorkspaces []string) []databricks.Workspace { + if len(configuredWorkspaces) == 0 { + return workspaces + } + + configured := make(map[string]struct{}, len(configuredWorkspaces)) + for _, name := range configuredWorkspaces { + configured[name] = struct{}{} + } + + filtered := make([]databricks.Workspace, 0, len(workspaces)) + for _, w := range workspaces { + if _, ok := matchConfiguredWorkspace(configured, w.DeploymentName, w.Name, strconv.Itoa(w.ID)); ok { + filtered = append(filtered, w) + } + } + + return filtered +} + +// resolveWarehouseWorkspace finds which workspace hosts warehouseId by probing each +// candidate workspace, since Databricks has no account-level lookup for this. +func resolveWarehouseWorkspace(ctx context.Context, client *databricks.Client, workspaces []databricks.Workspace, warehouseId string) (string, *v2.RateLimitDescription, error) { + var rateLimit *v2.RateLimitDescription + var inaccessible []string + for _, w := range workspaces { + found, rl, err := client.WarehouseExists(ctx, w.DeploymentName, warehouseId) + if rl != nil { + rateLimit = rl + } + if err != nil { + // The service principal needn't be assigned to every workspace; keep looking. + if isAccessDenied(err) { + inaccessible = append(inaccessible, w.DeploymentName) + continue + } + return "", rateLimit, fmt.Errorf( + "databricks-connector: failed to check workspace %s for sql-warehouse-id %s: %w", + w.DeploymentName, warehouseId, err, + ) + } + if found { + return w.DeploymentName, rateLimit, nil + } + } + + skipped := "" + if len(inaccessible) > 0 { + skipped = fmt.Sprintf(" (skipped %d inaccessible: %s)", len(inaccessible), strings.Join(inaccessible, ", ")) + } + if len(workspaces) == 1 { + return "", rateLimit, uhttp.WrapErrors(codes.NotFound, fmt.Sprintf( + "databricks-connector: sql-warehouse-id %q was not found in workspace %s%s", + warehouseId, workspaces[0].DeploymentName, skipped, + )) + } + return "", rateLimit, uhttp.WrapErrors(codes.NotFound, fmt.Sprintf( + "databricks-connector: sql-warehouse-id %q was not found in any of the %d available workspaces%s", + warehouseId, len(workspaces), skipped, + )) +} + +// isAccessDenied reports whether err is a 401/403 from the Databricks API. +func isAccessDenied(err error) bool { + var apiErr *databricks.APIError + return errors.As(err, &apiErr) && + (apiErr.StatusCode == http.StatusUnauthorized || apiErr.StatusCode == http.StatusForbidden) +} + +// queryAuditLog returns rows in (cursor, lagCutoff], plus the raw row count (before +// parseAuditLogRows may drop malformed ones) so callers can tell if the page was full. +func (f *auditEventFeed) queryAuditLog(ctx context.Context, workspaceId string, cursor eventPageCursor, lagCutoff time.Time) ([]auditLogRow, int, eventPageCursor, *v2.RateLimitDescription, error) { + // The (event_time, event_id) tiebreaker keeps ordering deterministic and lets us page + // with a composite > predicate, so progress never stalls even if many rows share one + // event_time (see advanceEventCursor); this holds as long as event_id compares consistently + // under Databricks SQL's ">"/ORDER BY, which is true for this table's opaque IDs. + // The table also logs requests Databricks rejected (e.g. a 403 on removePrincipalFromGroup), + // so only successful ones are read; a failed one would otherwise become a false grant or revoke. + statement := fmt.Sprintf(` + SELECT event_id, event_time, workspace_id, action_name, service_name, request_params + FROM system.access.audit + WHERE event_date >= :start_date + AND (event_time > :start_time OR (event_time = :start_time AND event_id > :start_after_event_id)) + AND event_time <= :lag_cutoff + AND service_name IN (%s) + AND action_name IN (%s) + AND response.status_code = 200 + ORDER BY event_time ASC, event_id ASC + LIMIT %d + `, quotedInClause(auditLogServiceNames()), quotedInClause(auditLogActionNames()), auditLogPageLimit) + + result, rateLimit, err := f.client.ExecuteStatement( + ctx, + workspaceId, + f.sqlWarehouseID, + statement, + databricks.StatementParameter{Name: "start_date", Value: cursor.StartAt.UTC().Format("2006-01-02"), Type: "DATE"}, + // RFC3339Nano, not RFC3339: the (event_time, event_id) tiebreaker needs start_time + // to round-trip at the same sub-second precision parseAuditLogRows parses. + databricks.StatementParameter{Name: "start_time", Value: cursor.StartAt.UTC().Format(time.RFC3339Nano), Type: "TIMESTAMP"}, + databricks.StatementParameter{Name: "start_after_event_id", Value: cursor.StartAfterEventID, Type: "STRING"}, + databricks.StatementParameter{Name: "lag_cutoff", Value: lagCutoff.UTC().Format(time.RFC3339Nano), Type: "TIMESTAMP"}, + ) + if err != nil { + return nil, 0, eventPageCursor{}, rateLimit, err + } + + rows, lastRawBoundary, err := parseAuditLogRows(ctx, result) + if err != nil { + return nil, len(result.Rows), lastRawBoundary, rateLimit, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: queryAuditLog: audit log query succeeded", + zap.String("workspace_id", workspaceId), + zap.String("warehouse_id", f.sqlWarehouseID), + zap.Int("audit_rows_fetched", len(result.Rows)), + zap.Int("audit_rows_parsed", len(rows)), + zap.Int("audit_rows_malformed", len(result.Rows)-len(rows)), + ) + return rows, len(result.Rows), lastRawBoundary, rateLimit, nil +} + +func quotedInClause(values []string) string { + quoted := make([]string, len(values)) + for i, v := range values { + quoted[i] = "'" + v + "'" + } + + return strings.Join(quoted, ", ") +} + +const ( + colEventID = "event_id" + colEventTime = "event_time" + colWorkspaceID = "workspace_id" + colActionName = "action_name" + colServiceName = "service_name" + colRequestParams = "request_params" +) + +// parseAuditLogRows skips (and logs) any individual row that fails to parse instead of +// failing the whole page; a missing expected column is a schema problem, so that still fails. +// lastRawBoundary is the last row's (event_time, event_id) regardless of whether the rest of +// that row parsed, so a page where every row fails can still page forward. +func parseAuditLogRows(ctx context.Context, result *databricks.StatementResult) ([]auditLogRow, eventPageCursor, error) { + colIndex := make(map[string]int, len(result.Columns)) + for i, name := range result.Columns { + colIndex[name] = i + } + + maxColIndex := 0 + for _, name := range []string{colEventID, colEventTime, colWorkspaceID, colActionName, colServiceName, colRequestParams} { + idx, ok := colIndex[name] + if !ok { + return nil, eventPageCursor{}, fmt.Errorf("audit log query result missing column %q", name) + } + if idx > maxColIndex { + maxColIndex = idx + } + } + + l := ctxzap.Extract(ctx) + + rows := make([]auditLogRow, 0, len(result.Rows)) + for _, r := range result.Rows { + row, err := parseAuditLogRow(r, colIndex, maxColIndex) + if err != nil { + l.Debug("databricks-connector: skipping malformed audit log row", zap.Error(err)) + continue + } + rows = append(rows, row) + } + + var lastRawBoundary eventPageCursor + if len(result.Rows) > 0 { + var err error + lastRawBoundary, err = parseEventBoundary(result.Rows[len(result.Rows)-1], colIndex) + if err != nil { + l.Debug("databricks-connector: failed to parse last raw row's event boundary", zap.Error(err)) + } + } + + return rows, lastRawBoundary, nil +} + +// parseEventBoundary extracts just event_id/event_time from a raw row, tolerating failures +// elsewhere in the row (e.g. malformed request_params) that would fail parseAuditLogRow. +func parseEventBoundary(r []string, colIndex map[string]int) (eventPageCursor, error) { + idIdx, timeIdx := colIndex[colEventID], colIndex[colEventTime] + if len(r) <= idIdx || len(r) <= timeIdx { + return eventPageCursor{}, fmt.Errorf("audit log query result row has %d columns, expected event_id/event_time", len(r)) + } + + eventTime, err := time.Parse("2006-01-02 15:04:05.999", r[timeIdx]) + if err != nil { + eventTime, err = time.Parse(time.RFC3339, r[timeIdx]) + if err != nil { + return eventPageCursor{}, fmt.Errorf("failed to parse event_time %q: %w", r[timeIdx], err) + } + } + + return eventPageCursor{StartAt: eventTime, StartAfterEventID: r[idIdx]}, nil +} + +func parseAuditLogRow(r []string, colIndex map[string]int, maxColIndex int) (auditLogRow, error) { + if len(r) <= maxColIndex { + return auditLogRow{}, fmt.Errorf("audit log query result row has %d columns, expected at least %d", len(r), maxColIndex+1) + } + + boundary, err := parseEventBoundary(r, colIndex) + if err != nil { + return auditLogRow{}, err + } + + var workspaceId int64 + if v := r[colIndex[colWorkspaceID]]; v != "" { + workspaceId, err = strconv.ParseInt(v, 10, 64) + if err != nil { + return auditLogRow{}, fmt.Errorf("failed to parse workspace_id %q: %w", v, err) + } + } + + requestParams := map[string]string{} + if v := r[colIndex[colRequestParams]]; v != "" { + if err := json.Unmarshal([]byte(v), &requestParams); err != nil { + return auditLogRow{}, fmt.Errorf("failed to parse request_params %q: %w", v, err) + } + } + + return auditLogRow{ + EventID: boundary.StartAfterEventID, + EventTime: boundary.StartAt, + WorkspaceID: workspaceId, + ActionName: r[colIndex[colActionName]], + ServiceName: r[colIndex[colServiceName]], + RequestParams: requestParams, + }, nil +} diff --git a/pkg/connector/audit_event_feed_test.go b/pkg/connector/audit_event_feed_test.go new file mode 100644 index 00000000..7924e141 --- /dev/null +++ b/pkg/connector/audit_event_feed_test.go @@ -0,0 +1,2211 @@ +package connector + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/conductorone/baton-databricks/pkg/databricks" + v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" + "github.com/conductorone/baton-sdk/pkg/pagination" + ent "github.com/conductorone/baton-sdk/pkg/types/entitlement" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// testEarliestEvent starts a fresh cursor before lagCutoff, so ListEvents' bootstrap +// doesn't hit the guard for cursor.StartAt >= lagCutoff (see TestListEventsSkipsQueryPastLagCutoff). +func testEarliestEvent() *timestamppb.Timestamp { + return timestamppb.New(time.Now().Add(-2 * auditLogTrailingLag)) +} + +func TestBootstrapStartAt(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + + cases := []struct { + name string + earliestEvent *timestamppb.Timestamp + want time.Time + }{ + {"nil earliestEvent uses the lookback default", nil, now.Add(-auditLogLookback)}, + {"zero-valued earliestEvent is treated like nil", timestamppb.New(time.Unix(0, 0)), now.Add(-auditLogLookback)}, + {"recent earliestEvent is used as-is", timestamppb.New(now.Add(-time.Hour)), now.Add(-time.Hour)}, + {"earliestEvent older than retention is clamped", timestamppb.New(now.AddDate(-2, 0, 0)), now.Add(-auditLogRetention)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := bootstrapStartAt(now, tc.earliestEvent); !got.Equal(tc.want) { + t.Errorf("bootstrapStartAt() = %v, want %v", got, tc.want) + } + }) + } +} + +// writeJSONNotFound writes a 404 with a JSON body; a plain-text one (e.g. http.NotFound) +// breaks the client's JSON decoder. +func writeJSONNotFound(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"not found"}`)) +} + +// newProbeTestClient builds a databricks.Client whose requests are redirected to a local +// httptest.Server running handler (see redirectTransport). +func newProbeTestClient(t *testing.T, handler http.HandlerFunc) *databricks.Client { + t.Helper() + + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + auth := &databricks.NoAuth{} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", auth, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + return client +} + +func TestResolveWarehouseWorkspace(t *testing.T) { + const warehouseId = "wh-123" + + t.Run("single workspace is still probed", func(t *testing.T) { + probed := false + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + probed = true + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":%q}`, warehouseId) + }) + workspaces := []databricks.Workspace{{ID: 1, DeploymentName: "dbc-only"}} + + got, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err != nil { + t.Fatalf("resolveWarehouseWorkspace() error = %v", err) + } + if got != "dbc-only" { + t.Errorf("got %q, want %q", got, "dbc-only") + } + if !probed { + t.Error("WarehouseExists was never called; a single workspace must still be probed so a bad sql-warehouse-id is caught with a clear error") + } + }) + + t.Run("single workspace missing the warehouse gets a specific not-found error", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + writeJSONNotFound(w) + }) + workspaces := []databricks.Workspace{{ID: 1, DeploymentName: "dbc-only"}} + + _, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err == nil { + t.Fatal("resolveWarehouseWorkspace() error = nil, want error when the single workspace doesn't have the warehouse") + } + wantMsg := `sql-warehouse-id "wh-123" was not found in workspace dbc-only` + if !strings.Contains(err.Error(), wantMsg) { + t.Errorf("error = %q, want it to contain %q", err.Error(), wantMsg) + } + }) + + t.Run("probes each workspace until the warehouse is found", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Header.Get("X-Test-Original-Host"), "dbc-bbb.") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":%q}`, warehouseId) + return + } + writeJSONNotFound(w) + }) + workspaces := []databricks.Workspace{ + {ID: 1, DeploymentName: "dbc-aaa"}, + {ID: 2, DeploymentName: "dbc-bbb"}, + } + + got, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err != nil { + t.Fatalf("resolveWarehouseWorkspace() error = %v", err) + } + if got != "dbc-bbb" { + t.Errorf("got %q, want %q", got, "dbc-bbb") + } + }) + + t.Run("warehouse not found anywhere is a clear error", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + writeJSONNotFound(w) + }) + workspaces := []databricks.Workspace{ + {ID: 1, DeploymentName: "dbc-aaa"}, + {ID: 2, DeploymentName: "dbc-bbb"}, + } + + _, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err == nil { + t.Fatal("resolveWarehouseWorkspace() error = nil, want error when no workspace has the warehouse") + } + }) + + t.Run("an inaccessible workspace is skipped, not fatal", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.Header.Get("X-Test-Original-Host"), "dbc-aaa.") { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"message":"not assigned to workspace"}`)) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":%q}`, warehouseId) + }) + workspaces := []databricks.Workspace{ + {ID: 1, DeploymentName: "dbc-aaa"}, + {ID: 2, DeploymentName: "dbc-bbb"}, + } + + got, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err != nil { + t.Fatalf("resolveWarehouseWorkspace() error = %v", err) + } + if got != "dbc-bbb" { + t.Errorf("got %q, want %q", got, "dbc-bbb") + } + }) + + t.Run("all workspaces inaccessible is a not-found naming them", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"message":"unauthorized"}`)) + }) + workspaces := []databricks.Workspace{ + {ID: 1, DeploymentName: "dbc-aaa"}, + {ID: 2, DeploymentName: "dbc-bbb"}, + } + + _, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if got := status.Code(err); got != codes.NotFound { + t.Fatalf("error code = %s (%v), want %s", got, err, codes.NotFound) + } + if !strings.Contains(err.Error(), "skipped 2 inaccessible: dbc-aaa, dbc-bbb") { + t.Errorf("error = %q, want it to name the skipped workspaces", err.Error()) + } + }) + + t.Run("a real error from a probe is returned, not swallowed as not-found", func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"message":"boom"}`)) + }) + workspaces := []databricks.Workspace{ + {ID: 1, DeploymentName: "dbc-aaa"}, + {ID: 2, DeploymentName: "dbc-bbb"}, + } + + _, _, err := resolveWarehouseWorkspace(context.Background(), client, workspaces, warehouseId) + if err == nil { + t.Fatal("resolveWarehouseWorkspace() error = nil, want a propagated probe error") + } + }) +} + +func TestEventCursorRoundTrip(t *testing.T) { + want := eventPageCursor{ + StartAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), + StartAfterEventID: "b", + } + + encoded, err := encodeEventCursor(want) + if err != nil { + t.Fatalf("encodeEventCursor() error = %v", err) + } + + got := decodeEventCursor(context.Background(), encoded, want.StartAt) + if !got.StartAt.Equal(want.StartAt) || got.StartAfterEventID != want.StartAfterEventID { + t.Errorf("decodeEventCursor() = %+v, want %+v", got, want) + } +} + +func TestDecodeEventCursorSelfHeals(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + cases := []string{"", "not-base64!!!", "aW52YWxpZC1qc29u"} // last one is base64("invalid-json") + for _, c := range cases { + got := decodeEventCursor(context.Background(), c, now) + if !got.StartAt.IsZero() { + t.Errorf("decodeEventCursor(%q) = %+v, want zero-value cursor", c, got) + } + } +} + +// TestDecodeEventCursorResetsStaleCursor covers a valid cursor whose StartAt has aged past +// the audit log retention window, which must self-heal like a corrupt cursor. +func TestDecodeEventCursorResetsStaleCursor(t *testing.T) { + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + + stale := eventPageCursor{StartAt: now.Add(-auditLogRetention - time.Hour), StartAfterEventID: "x"} + encoded, err := encodeEventCursor(stale) + if err != nil { + t.Fatalf("encodeEventCursor() error = %v", err) + } + + got := decodeEventCursor(context.Background(), encoded, now) + if !got.StartAt.IsZero() || got.StartAfterEventID != "" { + t.Errorf("decodeEventCursor() = %+v, want zero-value cursor for a stale StartAt", got) + } + + fresh := eventPageCursor{StartAt: now.Add(-auditLogRetention + time.Hour), StartAfterEventID: "y"} + encoded, err = encodeEventCursor(fresh) + if err != nil { + t.Fatalf("encodeEventCursor() error = %v", err) + } + + got = decodeEventCursor(context.Background(), encoded, now) + if !got.StartAt.Equal(fresh.StartAt) || got.StartAfterEventID != fresh.StartAfterEventID { + t.Errorf("decodeEventCursor() = %+v, want unchanged %+v (within retention)", got, fresh) + } +} + +func TestAdvanceEventCursorAdvancesToLastRawBoundary(t *testing.T) { + cursor := eventPageCursor{StartAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + lastRawBoundary := eventPageCursor{StartAt: cursor.StartAt.Add(time.Minute), StartAfterEventID: "evt-999"} + + next, advanced := advanceEventCursor(cursor, nil, lastRawBoundary, true, cursor.StartAt.Add(auditLogTrailingLag)) + + if !advanced || next != lastRawBoundary { + t.Errorf("next = %+v, advanced = %v, want %+v, true", next, advanced, lastRawBoundary) + } +} + +// TestAdvanceEventCursorFallsBackToLastParsedRow covers a full page where only the last raw +// row fails to parse: lastRawBoundary is zero-value, but the other rows parsed fine and must +// still advance the cursor instead of stalling on a page that otherwise made progress. +func TestAdvanceEventCursorFallsBackToLastParsedRow(t *testing.T) { + cursor := eventPageCursor{StartAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + rows := []auditLogRow{ + {EventID: "evt-1", EventTime: cursor.StartAt.Add(time.Minute)}, + {EventID: "evt-2", EventTime: cursor.StartAt.Add(2 * time.Minute)}, + } + + next, advanced := advanceEventCursor(cursor, rows, eventPageCursor{}, true, cursor.StartAt.Add(auditLogTrailingLag)) + + want := eventPageCursor{StartAt: rows[1].EventTime, StartAfterEventID: rows[1].EventID} + if !advanced || next != want { + t.Errorf("next = %+v, advanced = %v, want %+v, true", next, advanced, want) + } +} + +// TestAdvanceEventCursorFullyMalformedPageDoesNotStall covers a full page where every row +// failed to parse: neither lastRawBoundary nor rows can advance the cursor, so this must +// signal advanced=false (letting the caller stop claiming HasMore) instead of looping forever +// on an unchanged cursor. It also must not panic indexing an empty rows slice. +func TestAdvanceEventCursorFullyMalformedPageDoesNotStall(t *testing.T) { + cursor := eventPageCursor{StartAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), StartAfterEventID: "evt-1"} + + next, advanced := advanceEventCursor(cursor, nil, eventPageCursor{}, true, cursor.StartAt.Add(auditLogTrailingLag)) + + if advanced || next != cursor { + t.Errorf("next = %+v, advanced = %v, want unchanged cursor %+v, false", next, advanced, cursor) + } +} + +// TestAdvanceEventCursorDrainedJumpsToLagCutoff verifies a drained page advances straight to +// lagCutoff: rows are already bounded by it (see queryAuditLog), so draining proves nothing +// else exists up to that point. +func TestAdvanceEventCursorDrainedJumpsToLagCutoff(t *testing.T) { + cursor := eventPageCursor{StartAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)} + lagCutoff := cursor.StartAt.Add(4 * time.Hour) + + next, advanced := advanceEventCursor(cursor, nil, eventPageCursor{}, false, lagCutoff) + + if !advanced || !next.StartAt.Equal(lagCutoff) || next.StartAfterEventID != "" { + t.Errorf("next = %+v, advanced = %v, want StartAt=%v with no tiebreaker, true", next, advanced, lagCutoff) + } +} + +func TestMapAuditRowToResource(t *testing.T) { + client := principalKindTestClient(t, "u-1", "Users") + workspaceLookup := map[int64]string{123: "my-workspace"} + accountId := "acct-1" + + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: accountId} + workspaceParent := &v2.ResourceId{ResourceType: workspaceResourceType.Id, Resource: "my-workspace"} + + type wantResource struct { + resourceType string + resource string + parentType string + parentID string + } + + cases := []struct { + name string + row auditLogRow + want []wantResource + }{ + { + name: "account-level group create", + row: auditLogRow{ + ActionName: "createGroup", + ServiceName: "accounts", + WorkspaceID: 0, + RequestParams: map[string]string{"targetGroupId": "g-1"}, + }, + want: []wantResource{ + {groupResourceType.Id, groupResourceId(context.Background(), "g-1", accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "workspace-scoped group change stays account-parented", + row: auditLogRow{ + ActionName: "removeGroup", + ServiceName: "accounts", + WorkspaceID: 123, + RequestParams: map[string]string{"targetGroupId": "g-1"}, + }, + want: []wantResource{ + // Groups are only ever synced as children of the account when the Account + // API is reachable, regardless of which workspace the change occurred in. + {groupResourceType.Id, groupResourceId(context.Background(), "g-1", accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "workspace-scoped acl change also refreshes the workspace-access role", + row: auditLogRow{ + ActionName: "changeDatabricksWorkspaceAcl", + ServiceName: "accounts", + WorkspaceID: 123, + }, + want: []wantResource{ + {workspaceResourceType.Id, "my-workspace", accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(WorkspaceAccessRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + }, + }, + { + name: "setAdmin refreshes the user and the account-admin role", + row: auditLogRow{ + ActionName: "setAdmin", + ServiceName: "accounts", + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(AccountAdminRole, accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "setAccountAdmin refreshes the user and the account-admin role", + row: auditLogRow{ + ActionName: "setAccountAdmin", + ServiceName: "accounts", + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(AccountAdminRole, accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "removeAccountAdmin refreshes the user and the account-admin role", + row: auditLogRow{ + ActionName: "removeAccountAdmin", + ServiceName: "accounts", + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(AccountAdminRole, accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "deactivateUser refreshes the user", + row: auditLogRow{ + ActionName: "deactivateUser", + ServiceName: "accounts", + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + }, + }, + { + name: "account-level addPermissionAssignment resolves the workspace from request_params", + row: auditLogRow{ + ActionName: "addPermissionAssignment", + ServiceName: "workspace", + WorkspaceID: 0, + RequestParams: map[string]string{"principal_id": "u-1", "account_id": accountId, "workspace_id": "123"}, + }, + want: []wantResource{ + {workspaceResourceType.Id, "my-workspace", accountResourceType.Id, accountId}, + }, + }, + { + name: "account-level updatePermissionAssignment resolves the workspace from request_params", + row: auditLogRow{ + ActionName: "updatePermissionAssignment", + ServiceName: "workspace", + WorkspaceID: 0, + RequestParams: map[string]string{"principal_id": "u-1", "workspace_id": "123"}, + }, + want: []wantResource{ + {workspaceResourceType.Id, "my-workspace", accountResourceType.Id, accountId}, + }, + }, + { + name: "updatePermissionAssignment uses the row's workspace_id", + row: auditLogRow{ + ActionName: "updatePermissionAssignment", + ServiceName: "workspace", + WorkspaceID: 123, + RequestParams: map[string]string{"principal_id": "u-1"}, + }, + want: []wantResource{ + {workspaceResourceType.Id, "my-workspace", accountResourceType.Id, accountId}, + }, + }, + { + name: "deletePermissionAssignment for a workspace outside sync scope is skipped", + row: auditLogRow{ + ActionName: "deletePermissionAssignment", + ServiceName: "workspace", + RequestParams: map[string]string{"principal_id": "u-1", "workspace_id": "999"}, + }, + }, + { + name: "permission assignment with an unparseable workspace_id is skipped", + row: auditLogRow{ + ActionName: "deletePermissionAssignment", + ServiceName: "workspace", + RequestParams: map[string]string{"principal_id": "u-1", "workspace_id": "not-a-number"}, + }, + }, + { + name: "updateUser stays account-parented, but workspace roles still refresh", + row: auditLogRow{ + ActionName: "updateUser", + ServiceName: "accounts", + WorkspaceID: 123, + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(WorkspaceAccessRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(SQLAccessRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(ClusterCreateRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(InstancePoolCreateRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + }, + }, + { + name: "updateGroup in a workspace refreshes the group and every workspace entitlement role", + row: auditLogRow{ + ActionName: "updateGroup", + ServiceName: "accounts", + WorkspaceID: 123, + RequestParams: map[string]string{"targetGroupId": "g-1"}, + }, + want: []wantResource{ + {groupResourceType.Id, groupResourceId(context.Background(), "g-1", accountParent), accountResourceType.Id, accountId}, + {roleResourceType.Id, roleResourceId(WorkspaceAccessRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(SQLAccessRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(ClusterCreateRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + {roleResourceType.Id, roleResourceId(InstancePoolCreateRole, workspaceParent), workspaceResourceType.Id, "my-workspace"}, + }, + }, + { + name: "account-level updateUser refreshes only the user", + row: auditLogRow{ + ActionName: "updateUser", + ServiceName: "accounts", + WorkspaceID: 0, + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + want: []wantResource{ + {userResourceType.Id, "u-1", accountResourceType.Id, accountId}, + }, + }, + { + name: "account-level updateGroup refreshes only the group", + row: auditLogRow{ + ActionName: "updateGroup", + ServiceName: "accounts", + WorkspaceID: 0, + RequestParams: map[string]string{"targetGroupId": "g-1"}, + }, + want: []wantResource{ + {groupResourceType.Id, groupResourceId(context.Background(), "g-1", accountParent), accountResourceType.Id, accountId}, + }, + }, + { + name: "unknown action is skipped", + row: auditLogRow{ActionName: "someUnityCatalogAction"}, + }, + { + name: "known action_name under an unmapped service_name is skipped", + row: auditLogRow{ActionName: "delete", ServiceName: "clusters"}, + }, + { + name: "principal delete is left to full sync", + row: auditLogRow{ActionName: "delete", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "u-1"}}, + }, + { + name: "unresolvable workspace is skipped", + row: auditLogRow{ + ActionName: "add", + ServiceName: "accounts", + WorkspaceID: 999, + RequestParams: map[string]string{"targetUserId": "u-1"}, + }, + }, + { + name: "missing id param is skipped", + row: auditLogRow{ActionName: "add", ServiceName: "accounts", WorkspaceID: 0}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), tc.row, accountId, workspaceLookup) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != len(tc.want) { + t.Fatalf("got %d affected resources, want %d: %+v", len(got), len(tc.want), got) + } + for i, w := range tc.want { + if got[i].resourceId.ResourceType != w.resourceType || got[i].resourceId.Resource != w.resource { + t.Errorf("[%d] resourceId = %+v, want type=%s id=%s", i, got[i].resourceId, w.resourceType, w.resource) + } + if got[i].parentResourceId.ResourceType != w.parentType || got[i].parentResourceId.Resource != w.parentID { + t.Errorf("[%d] parentResourceId = %+v, want type=%s id=%s", i, got[i].parentResourceId, w.parentType, w.parentID) + } + } + }) + } +} + +func assertGroupRefresh(t *testing.T, got []affectedResource, wantGroupId string) { + t.Helper() + if len(got) != 1 || got[0].grant != nil { + t.Fatalf("got %+v, want exactly one group refresh", got) + } + if id := got[0].resourceId; id.GetResourceType() != groupResourceType.Id || id.GetResource() != wantGroupId { + t.Errorf("resourceId = %+v, want type=%s id=%s", id, groupResourceType.Id, wantGroupId) + } +} + +// principalKindTestClient serves GetUser/GetGroup/GetServicePrincipal lookups for a single +// native id, returning 200 for kind ("Users", "Groups", or "ServicePrincipals") and 404 for +// the other two - or 500 for all three if kind is "error". +func principalKindTestClient(t *testing.T, nativeId, kind string) *databricks.Client { + t.Helper() + return newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + if !strings.HasSuffix(r.URL.Path, "/"+nativeId) { + writeJSONNotFound(w) + return + } + if kind == "error" { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(`{"message":"boom"}`)) + return + } + if strings.Contains(r.URL.Path, "/"+kind+"/") { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{}`)) + return + } + writeJSONNotFound(w) + }) +} + +// TestMapAuditRowToResourceResolvesPrincipalType covers principal-lifecycle rows whose +// targetUserId names a service principal, a group, or nothing that still exists. +func TestMapAuditRowToResourceResolvesPrincipalType(t *testing.T) { + accountId := "acct-1" + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: accountId} + workspaceParent := &v2.ResourceId{ResourceType: workspaceResourceType.Id, Resource: "my-workspace"} + workspaceLookup := map[int64]string{123: "my-workspace"} + accountAdmin := roleResourceId(AccountAdminRole, accountParent) + + type want struct{ resourceType, resource string } + cases := []struct { + name string + nativeId string + kind string + row auditLogRow + want []want + }{ + { + name: "add of a service principal", nativeId: "sp-1", kind: "ServicePrincipals", + row: auditLogRow{ActionName: "add", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "sp-1"}}, + want: []want{{servicePrincipalResourceType.Id, "sp-1"}}, + }, + { + name: "setAdmin on a service principal", nativeId: "sp-1", kind: "ServicePrincipals", + row: auditLogRow{ActionName: "setAdmin", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "sp-1"}}, + want: []want{{servicePrincipalResourceType.Id, "sp-1"}, {roleResourceType.Id, accountAdmin}}, + }, + { + name: "updateUser on a service principal in a workspace", nativeId: "sp-1", kind: "ServicePrincipals", + row: auditLogRow{ActionName: "updateUser", ServiceName: "accounts", WorkspaceID: 123, RequestParams: map[string]string{"targetUserId": "sp-1"}}, + want: []want{ + {servicePrincipalResourceType.Id, "sp-1"}, + {roleResourceType.Id, roleResourceId(WorkspaceAccessRole, workspaceParent)}, + {roleResourceType.Id, roleResourceId(SQLAccessRole, workspaceParent)}, + {roleResourceType.Id, roleResourceId(ClusterCreateRole, workspaceParent)}, + {roleResourceType.Id, roleResourceId(InstancePoolCreateRole, workspaceParent)}, + }, + }, + { + name: "add naming a group uses the full-sync group id", nativeId: "g-1", kind: "Groups", + row: auditLogRow{ActionName: "add", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "g-1"}}, + want: []want{{groupResourceType.Id, groupResourceId(context.Background(), "g-1", accountParent)}}, + }, + { + name: "setAdmin on an unknown principal still refreshes the role", nativeId: "gone-1", kind: "none", + row: auditLogRow{ActionName: "setAdmin", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "gone-1"}}, + want: []want{{userResourceType.Id, "gone-1"}, {roleResourceType.Id, accountAdmin}}, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + client := principalKindTestClient(t, tc.nativeId, tc.kind) + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), tc.row, accountId, workspaceLookup) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != len(tc.want) { + t.Fatalf("got %d affected resources, want %d: %+v", len(got), len(tc.want), got) + } + for i, w := range tc.want { + if got[i].resourceId.GetResourceType() != w.resourceType || got[i].resourceId.GetResource() != w.resource { + t.Errorf("[%d] resourceId = %+v, want type=%s id=%s", i, got[i].resourceId, w.resourceType, w.resource) + } + } + if p := got[0].parentResourceId; p.GetResourceType() != accountResourceType.Id || p.GetResource() != accountId { + t.Errorf("parentResourceId = %+v, want the account", p) + } + }) + } + + t.Run("a lookup error is returned", func(t *testing.T) { + client := principalKindTestClient(t, "sp-1", "error") + row := auditLogRow{ActionName: "add", ServiceName: "accounts", RequestParams: map[string]string{"targetUserId": "sp-1"}} + if _, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, accountId, workspaceLookup); err == nil { + t.Fatal("mapAuditRowToResource() error = nil, want the lookup failure") + } + }) +} + +// TestResolvePrincipalTypeServicePrincipalFirst verifies a UUID targetUserName sends the +// service principal lookup first, and a username keeps the user-first order. +func TestResolvePrincipalTypeServicePrincipalFirst(t *testing.T) { + cases := []struct { + name string + targetName string + wantPaths []string + }{ + { + name: "application id tries service principals first", + targetName: "8f2e6c1a-3b4d-4e5f-9a0b-1c2d3e4f5a6b", + wantPaths: []string{"/ServicePrincipals/sp-1"}, + }, + { + name: "username keeps the user-first order", + targetName: "someone@example.com", + wantPaths: []string{"/Users/sp-1", "/Groups/sp-1", "/ServicePrincipals/sp-1"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var mu sync.Mutex + var paths []string + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + paths = append(paths, r.URL.Path[strings.Index(r.URL.Path, "/scim/v2")+len("/scim/v2"):]) + mu.Unlock() + if strings.HasSuffix(r.URL.Path, "/ServicePrincipals/sp-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + writeJSONNotFound(w) + }) + row := auditLogRow{ + ActionName: "add", + ServiceName: "accounts", + RequestParams: map[string]string{"targetUserId": "sp-1", "targetUserName": tc.targetName}, + } + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, "acct-1", nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != 1 || got[0].resourceId.GetResourceType() != servicePrincipalResourceType.Id { + t.Fatalf("got %+v, want one service principal", got) + } + if strings.Join(paths, ",") != strings.Join(tc.wantPaths, ",") { + t.Errorf("lookups = %v, want %v", paths, tc.wantPaths) + } + }) + } +} + +// TestMapAuditRowToResourceGrantMapping covers the group-membership actions that map to an +// atomic CREATE_GRANT/CREATE_REVOKE instead of a RESOURCE_CHANGE. +func TestMapAuditRowToResourceGrantMapping(t *testing.T) { + accountId := "acct-1" + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: accountId} + wantGroupId := groupResourceId(context.Background(), "g-1", accountParent) + wantEntitlementId := ent.NewEntitlementID(&v2.Resource{Id: &v2.ResourceId{ResourceType: groupResourceType.Id, Resource: wantGroupId}}, groupMemberEntitlement) + + cases := []struct { + name string + actionName string + wantRevoke bool + }{ + {"addPrincipalToGroup grants", "addPrincipalToGroup", false}, + {"removePrincipalFromGroup revokes", "removePrincipalFromGroup", true}, + {"addPrincipalsToGroup grants", "addPrincipalsToGroup", false}, + {"removePrincipalsFromGroup revokes", "removePrincipalsFromGroup", true}, + } + + client := principalKindTestClient(t, "u-1", "Users") + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + row := auditLogRow{ + ActionName: tc.actionName, + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "u-1"}, + } + + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != 1 || got[0].grant == nil { + t.Fatalf("got %+v, want exactly one grant-mapped affected resource", got) + } + + g := got[0].grant + if g.revoke != tc.wantRevoke { + t.Errorf("revoke = %v, want %v", g.revoke, tc.wantRevoke) + } + if g.entitlement.GetId() != wantEntitlementId { + t.Errorf("entitlement id = %q, want %q", g.entitlement.GetId(), wantEntitlementId) + } + if g.principal.GetId().GetResourceType() != userResourceType.Id || g.principal.GetId().GetResource() != "u-1" { + t.Errorf("principal = %+v, want type=%s id=u-1", g.principal.GetId(), userResourceType.Id) + } + }) + } + + t.Run("missing principal id still refreshes the group", func(t *testing.T) { + row := auditLogRow{ + ActionName: "addPrincipalToGroup", + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1"}, + } + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + assertGroupRefresh(t, got, wantGroupId) + }) + + t.Run("principal resolves to a nested group", func(t *testing.T) { + groupClient := principalKindTestClient(t, "g-2", "Groups") + row := auditLogRow{ + ActionName: "addPrincipalToGroup", + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "g-2"}, + } + got, _, err := mapAuditRowToResource(context.Background(), groupClient, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != 1 || got[0].grant == nil { + t.Fatalf("got %+v, want exactly one grant-mapped affected resource", got) + } + wantId := groupResourceId(context.Background(), "g-2", accountParent) + if p := got[0].grant.principal.GetId(); p.GetResourceType() != groupResourceType.Id || p.GetResource() != wantId { + t.Errorf("principal = %+v, want type=%s id=%s", p, groupResourceType.Id, wantId) + } + }) + + t.Run("principal resolves to a service principal", func(t *testing.T) { + spClient := principalKindTestClient(t, "sp-1", "ServicePrincipals") + row := auditLogRow{ + ActionName: "addPrincipalToGroup", + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "sp-1"}, + } + got, _, err := mapAuditRowToResource(context.Background(), spClient, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != 1 || got[0].grant == nil { + t.Fatalf("got %+v, want exactly one grant-mapped affected resource", got) + } + if p := got[0].grant.principal.GetId(); p.GetResourceType() != servicePrincipalResourceType.Id || p.GetResource() != "sp-1" { + t.Errorf("principal = %+v, want type=%s id=sp-1", p, servicePrincipalResourceType.Id) + } + }) + + t.Run("principal not found anywhere still refreshes the group", func(t *testing.T) { + notFoundClient := principalKindTestClient(t, "ghost", "none") + row := auditLogRow{ + ActionName: "addPrincipalToGroup", + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "ghost"}, + } + got, _, err := mapAuditRowToResource(context.Background(), notFoundClient, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + assertGroupRefresh(t, got, wantGroupId) + }) + + t.Run("a real lookup error propagates instead of being swallowed", func(t *testing.T) { + errClient := principalKindTestClient(t, "u-1", "error") + row := auditLogRow{ + ActionName: "addPrincipalToGroup", + ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "u-1"}, + } + if _, _, err := mapAuditRowToResource(context.Background(), errClient, newPrincipalLookups(nil), row, accountId, nil); err == nil { + t.Error("mapAuditRowToResource() error = nil, want a propagated lookup error") + } + }) +} + +// multiPrincipalTestClient returns a client whose account SCIM lookups are served by scimKindsHandler. +func multiPrincipalTestClient(t *testing.T, kinds map[string]string) (*databricks.Client, func() []string) { + t.Helper() + handler, lookups := scimKindsHandler(kinds) + return newProbeTestClient(t, handler), lookups +} + +// scimKindsHandler serves account SCIM lookups from kinds (native id to "Users", "Groups", +// "ServicePrincipals", or an HTTP status code as a string), 404s everything else, and records +// each lookup's path below /scim/v2. +func scimKindsHandler(kinds map[string]string) (http.HandlerFunc, func() []string) { + var mu sync.Mutex + var paths []string + handler := func(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path[strings.Index(r.URL.Path, "/scim/v2")+len("/scim/v2"):] + mu.Lock() + paths = append(paths, path) + mu.Unlock() + + parts := strings.Split(strings.TrimPrefix(path, "/"), "/") + if len(parts) != 2 { + writeJSONNotFound(w) + return + } + kind := kinds[parts[1]] + if code, err := strconv.Atoi(kind); err == nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(code) + fmt.Fprint(w, `{"detail":"lookup failed"}`) + return + } + if kind == parts[0] { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + writeJSONNotFound(w) + } + return handler, func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(paths) + } +} + +// TestMapAuditRowToResourceMultiMember covers membership rows whose targetUserId lists several +// comma-separated members. +func TestMapAuditRowToResourceMultiMember(t *testing.T) { + accountId := "acct-1" + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: accountId} + wantGroupId := groupResourceId(context.Background(), "g-1", accountParent) + nestedGroupId := groupResourceId(context.Background(), "g-2", accountParent) + + type wantGrant struct{ resourceType, resource string } + cases := []struct { + name string + action string + params map[string]string + kinds map[string]string + wantGrants []wantGrant + wantRevoke bool + wantRefresh bool + wantLookups int + }{ + { + name: "three members are each granted", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": "u-1,u-2,u-3"}, + kinds: map[string]string{"u-1": "Users", "u-2": "Users", "u-3": "Users"}, + wantGrants: []wantGrant{ + {userResourceType.Id, "u-1"}, {userResourceType.Id, "u-2"}, {userResourceType.Id, "u-3"}, + }, + wantLookups: 3, + }, + { + name: "two members are each revoked", + action: "removePrincipalsFromGroup", + params: map[string]string{"targetUserId": "u-1,u-2"}, + kinds: map[string]string{"u-1": "Users", "u-2": "Users"}, + wantGrants: []wantGrant{{userResourceType.Id, "u-1"}, {userResourceType.Id, "u-2"}}, + wantRevoke: true, + wantLookups: 2, + }, + { + name: "mixed principal kinds resolve separately", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": "u-1,sp-1,g-2"}, + kinds: map[string]string{"u-1": "Users", "sp-1": "ServicePrincipals", "g-2": "Groups"}, + wantGrants: []wantGrant{ + {userResourceType.Id, "u-1"}, {servicePrincipalResourceType.Id, "sp-1"}, {groupResourceType.Id, nestedGroupId}, + }, + wantLookups: 1 + 3 + 2, + }, + { + name: "single id on a plural action matches the singular output", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": "u-1"}, + kinds: map[string]string{"u-1": "Users"}, + wantGrants: []wantGrant{{userResourceType.Id, "u-1"}}, + wantLookups: 1, + }, + { + name: "an unknown member refreshes the group once", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": "u-1,gone-1,gone-2,u-2"}, + kinds: map[string]string{"u-1": "Users", "u-2": "Users"}, + wantGrants: []wantGrant{{userResourceType.Id, "u-1"}, {userResourceType.Id, "u-2"}}, + wantRefresh: true, + wantLookups: 1 + 3 + 3 + 1, + }, + { + name: "spaces, blanks and repeats are cleaned up", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": " u-1 , u-2,u-1,, "}, + kinds: map[string]string{"u-1": "Users", "u-2": "Users"}, + wantGrants: []wantGrant{{userResourceType.Id, "u-1"}, {userResourceType.Id, "u-2"}}, + wantLookups: 2, + }, + { + name: "aligned application ids look up service principals first", + action: "addPrincipalsToGroup", + params: map[string]string{ + "targetUserId": "sp-1,u-1", + "targetUserName": "8f2e6c1a-3b4d-4e5f-9a0b-1c2d3e4f5a6b,someone@example.com", + }, + kinds: map[string]string{"sp-1": "ServicePrincipals", "u-1": "Users"}, + wantGrants: []wantGrant{{servicePrincipalResourceType.Id, "sp-1"}, {userResourceType.Id, "u-1"}}, + wantLookups: 2, + }, + { + name: "too many members refresh the group without lookups", + action: "addPrincipalsToGroup", + params: map[string]string{"targetUserId": manyIDs(maxAuditMembershipLookups + 1)}, + wantRefresh: true, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + client, lookups := multiPrincipalTestClient(t, tc.kinds) + params := map[string]string{"targetGroupId": "g-1"} + for k, v := range tc.params { + params[k] = v + } + row := auditLogRow{EventID: "evt-1", ActionName: tc.action, ServiceName: auditServiceAccounts, RequestParams: params} + + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + + wantLen := len(tc.wantGrants) + if tc.wantRefresh { + wantLen++ + } + if len(got) != wantLen { + t.Fatalf("got %d affected resources, want %d: %+v", len(got), wantLen, got) + } + for i, w := range tc.wantGrants { + g := got[i].grant + if g == nil { + t.Fatalf("[%d] = %+v, want a grant", i, got[i]) + } + if g.revoke != tc.wantRevoke { + t.Errorf("[%d] revoke = %v, want %v", i, g.revoke, tc.wantRevoke) + } + if g.entitlement.GetResource().GetId().GetResource() != wantGroupId { + t.Errorf("[%d] entitlement resource = %q, want %q", i, g.entitlement.GetResource().GetId().GetResource(), wantGroupId) + } + if p := g.principal.GetId(); p.GetResourceType() != w.resourceType || p.GetResource() != w.resource { + t.Errorf("[%d] principal = %+v, want type=%s id=%s", i, p, w.resourceType, w.resource) + } + } + if tc.wantRefresh { + assertGroupRefresh(t, got[len(got)-1:], wantGroupId) + } + if n := len(lookups()); n != tc.wantLookups { + t.Errorf("lookups = %d (%v), want %d", n, lookups(), tc.wantLookups) + } + }) + } + + t.Run("a retryable error on any member fails the row", func(t *testing.T) { + client, _ := multiPrincipalTestClient(t, map[string]string{"u-1": "Users", "u-2": "503"}) + row := auditLogRow{ + ActionName: "addPrincipalsToGroup", ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "u-1,u-2,u-3"}, + } + got, _, err := mapAuditRowToResource(context.Background(), client, newPrincipalLookups(nil), row, accountId, nil) + if err == nil || !isRetryableLookupError(err) { + t.Fatalf("mapAuditRowToResource() error = %v, want a retryable error", err) + } + if len(got) != 0 { + t.Errorf("got %+v, want nothing", got) + } + }) + + t.Run("a non-retryable error keeps the other members and refreshes the group", func(t *testing.T) { + client, _ := multiPrincipalTestClient(t, map[string]string{"u-1": "Users", "u-2": "405", "u-3": "Users"}) + row := auditLogRow{ + ActionName: "addPrincipalsToGroup", ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "u-1,u-2,u-3"}, + } + lookups := newPrincipalLookups(nil) + got, _, err := mapAuditRowToResource(context.Background(), client, lookups, row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v, want the failure absorbed", err) + } + if len(got) != 3 || got[0].grant.principal.GetId().GetResource() != "u-1" || got[1].grant.principal.GetId().GetResource() != "u-3" { + t.Fatalf("got %+v, want grants for u-1 and u-3 plus a group refresh", got) + } + assertGroupRefresh(t, got[2:], wantGroupId) + if lookups.memberFailures != 1 || lookups.failures.Load() != 1 { + t.Errorf("memberFailures = %d, failures = %d, want 1 and 1", lookups.memberFailures, lookups.failures.Load()) + } + }) + + t.Run("members past the poll budget refresh the group without lookups", func(t *testing.T) { + client, calls := multiPrincipalTestClient(t, map[string]string{"u-1": "Users", "u-2": "Users", "u-3": "Users"}) + lookups := newPrincipalLookups(nil) + lookups.types["u-3"] = userResourceType + lookups.remainingMemberLookups = 1 + row := auditLogRow{ + ActionName: "addPrincipalsToGroup", ServiceName: auditServiceAccounts, + RequestParams: map[string]string{"targetGroupId": "g-1", "targetUserId": "u-1,u-2,u-3"}, + } + got, _, err := mapAuditRowToResource(context.Background(), client, lookups, row, accountId, nil) + if err != nil { + t.Fatalf("mapAuditRowToResource() error = %v", err) + } + if len(got) != 3 || got[0].grant.principal.GetId().GetResource() != "u-1" || got[1].grant.principal.GetId().GetResource() != "u-3" { + t.Fatalf("got %+v, want grants for u-1 and the cached u-3 plus a group refresh", got) + } + assertGroupRefresh(t, got[2:], wantGroupId) + if n := len(calls()); n != 1 || lookups.membersOverBudget != 1 { + t.Errorf("lookups = %v, membersOverBudget = %d, want one lookup and one member over budget", calls(), lookups.membersOverBudget) + } + }) +} + +func manyIDs(n int) string { + ids := make([]string, n) + for i := range ids { + ids[i] = fmt.Sprintf("u-%d", i) + } + return strings.Join(ids, ",") +} + +func TestParseAuditLogRowsDedupesNothingAndParsesFields(t *testing.T) { + result := &databricks.StatementResult{ + Columns: []string{"event_id", "event_time", "workspace_id", "action_name", "service_name", "request_params"}, + Rows: [][]string{ + {"evt-1", "2026-01-01 00:00:00.000", "123", "createGroup", "accounts", `{"targetGroupId":"g-1"}`}, + {"evt-2", "2026-01-01T00:01:00Z", "0", "add", "accounts", `{"targetUserId":"u-1"}`}, + }, + } + + rows, _, err := parseAuditLogRows(context.Background(), result) + if err != nil { + t.Fatalf("parseAuditLogRows() error = %v", err) + } + if len(rows) != 2 { + t.Fatalf("len(rows) = %d, want 2", len(rows)) + } + if rows[0].WorkspaceID != 123 || rows[0].ServiceName != "accounts" || rows[0].RequestParams["targetGroupId"] != "g-1" { + t.Errorf("row[0] = %+v", rows[0]) + } + if rows[1].WorkspaceID != 0 || rows[1].RequestParams["targetUserId"] != "u-1" { + t.Errorf("row[1] = %+v", rows[1]) + } +} + +func TestParseAuditLogRowsMissingColumnErrors(t *testing.T) { + result := &databricks.StatementResult{ + Columns: []string{"event_id", "event_time"}, + Rows: [][]string{{"evt-1", "2026-01-01 00:00:00.000"}}, + } + + if _, _, err := parseAuditLogRows(context.Background(), result); err == nil { + t.Error("parseAuditLogRows() error = nil, want error for missing required column") + } +} + +// TestParseAuditLogRowsSkipsMalformedRow verifies a single poisoned row (unparseable +// event_time here) is skipped rather than failing the whole page. +func TestParseAuditLogRowsSkipsMalformedRow(t *testing.T) { + result := &databricks.StatementResult{ + Columns: []string{"event_id", "event_time", "workspace_id", "action_name", "service_name", "request_params"}, + Rows: [][]string{ + {"evt-1", "not-a-timestamp", "123", "createGroup", "accounts", `{"targetGroupId":"g-1"}`}, + {"evt-2", "2026-01-01T00:01:00Z", "0", "add", "accounts", `{"targetUserId":"u-1"}`}, + }, + } + + rows, _, err := parseAuditLogRows(context.Background(), result) + if err != nil { + t.Fatalf("parseAuditLogRows() error = %v, want the malformed row skipped instead", err) + } + if len(rows) != 1 { + t.Fatalf("len(rows) = %d, want 1 (malformed row skipped)", len(rows)) + } + if rows[0].EventID != "evt-2" { + t.Errorf("rows[0].EventID = %q, want %q", rows[0].EventID, "evt-2") + } +} + +// redirectTransport rewrites every outgoing request to target, since workspaceUrl always +// builds a "." subdomain a local httptest.Server can't listen on directly. +type redirectTransport struct { + target *url.URL +} + +func (t *redirectTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + originalHost := req.URL.Host + req.URL.Scheme = t.target.Scheme + req.URL.Host = t.target.Host + req.Host = t.target.Host + // Preserve the workspace-specific host the client intended, since it's otherwise lost + // once every request is rewritten to the same local test server. + req.Header.Set("X-Test-Original-Host", originalHost) + return http.DefaultTransport.RoundTrip(req) +} + +// TestListEventsSkipsQueryPastLagCutoff covers the bootstrap default landing exactly at +// lagCutoff (auditLogLookback == auditLogTrailingLag): ListEvents must not query an +// inverted (start > end) range. +func TestListEventsSkipsQueryPastLagCutoff(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + t.Fatalf("unexpected request %s %s: should have been skipped by the lagCutoff guard", r.Method, r.URL.Path) + }) + + feed := newAuditEventFeed(client, nil, "wh-1") + events, streamState, _, err := feed.ListEvents(context.Background(), nil, &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != 0 { + t.Errorf("len(events) = %d, want 0", len(events)) + } + if streamState.HasMore { + t.Error("HasMore = true, want false") + } + if streamState.Cursor == "" { + t.Error("Cursor is empty, want the bootstrap cursor to still be encoded") + } +} + +// TestListEventsEndToEnd exercises ListEvents against a mocked Statement Execution API, +// verifying the service_name query filter, resource mapping, and rate-limit propagation. +func TestListEventsEndToEnd(t *testing.T) { + const wantLimit = 100 + const wantRemaining = 42 + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // ListEvents always lists workspaces via the Account API before querying the audit log. + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces") { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode([]map[string]any{ + {"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}, + }); err != nil { + t.Fatalf("failed to encode mock workspaces response: %v", err) + } + return + } + + // resolveWarehouseWorkspace probes every candidate workspace (including a lone + // one) via WarehouseExists before running the audit-log query. + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":"wh-1"}`) + return + } + + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/scim/v2/Users/u-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements") { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + + var body struct { + Statement string `json:"statement"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Fatalf("failed to decode statement request body: %v", err) + } + if !strings.Contains(body.Statement, "service_name") { + t.Errorf("statement does not select/filter service_name: %s", body.Statement) + } + if !strings.Contains(body.Statement, "'accounts'") { + t.Errorf("statement does not filter service_name IN ('accounts', ...): %s", body.Statement) + } + if !strings.Contains(body.Statement, "response.status_code = 200") { + t.Errorf("statement does not filter out failed requests with response.status_code = 200: %s", body.Statement) + } + + w.Header().Set("X-Ratelimit-Limit", strconv.Itoa(wantLimit)) + w.Header().Set("X-Ratelimit-Remaining", strconv.Itoa(wantRemaining)) + w.Header().Set("Content-Type", "application/json") + + resp := map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "schema": map[string]any{ + "columns": []map[string]any{ + {"name": "event_id"}, + {"name": "event_time"}, + {"name": "workspace_id"}, + {"name": "action_name"}, + {"name": "service_name"}, + {"name": "request_params"}, + }, + }, + }, + "result": map[string]any{ + "data_array": [][]string{ + {"evt-1", "2026-01-01T00:00:00Z", "0", "add", "accounts", `{"targetUserId":"u-1"}`}, + }, + }, + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + t.Fatalf("failed to encode mock statement response: %v", err) + } + })) + defer server.Close() + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + auth := &databricks.NoAuth{} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", auth, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + // Mirrors what Validate() sets before any sync/event-feed call runs in production. + + feed := newAuditEventFeed(client, nil, "wh-1") + + events, streamState, annos, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != 1 { + t.Fatalf("len(events) = %d, want 1: %+v", len(events), events) + } + + rc := events[0].GetResourceChangeEvent() + if rc.GetResourceId().GetResourceType() != userResourceType.Id || rc.GetResourceId().GetResource() != "u-1" { + t.Errorf("event resource = %+v, want type=%s id=u-1", rc.GetResourceId(), userResourceType.Id) + } + if streamState.Cursor == "" { + t.Error("StreamState.Cursor is empty, want an encoded cursor") + } + + rld := &v2.RateLimitDescription{} + ok, err := annos.Pick(rld) + if err != nil { + t.Fatalf("annos.Pick() error = %v", err) + } + if !ok { + t.Fatal("annotations do not carry a RateLimitDescription, want the rate-limit headers propagated") + } + if rld.GetLimit() != wantLimit || rld.GetRemaining() != wantRemaining { + t.Errorf("RateLimitDescription = %+v, want limit=%d remaining=%d", rld, wantLimit, wantRemaining) + } +} + +// TestListEventsEmitsCreateGrantEvent verifies ListEvents wires a grant-mapped audit row all +// the way to a CreateGrantEvent, not a ResourceChangeEvent. +func TestListEventsEmitsCreateGrantEvent(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces") { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + return + } + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":"wh-1"}`) + return + } + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/scim/v2/Users/u-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements") { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + + w.Header().Set("Content-Type", "application/json") + resp := map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "schema": map[string]any{ + "columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }, + }, + }, + "result": map[string]any{ + "data_array": [][]string{ + {"evt-1", "2026-01-01T00:00:00Z", "0", "addPrincipalToGroup", "accounts", `{"targetGroupId":"g-1","targetUserId":"u-1"}`}, + }, + }, + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + t.Fatalf("failed to encode mock statement response: %v", err) + } + })) + defer server.Close() + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + auth := &databricks.NoAuth{} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", auth, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + + feed := newAuditEventFeed(client, nil, "wh-1") + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != 1 { + t.Fatalf("len(events) = %d, want 1: %+v", len(events), events) + } + + cg := events[0].GetCreateGrantEvent() + if cg == nil { + t.Fatalf("event = %+v, want a CreateGrantEvent", events[0]) + } + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: "acct-1"} + wantGroupId := groupResourceId(context.Background(), "g-1", accountParent) + if cg.GetEntitlement().GetResource().GetId().GetResource() != wantGroupId { + t.Errorf("entitlement resource = %q, want %q", cg.GetEntitlement().GetResource().GetId().GetResource(), wantGroupId) + } + if cg.GetPrincipal().GetId().GetResourceType() != userResourceType.Id || cg.GetPrincipal().GetId().GetResource() != "u-1" { + t.Errorf("principal = %+v, want type=%s id=u-1", cg.GetPrincipal().GetId(), userResourceType.Id) + } +} + +// newLookupFailureFeed returns a feed whose single grant-mapped audit row's principal lookup +// fails with lookupStatus. +func newLookupFailureFeed(t *testing.T, lookupStatus int) *auditEventFeed { + t.Helper() + row := []string{"evt-1", "2026-01-01T00:00:00Z", "0", "addPrincipalToGroup", "accounts", `{"targetGroupId":"g-1","targetUserId":"u-1"}`} + return newSingleRowFeed(t, row, func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/Users/u-1") { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(lookupStatus) + fmt.Fprint(w, `{"detail":"lookup failed"}`) + return + } + writeJSONNotFound(w) + }) +} + +// newSingleRowFeed returns a feed whose audit query yields row, with account SCIM lookups +// served by scim. +func newSingleRowFeed(t *testing.T, row []string, scim http.HandlerFunc) *auditEventFeed { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces") { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + return + } + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":"wh-1"}`) + return + } + if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/api/2.0/accounts/acct-1/scim/v2/") { + scim(w, r) + return + } + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements") { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + + w.Header().Set("Content-Type", "application/json") + resp := map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "schema": map[string]any{ + "columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }, + }, + }, + "result": map[string]any{ + "data_array": [][]string{row}, + }, + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + t.Fatalf("failed to encode mock statement response: %v", err) + } + })) + t.Cleanup(server.Close) + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + auth := &databricks.NoAuth{} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", auth, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + + return newAuditEventFeed(client, nil, "wh-1") +} + +// TestListEventsReturnsErrorOnRetryableLookupFailure verifies that a transient principal lookup +// failure fails the poll, so the cursor isn't advanced past the row. +func TestListEventsReturnsErrorOnRetryableLookupFailure(t *testing.T) { + feed := newLookupFailureFeed(t, http.StatusServiceUnavailable) + events, streamState, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err == nil { + t.Fatalf("ListEvents() error = nil, want the principal lookup failure; events=%+v", events) + } + if events != nil || streamState != nil { + t.Errorf("ListEvents() = (%+v, %+v), want no events and no stream state so the cursor is not advanced", events, streamState) + } +} + +// TestListEventsRefreshesGroupOnPermanentLookupFailure verifies that a non-retryable principal +// lookup failure on a membership row refreshes the group instead of blocking the cursor. +func TestListEventsRefreshesGroupOnPermanentLookupFailure(t *testing.T) { + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: "acct-1"} + wantGroupId := groupResourceId(context.Background(), "g-1", accountParent) + + for _, lookupStatus := range []int{http.StatusForbidden, http.StatusMethodNotAllowed} { + t.Run(strconv.Itoa(lookupStatus), func(t *testing.T) { + feed := newLookupFailureFeed(t, lookupStatus) + events, streamState, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v, want a group refresh", err) + } + if len(events) != 1 || events[0].GetResourceChangeEvent() == nil { + t.Fatalf("events = %+v, want one resource change", events) + } + if id := events[0].GetResourceChangeEvent().GetResourceId(); id.GetResourceType() != groupResourceType.Id || id.GetResource() != wantGroupId { + t.Errorf("resourceId = %+v, want group %s", id, wantGroupId) + } + if streamState == nil || streamState.Cursor == "" { + t.Errorf("streamState = %+v, want an advanced cursor", streamState) + } + }) + } +} + +// TestListEventsSkipsNonGrantRowOnPermanentLookupFailure verifies that a non-retryable lookup +// failure on a row with no group to fall back to is still skipped. +func TestListEventsSkipsNonGrantRowOnPermanentLookupFailure(t *testing.T) { + row := []string{"evt-1", "2026-01-01T00:00:00Z", "0", "add", "accounts", `{"targetUserId":"u-1"}`} + feed := newSingleRowFeed(t, row, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"detail":"lookup failed"}`) + }) + events, streamState, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v, want the row skipped", err) + } + if len(events) != 0 { + t.Errorf("len(events) = %d, want 0", len(events)) + } + if streamState == nil || streamState.Cursor == "" { + t.Errorf("streamState = %+v, want an advanced cursor", streamState) + } +} + +// TestListEventsEmitsEventPerGroupMember verifies a batched membership row yields one event per +// member with unique ids. +func TestListEventsEmitsEventPerGroupMember(t *testing.T) { + row := []string{"evt-1", "2026-01-01T00:00:00Z", "0", "addPrincipalsToGroup", "accounts", `{"targetGroupId":"g-1","targetUserId":"u-1,u-2,u-3"}`} + feed := newSingleRowFeed(t, row, func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "/Users/u-") && !strings.Contains(r.URL.Path, ",") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + writeJSONNotFound(w) + }) + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != 3 { + t.Fatalf("len(events) = %d, want 3: %+v", len(events), events) + } + for i, e := range events { + if e.GetId() != fmt.Sprintf("evt-1/%d", i) { + t.Errorf("[%d] id = %q, want evt-1/%d", i, e.GetId(), i) + } + cg := e.GetCreateGrantEvent() + if cg == nil { + t.Fatalf("[%d] event = %+v, want a CreateGrantEvent", i, e) + } + if want := fmt.Sprintf("u-%d", i+1); cg.GetPrincipal().GetId().GetResource() != want { + t.Errorf("[%d] principal = %+v, want %s", i, cg.GetPrincipal().GetId(), want) + } + } +} + +// TestListEventsLiveMultiMemberRows replays the request_params Databricks logged on a live Azure +// account for batched SCIM PATCHes, where names pair with ids in order. +func TestListEventsLiveMultiMemberRows(t *testing.T) { + const ( + spId = "143679241589540" + userB = "143797019507719" + userA = "147934750343750" + groupId = "153270043448790" + ) + kinds := map[string]string{spId: "ServicePrincipals", userB: "Users", userA: "Users"} + + type wantEvent struct{ resourceType, resource string } + cases := []struct { + name string + action string + params string + wantRevoke bool + wantEvents []wantEvent + wantLookups []string + }{ + { + name: "add of a service principal and two users", + action: "addPrincipalsToGroup", + params: `{"targetGroupId":"153270043448790","targetGroupName":"batch-group",` + + `"targetUserName":"8933382e-9e91-4caf-b0ad-b277dd60956d,member-b@example.com,member-a@example.com",` + + `"endpoint":"scim","targetUserId":"143679241589540,143797019507719,147934750343750"}`, + wantEvents: []wantEvent{ + {servicePrincipalResourceType.Id, spId}, {userResourceType.Id, userB}, {userResourceType.Id, userA}, + }, + wantLookups: []string{"/ServicePrincipals/" + spId, "/Users/" + userB, "/Users/" + userA}, + }, + { + name: "remove of two members without names", + action: "removePrincipalsFromGroup", + params: `{"targetGroupId":"153270043448790","targetGroupName":"batch-group","endpoint":"scim","targetUserId":"143679241589540,147934750343750"}`, + wantRevoke: true, + wantEvents: []wantEvent{{servicePrincipalResourceType.Id, spId}, {userResourceType.Id, userA}}, + wantLookups: []string{"/Users/" + spId, "/Groups/" + spId, "/ServicePrincipals/" + spId, "/Users/" + userA}, + }, + } + + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: "acct-1"} + wantGroupId := groupResourceId(context.Background(), groupId, accountParent) + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + handler, lookups := scimKindsHandler(kinds) + row := []string{"627da5dc-47b1-38b3-a4c1-fac2ccfdace5", "2026-01-01T00:00:00Z", "0", tc.action, "accounts", tc.params} + feed := newSingleRowFeed(t, row, handler) + + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != len(tc.wantEvents) { + t.Fatalf("len(events) = %d, want %d: %+v", len(events), len(tc.wantEvents), events) + } + for i, w := range tc.wantEvents { + var entitlement *v2.Entitlement + var principal *v2.Resource + if tc.wantRevoke { + entitlement, principal = events[i].GetCreateRevokeEvent().GetEntitlement(), events[i].GetCreateRevokeEvent().GetPrincipal() + } else { + entitlement, principal = events[i].GetCreateGrantEvent().GetEntitlement(), events[i].GetCreateGrantEvent().GetPrincipal() + } + if entitlement.GetResource().GetId().GetResource() != wantGroupId { + t.Errorf("[%d] entitlement resource = %q, want %q", i, entitlement.GetResource().GetId().GetResource(), wantGroupId) + } + if p := principal.GetId(); p.GetResourceType() != w.resourceType || p.GetResource() != w.resource { + t.Errorf("[%d] principal = %+v, want type=%s id=%s", i, p, w.resourceType, w.resource) + } + } + if got := lookups(); strings.Join(got, ",") != strings.Join(tc.wantLookups, ",") { + t.Errorf("lookups = %v, want %v", got, tc.wantLookups) + } + }) + } +} + +// TestListEventsFullPageCursorAdvance verifies the HasMore wiring on a full page +// (auditLogPageLimit raw rows): it pages forward from the last raw row's boundary, but when +// no boundary can be parsed it reports HasMore=false with the cursor unchanged rather than +// claiming more data behind a cursor that would repeat the same query. +func TestListEventsFullPageCursorAdvance(t *testing.T) { + start := eventPageCursor{StartAt: time.Now().Add(-2 * auditLogTrailingLag).UTC().Truncate(time.Second), StartAfterEventID: "evt-0"} + lastTime := start.StartAt.Add(time.Minute) + + cases := []struct { + name string + lastRowTime string + wantHasMore bool + wantCursor eventPageCursor + }{ + { + name: "parseable last row pages forward", + lastRowTime: lastTime.Format(time.RFC3339), + wantHasMore: true, + wantCursor: eventPageCursor{StartAt: lastTime, StartAfterEventID: fmt.Sprintf("evt-%d", auditLogPageLimit)}, + }, + { + name: "no parseable boundary stops without advancing", + lastRowTime: "not-a-time", + wantHasMore: false, + wantCursor: start, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces"): + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1"): + fmt.Fprint(w, `{"id":"wh-1"}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements"): + // Every row but the last has an unparseable event_time, so no row parses + // and only the last raw row can supply the boundary. The action is + // unmapped, so no principal lookups are made either way. + data := make([][]string, auditLogPageLimit) + for i := range data { + data[i] = []string{fmt.Sprintf("evt-%d", i+1), "not-a-time", "0", "someUnmappedAction", "accounts", `{}`} + } + data[len(data)-1][1] = tc.lastRowTime + _ = json.NewEncoder(w).Encode(map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{"schema": map[string]any{"columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }}}, + "result": map[string]any{"data_array": data}, + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + }) + + encoded, err := encodeEventCursor(start) + if err != nil { + t.Fatalf("encodeEventCursor() error = %v", err) + } + + feed := newAuditEventFeed(client, nil, "wh-1") + events, streamState, _, err := feed.ListEvents(context.Background(), nil, &pagination.StreamToken{Cursor: encoded}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + if len(events) != 0 { + t.Errorf("len(events) = %d, want 0", len(events)) + } + if streamState.HasMore != tc.wantHasMore { + t.Errorf("HasMore = %v, want %v", streamState.HasMore, tc.wantHasMore) + } + got := decodeEventCursor(context.Background(), streamState.Cursor, time.Now()) + if !got.StartAt.Equal(tc.wantCursor.StartAt) || got.StartAfterEventID != tc.wantCursor.StartAfterEventID { + t.Errorf("cursor = %+v, want %+v", got, tc.wantCursor) + } + }) + } +} + +// TestListEventsFindsWarehouseOutsideWorkspacesAllowlist verifies that resolving the SQL +// warehouse's workspace is NOT scoped by --workspaces: the warehouse can live in any +// workspace in the account, so the allowlist must only narrow which workspaces' audit +// rows get resolved to resources, not which workspaces are searched for the warehouse. +func TestListEventsFindsWarehouseOutsideWorkspacesAllowlist(t *testing.T) { + queriedWorkspace := "" + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces") { + w.Header().Set("Content-Type", "application/json") + if err := json.NewEncoder(w).Encode([]map[string]any{ + {"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}, + {"workspace_id": 2, "workspace_name": "ws2", "deployment_name": "ws2"}, + }); err != nil { + t.Fatalf("failed to encode mock workspaces response: %v", err) + } + return + } + + // The warehouse only exists in ws1, which is NOT in the --workspaces allowlist + // below (only ws2 is configured). Resolution must still find it in ws1. + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1") { + isWs1 := strings.HasPrefix(r.Header.Get("X-Test-Original-Host"), "ws1.") + w.Header().Set("Content-Type", "application/json") + if isWs1 { + fmt.Fprintf(w, `{"id":"wh-1"}`) + return + } + writeJSONNotFound(w) + return + } + + if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements") { + queriedWorkspace = r.Header.Get("X-Test-Original-Host") + w.Header().Set("Content-Type", "application/json") + resp := map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "schema": map[string]any{ + "columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }, + }, + }, + "result": map[string]any{"data_array": [][]string{}}, + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + t.Fatalf("failed to encode mock statement response: %v", err) + } + return + } + + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + })) + defer server.Close() + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + auth := &databricks.NoAuth{} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", auth, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + + // --workspaces is scoped to ws2 only; the warehouse lives in ws1. + feed := newAuditEventFeed(client, []string{"ws2"}, "wh-1") + + _, _, _, err = feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v, want warehouse resolution to succeed despite living outside --workspaces", err) + } + if !strings.HasPrefix(queriedWorkspace, "ws1.") { + t.Errorf("audit query ran against %q, want it to run against ws1 (where the warehouse actually lives)", queriedWorkspace) + } +} + +func TestFilterConfiguredWorkspaces(t *testing.T) { + all := []databricks.Workspace{ + {ID: 1, Name: "Prod", DeploymentName: "dbc-prod"}, + {ID: 2, Name: "Dev", DeploymentName: "dbc-dev"}, + } + + tests := []struct { + name string + configured []string + want []int + }{ + {"empty allowlist keeps all", nil, []int{1, 2}}, + {"deployment name", []string{"dbc-dev"}, []int{2}}, + {"workspace name, case-insensitive", []string{"PROD"}, []int{1}}, + {"numeric ID", []string{"2"}, []int{2}}, + {"no match", []string{"other"}, nil}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := filterConfiguredWorkspaces(all, tt.configured) + var ids []int + for _, w := range got { + ids = append(ids, w.ID) + } + if fmt.Sprint(ids) != fmt.Sprint(tt.want) { + t.Errorf("filterConfiguredWorkspaces(%v) = %v, want %v", tt.configured, ids, tt.want) + } + }) + } +} + +// TestExecuteStatementPollsPastCache guards against the uhttp GET cache freezing +// pollStatement: the poll URL never changes, so a cached RUNNING response would be +// returned until statementPollMaxWait. +func TestExecuteStatementPollsPastCache(t *testing.T) { + var polls atomic.Int32 + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + state := "PENDING" + if r.Method == http.MethodGet { + state = "RUNNING" + if polls.Add(1) >= 2 { + state = "SUCCEEDED" + } + } + fmt.Fprintf(w, `{"statement_id":"stmt-1","status":{"state":%q},"manifest":{"schema":{"columns":[{"name":"x"}]}},"result":{"data_array":[]}}`, state) + }) + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if _, _, err := client.ExecuteStatement(ctx, "dbc-aaa", "wh-1", "SELECT 1"); err != nil { + t.Fatalf("ExecuteStatement() error = %v", err) + } + if got := polls.Load(); got < 2 { + t.Errorf("server received %d poll GETs, want >= 2 (poll response was served from cache)", got) + } +} + +// TestGetBypassesCacheButSyncCallersDont verifies incremental-sync refreshes (builder Get) +// always hit the API, while the same client call from the regular sync path stays cached. +func TestGetBypassesCacheButSyncCallersDont(t *testing.T) { + var hits atomic.Int32 + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"id":"u-1","userName":"alice@example.com","active":true}`) + }) + ctx := context.Background() + accountParent := &v2.ResourceId{ResourceType: accountResourceType.Id, Resource: "acct-1"} + userId := &v2.ResourceId{ResourceType: userResourceType.Id, Resource: "u-1"} + + for range 2 { + if _, _, err := client.GetUser(ctx, "", "u-1"); err != nil { + t.Fatalf("GetUser() error = %v", err) + } + } + if got := hits.Load(); got != 1 { + t.Fatalf("regular GetUser calls made %d API calls, want 1 (second must be cached)", got) + } + + builder := newUserBuilder(client) + for range 2 { + if _, _, err := builder.Get(ctx, userId, accountParent); err != nil { + t.Fatalf("Get() error = %v", err) + } + } + if got := hits.Load() - 1; got != 2 { + t.Errorf("builder Get made %d API calls, want 2 (must bypass the cache)", got) + } +} + +// TestListEventsCachesPrincipalTypes verifies a principal named on several rows of one page is +// looked up once, including an id that matches no principal at all. +func TestListEventsCachesPrincipalTypes(t *testing.T) { + var mu sync.Mutex + hits := map[string]int{} + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces"): + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1"): + fmt.Fprint(w, `{"id":"wh-1"}`) + case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/scim/v2/"): + mu.Lock() + hits[r.URL.Path]++ + mu.Unlock() + if strings.HasSuffix(r.URL.Path, "/ServicePrincipals/sp-1") { + fmt.Fprint(w, `{}`) + return + } + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `{"detail":"not found"}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements"): + row := func(id, principal string) []string { + return []string{id, "2026-01-01T00:00:00Z", "0", "addPrincipalToGroup", "accounts", fmt.Sprintf(`{"targetGroupId":"g-1","targetUserId":%q}`, principal)} + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{"schema": map[string]any{"columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }}}, + "result": map[string]any{"data_array": [][]string{ + row("evt-1", "sp-1"), row("evt-2", "sp-1"), row("evt-3", "sp-1"), + row("evt-4", "gone-1"), row("evt-5", "gone-1"), + }}, + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + }) + + feed := newAuditEventFeed(client, nil, "wh-1") + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + // Three sp-1 grants, plus one g-1 change: both gone-1 rows fall back to the same group + // change, and only the last is kept. + if len(events) != 4 { + t.Fatalf("len(events) = %d, want 4", len(events)) + } + for _, id := range []string{"sp-1", "gone-1"} { + for _, kind := range []string{"Users", "Groups", "ServicePrincipals"} { + path := fmt.Sprintf("/api/2.0/accounts/acct-1/scim/v2/%s/%s", kind, id) + if got := hits[path]; got != 1 { + t.Errorf("%s hit %d times, want 1", path, got) + } + } + } +} + +// TestResolvePrincipalTypeDoesNotCacheErrors verifies a failed lookup is retried on the next +// row instead of being remembered. +func TestResolvePrincipalTypeDoesNotCacheErrors(t *testing.T) { + var calls atomic.Int32 + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if calls.Add(1) == 1 { + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"detail":"denied"}`) + return + } + fmt.Fprint(w, `{}`) + }) + + principalTypes := newPrincipalLookups(nil) + if _, _, err := resolvePrincipalType(context.Background(), client, principalTypes, "u-1", false); err == nil { + t.Fatal("first resolvePrincipalType() error = nil, want the lookup failure") + } + got, _, err := resolvePrincipalType(context.Background(), client, principalTypes, "u-1", false) + if err != nil { + t.Fatalf("second resolvePrincipalType() error = %v", err) + } + if got != userResourceType { + t.Errorf("second resolvePrincipalType() = %v, want %s", got, userResourceType.Id) + } + if n := calls.Load(); n != 2 { + t.Errorf("lookup made %d calls, want 2 (the error must not be cached)", n) + } +} + +// TestListEventsEmitsServicePrincipalChange verifies an accounts/add row naming a service +// principal reaches C1 as a service_principal change, resolved once across rows. The two rows' +// changes to sp-1 collapse into one. +func TestListEventsEmitsServicePrincipalChange(t *testing.T) { + var mu sync.Mutex + hits := map[string]int{} + client := newProbeTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces"): + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1"): + fmt.Fprint(w, `{"id":"wh-1"}`) + case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/scim/v2/"): + mu.Lock() + hits[r.URL.Path]++ + mu.Unlock() + if strings.HasSuffix(r.URL.Path, "/ServicePrincipals/sp-1") { + fmt.Fprint(w, `{}`) + return + } + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, `{"detail":"not found"}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements"): + _ = json.NewEncoder(w).Encode(map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{"schema": map[string]any{"columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }}}, + "result": map[string]any{"data_array": [][]string{ + {"evt-1", "2026-01-01T00:00:00Z", "0", "add", "accounts", `{"targetUserId":"sp-1"}`}, + {"evt-2", "2026-01-01T00:00:01Z", "0", "setAdmin", "accounts", `{"targetUserId":"sp-1"}`}, + }}, + }) + default: + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + }) + + feed := newAuditEventFeed(client, nil, "wh-1") + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + + var spEvents int + for _, e := range events { + id := e.GetResourceChangeEvent().GetResourceId() + if id.GetResourceType() == userResourceType.Id { + t.Errorf("event %+v names a user, want the service principal", id) + } + if id.GetResourceType() == servicePrincipalResourceType.Id && id.GetResource() == "sp-1" { + spEvents++ + } + } + if spEvents != 1 { + t.Errorf("got %d service_principal/sp-1 events, want 1: %+v", spEvents, events) + } + if got := hits["/api/2.0/accounts/acct-1/scim/v2/ServicePrincipals/sp-1"]; got != 1 { + t.Errorf("service principal looked up %d times, want 1", got) + } +} + +// TestListEventsDropsDuplicateResourceChanges verifies that when a page names the same resource +// more than once (the same user, or the same workspace role refreshed by several updateUser rows), +// only the last change is kept, with its own row's ID, and grant events are never collapsed. +func TestListEventsDropsDuplicateResourceChanges(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/workspaces") { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode([]map[string]any{{"workspace_id": 1, "workspace_name": "ws1", "deployment_name": "ws1"}}) + return + } + if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/api/2.0/sql/warehouses/wh-1") { + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, `{"id":"wh-1"}`) + return + } + if r.Method == http.MethodGet && (strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/scim/v2/Users/u-1") || strings.HasSuffix(r.URL.Path, "/api/2.0/accounts/acct-1/scim/v2/Users/u-2")) { + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + return + } + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/api/2.0/sql/statements") { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + return + } + + w.Header().Set("Content-Type", "application/json") + resp := map[string]any{ + "statement_id": "stmt-1", + "status": map[string]any{"state": "SUCCEEDED"}, + "manifest": map[string]any{ + "schema": map[string]any{ + "columns": []map[string]any{ + {"name": "event_id"}, {"name": "event_time"}, {"name": "workspace_id"}, + {"name": "action_name"}, {"name": "service_name"}, {"name": "request_params"}, + }, + }, + }, + "result": map[string]any{ + "data_array": [][]string{ + {"evt-1", "2026-01-01T00:00:00Z", "1", "updateUser", "accounts", `{"targetUserId":"u-1"}`}, + {"evt-2", "2026-01-01T00:01:00Z", "1", "updateUser", "accounts", `{"targetUserId":"u-2"}`}, + {"evt-3", "2026-01-01T00:02:00Z", "1", "updateUser", "accounts", `{"targetUserId":"u-1"}`}, + {"evt-4", "2026-01-01T00:03:00Z", "0", "addPrincipalToGroup", "accounts", `{"targetGroupId":"g-1","targetUserId":"u-1"}`}, + {"evt-5", "2026-01-01T00:04:00Z", "0", "addPrincipalToGroup", "accounts", `{"targetGroupId":"g-1","targetUserId":"u-1"}`}, + }, + }, + } + if err := json.NewEncoder(w).Encode(resp); err != nil { + t.Fatalf("failed to encode mock statement response: %v", err) + } + })) + defer server.Close() + + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("failed to parse test server URL: %v", err) + } + + httpClient := &http.Client{Transport: &redirectTransport{target: target}} + client, err := databricks.NewClient(context.Background(), httpClient, "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", &databricks.NoAuth{}, nil) + if err != nil { + t.Fatalf("NewClient() error = %v", err) + } + + feed := newAuditEventFeed(client, nil, "wh-1") + events, _, _, err := feed.ListEvents(context.Background(), testEarliestEvent(), &pagination.StreamToken{Cursor: ""}) + if err != nil { + t.Fatalf("ListEvents() error = %v", err) + } + + // evt-1 is fully superseded: evt-3 names u-1 and the same four roles again. evt-2 keeps only + // u-2, its roles are superseded by evt-3. evt-4 and evt-5: one grant each. + want := []string{"evt-2/0", "evt-3/0", "evt-3/1", "evt-3/2", "evt-3/3", "evt-3/4", "evt-4/0", "evt-5/0"} + got := make([]string, 0, len(events)) + for _, e := range events { + got = append(got, e.GetId()) + } + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("event IDs = %v, want %v", got, want) + } + for _, e := range events[6:] { + if e.GetCreateGrantEvent() == nil { + t.Errorf("event %s = %+v, want a CreateGrantEvent", e.GetId(), e) + } + } +} diff --git a/pkg/connector/connector.go b/pkg/connector/connector.go index f97021e6..082ad834 100644 --- a/pkg/connector/connector.go +++ b/pkg/connector/connector.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "strings" "github.com/conductorone/baton-databricks/pkg/config" "github.com/conductorone/baton-databricks/pkg/databricks" @@ -11,15 +12,19 @@ import ( "github.com/conductorone/baton-sdk/pkg/annotations" "github.com/conductorone/baton-sdk/pkg/cli" "github.com/conductorone/baton-sdk/pkg/connectorbuilder" + "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap" + "go.uber.org/zap" ) type Databricks struct { client *databricks.Client workspaces []string + // sqlWarehouseID enables incremental sync when non-empty. + sqlWarehouseID string } // ResourceSyncers returns a ResourceSyncerV2 for each resource type that should be synced from the upstream service. -func (d *Databricks) ResourceSyncers(ctx context.Context) []connectorbuilder.ResourceSyncerV2 { +func (d *Databricks) ResourceSyncers(_ context.Context) []connectorbuilder.ResourceSyncerV2 { syncers := []connectorbuilder.ResourceSyncerV2{ newAccountBuilder(d.client), newGroupBuilder(d.client), @@ -32,14 +37,22 @@ func (d *Databricks) ResourceSyncers(ctx context.Context) []connectorbuilder.Res return syncers } +// EventFeeds registers the audit-log event feed unconditionally; whether sql-warehouse-id +// is set gates its behavior inside ListEvents instead. +func (d *Databricks) EventFeeds(_ context.Context) []connectorbuilder.EventFeed { + return []connectorbuilder.EventFeed{ + newAuditEventFeed(d.client, d.workspaces, d.sqlWarehouseID), + } +} + // Asset takes an input AssetRef and attempts to fetch it using the connector's authenticated http client // It streams a response, always starting with a metadata object, following by chunked payloads for the asset. -func (d *Databricks) Asset(ctx context.Context, asset *v2.AssetRef) (string, io.ReadCloser, error) { +func (d *Databricks) Asset(_ context.Context, _ *v2.AssetRef) (string, io.ReadCloser, error) { return "", nil, nil } // Metadata returns metadata about the connector. -func (d *Databricks) Metadata(ctx context.Context) (*v2.ConnectorMetadata, error) { +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", @@ -112,11 +125,23 @@ func (d *Databricks) Validate(ctx context.Context) (annotations.Annotations, err // Workspace enumeration is the other account-plane call every sync depends on. // Per-workspace probing is deliberately not done here: a workspace the service // principal can't reach is skipped during sync rather than failing validation. - if _, _, err := d.client.ListWorkspaces(ctx); err != nil { - return nil, fmt.Errorf("databricks-connector: failed to list workspaces: %w", err) + annos := annotations.Annotations{} + _, rateLimit, err := d.client.ListWorkspaces(ctx) + if rateLimit != nil { + annos.WithRateLimiting(rateLimit) + } + if err != nil { + return annos, fmt.Errorf("databricks-connector: failed to list workspaces: %w", err) + } + + l := ctxzap.Extract(ctx) + if d.sqlWarehouseID == "" { + l.Info("databricks-connector: incremental sync disabled (sql-warehouse-id not set)") + return annos, nil } - return nil, nil + l.Info("databricks-connector: incremental sync enabled", zap.String("sql_warehouse_id", d.sqlWarehouseID)) + return annos, nil } // New returns a new instance of the connector. @@ -129,6 +154,7 @@ func New( auth databricks.Auth, excludeWorkspaces []string, workspaces []string, + sqlWarehouseID string, ) (*Databricks, error) { httpClient, err := auth.GetClient(ctx) if err != nil { @@ -143,6 +169,8 @@ func New( return &Databricks{ client: client, workspaces: workspaces, + // Trimmed so a whitespace-only value counts as unset (incremental sync off). + sqlWarehouseID: strings.TrimSpace(sqlWarehouseID), }, nil } @@ -160,6 +188,7 @@ func NewConnector(ctx context.Context, cfg *config.Databricks, _ *cli.ConnectorO auth, cfg.DatabricksExcludeWorkspaces, cfg.Workspaces, + cfg.SqlWarehouseId, ) if err != nil { return nil, nil, err diff --git a/pkg/connector/groups.go b/pkg/connector/groups.go index b5979b73..5053fb28 100644 --- a/pkg/connector/groups.go +++ b/pkg/connector/groups.go @@ -288,6 +288,40 @@ func (g *groupBuilder) Grants(ctx context.Context, resource *v2.Resource, attr r return rv, &rs.SyncOpResults{NextPageToken: nextPage, Annotations: annos}, nil } +// Get re-fetches a single group, used to re-sync it after a RESOURCE_CHANGE event; fetched +// without members since groupResource doesn't need them (Grants fetches them separately). +func (g *groupBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + parentId, groupId, err := parseResourceId(resourceId.Resource) + if err != nil { + return nil, nil, fmt.Errorf("databricks-connector: failed to parse group resource id: %w", err) + } + + var workspaceId string + if parentId != nil && parentId.ResourceType == workspaceResourceType.Id { + workspaceId = parentId.Resource + } + + group, rateLimitData, err := g.client.GetGroup(databricks.WithoutCache(ctx), workspaceId, groupId.Resource, databricks.NewGroupAttrVars()) + annos := annotations.Annotations{} + if rateLimitData != nil { + annos.WithRateLimiting(rateLimitData) + } + if err != nil { + return nil, annos, fmt.Errorf("databricks-connector: failed to get group %s: %w", groupId.Resource, err) + } + + resource, err := groupResource(ctx, group, parentResourceId) + if err != nil { + return nil, nil, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed group", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, annos, nil +} + func (g *groupBuilder) Grant(ctx context.Context, principal *v2.Resource, entitlement *v2.Entitlement) (annotations.Annotations, error) { l := ctxzap.Extract(ctx) diff --git a/pkg/connector/roles.go b/pkg/connector/roles.go index 175f6ae5..127589c8 100644 --- a/pkg/connector/roles.go +++ b/pkg/connector/roles.go @@ -3,6 +3,7 @@ package connector import ( "context" "fmt" + "strings" "github.com/conductorone/baton-databricks/pkg/databricks" v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" @@ -43,21 +44,22 @@ func (r *roleBuilder) ResourceType(ctx context.Context) *v2.ResourceType { return roleResourceType } +// roleResourceId builds a role's resource ID, namespaced by workspace for workspace roles. +func roleResourceId(role string, parent *v2.ResourceId) string { + if parent.GetResourceType() == workspaceResourceType.Id { + return fmt.Sprintf("%s:%s", parent.Resource, role) + } + return role +} + func roleResource(ctx context.Context, role string, parent *v2.ResourceId) (*v2.Resource, error) { - var roleID string profile := map[string]interface{}{ "role_name": role, - "parent_type": parent.ResourceType, - "parent_id": parent.Resource, + "parent_type": parent.GetResourceType(), + "parent_id": parent.GetResource(), } - // To differentiate between what type of role does the resource represent. - switch parent.ResourceType { - case workspaceResourceType.Id: - roleID = fmt.Sprintf("%s:%s", parent.Resource, role) - case accountResourceType.Id: - roleID = role - } + roleID := roleResourceId(role, parent) resource, err := rs.NewRoleResource( role, @@ -297,6 +299,31 @@ func (r *roleBuilder) Grants(ctx context.Context, resource *v2.Resource, attr rs return rv, &rs.SyncOpResults{NextPageToken: nextPage}, nil } +// Get rebuilds a single role resource, used to re-sync it after a RESOURCE_CHANGE event. +// Roles are synthetic (not fetched from an API), so this just reconstructs the resource +// from its resource ID the same way List does. +func (r *roleBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + roleName := resourceId.Resource + if parentResourceId.GetResourceType() == workspaceResourceType.Id { + _, name, found := strings.Cut(resourceId.Resource, ":") + if !found { + return nil, nil, fmt.Errorf("databricks-connector: invalid workspace role resource id: %s", resourceId.Resource) + } + roleName = name + } + + resource, err := roleResource(ctx, roleName, parentResourceId) + if err != nil { + return nil, nil, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed role", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, nil, nil +} + func (r *roleBuilder) Grant(ctx context.Context, principal *v2.Resource, entitlement *v2.Entitlement) (annotations.Annotations, error) { l := ctxzap.Extract(ctx) diff --git a/pkg/connector/service-principals.go b/pkg/connector/service-principals.go index ccd109ba..51bc131d 100644 --- a/pkg/connector/service-principals.go +++ b/pkg/connector/service-principals.go @@ -30,15 +30,16 @@ func (s *servicePrincipalBuilder) servicePrincipalResource(ctx context.Context, profile := map[string]interface{}{ "application_id": servicePrincipal.ApplicationID, "display_name": servicePrincipal.DisplayName, - "parent_type": parent.ResourceType, - "parent_id": parent.Resource, + "parent_type": parent.GetResourceType(), + "parent_id": parent.GetResource(), } options := []rs.ResourceOption{ rs.WithResourceProfile(profile), } + // keep the parent resource id, only if the parent resource is account - if parent.ResourceType == accountResourceType.Id { + if parent.GetResourceType() == accountResourceType.Id { options = append(options, rs.WithParentResourceID(parent)) } @@ -220,6 +221,34 @@ func (s *servicePrincipalBuilder) Grants(ctx context.Context, resource *v2.Resou return rv, nil, nil } +// Get re-fetches a single service principal, used to re-sync it after a RESOURCE_CHANGE event. +func (s *servicePrincipalBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + var workspaceId string + if parentResourceId.GetResourceType() == workspaceResourceType.Id { + workspaceId = parentResourceId.Resource + } + + servicePrincipal, rateLimitData, err := s.client.GetServicePrincipal(databricks.WithoutCache(ctx), workspaceId, resourceId.Resource) + annos := annotations.Annotations{} + if rateLimitData != nil { + annos.WithRateLimiting(rateLimitData) + } + if err != nil { + return nil, annos, fmt.Errorf("databricks-connector: failed to get service principal %s: %w", resourceId.Resource, err) + } + + resource, err := s.servicePrincipalResource(ctx, servicePrincipal, parentResourceId) + if err != nil { + return nil, nil, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed service principal", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, annos, nil +} + func (s *servicePrincipalBuilder) Grant(ctx context.Context, principal *v2.Resource, entitlement *v2.Entitlement) (annotations.Annotations, error) { l := ctxzap.Extract(ctx) diff --git a/pkg/connector/users.go b/pkg/connector/users.go index 5e3f780b..028e3e29 100644 --- a/pkg/connector/users.go +++ b/pkg/connector/users.go @@ -11,6 +11,8 @@ import ( "github.com/conductorone/baton-sdk/pkg/connectorbuilder" 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" ) @@ -66,8 +68,9 @@ func (u *userBuilder) userResource(ctx context.Context, user *databricks.User, p rs.WithResourceStatus(status, ""), rs.WithAnnotation(&v2.RawId{Id: user.ID}), } + // keep the parent resource id, only if the parent resource is account - if parent.ResourceType == accountResourceType.Id { + if parent.GetResourceType() == accountResourceType.Id { options = append(options, rs.WithParentResourceID(parent)) } @@ -272,6 +275,34 @@ func (o *userBuilder) CreateAccount(ctx context.Context, accountInfo *v2.Account }, nil, nil, nil } +// Get re-fetches a single user, used to re-sync it after a RESOURCE_CHANGE event. +func (u *userBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + var workspaceId string + if parentResourceId.GetResourceType() == workspaceResourceType.Id { + workspaceId = parentResourceId.Resource + } + + user, rateLimitData, err := u.client.GetUser(databricks.WithoutCache(ctx), workspaceId, resourceId.Resource) + annos := annotations.Annotations{} + if rateLimitData != nil { + annos.WithRateLimiting(rateLimitData) + } + if err != nil { + return nil, annos, fmt.Errorf("databricks-connector: failed to get user %s: %w", resourceId.Resource, err) + } + + resource, err := u.userResource(ctx, user, parentResourceId) + if err != nil { + return nil, nil, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed user", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, annos, nil +} + func (o *userBuilder) Delete(ctx context.Context, resourceId *v2.ResourceId) (annotations.Annotations, error) { _, err := o.client.DeleteUser(ctx, "", resourceId.Resource) if err != nil { diff --git a/pkg/connector/validate_test.go b/pkg/connector/validate_test.go index 225b54e6..04678e99 100644 --- a/pkg/connector/validate_test.go +++ b/pkg/connector/validate_test.go @@ -5,9 +5,11 @@ import ( "io" "net/http" "strings" + "sync" "testing" "github.com/conductorone/baton-databricks/pkg/databricks" + "github.com/conductorone/baton-sdk/pkg/pagination" ) // rolesTransport answers the assignable-roles calls Validate makes. failAccount @@ -54,3 +56,112 @@ func TestValidateOAuthAccountCheckFailureReturnsError(t *testing.T) { t.Fatal("Validate: want error on OAuth account check failure, got nil") } } + +// incrementalTransport serves the account calls Validate always makes (roles, one +// workspace) and records every path, so tests can assert whether any incremental-sync +// call (SQL warehouse lookup, statement execution) was made. +type incrementalTransport struct { + mu sync.Mutex + paths []string +} + +func (t *incrementalTransport) RoundTrip(req *http.Request) (*http.Response, error) { + t.mu.Lock() + t.paths = append(t.paths, req.URL.Path) + t.mu.Unlock() + + status, body := http.StatusOK, `{"roles":[]}` + switch { + case strings.HasSuffix(req.URL.Path, "/accounts/acct-1/workspaces"): + body = `[{"workspace_id":1,"workspace_name":"ws1","deployment_name":"ws1"}]` + case strings.Contains(req.URL.Path, "/sql/warehouses/"): + status, body = http.StatusNotFound, `{"error_code":"RESOURCE_DOES_NOT_EXIST","message":"not found"}` + } + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil +} + +func (t *incrementalTransport) hitIncrementalSyncAPI() bool { + t.mu.Lock() + defer t.mu.Unlock() + for _, p := range t.paths { + if strings.Contains(p, "/sql/") { + return true + } + } + return false +} + +// No sql-warehouse-id means incremental sync is off: Validate succeeds without touching +// any warehouse/audit-log API. +func TestValidateWithoutWarehouseIDDisablesIncrementalSync(t *testing.T) { + tr := &incrementalTransport{} + d := newValidateConnector(t, &databricks.NoAuth{}, tr) + + if _, err := d.Validate(context.Background()); err != nil { + t.Fatalf("Validate: want nil with incremental sync disabled, got %v", err) + } + if tr.hitIncrementalSyncAPI() { + t.Errorf("Validate made incremental-sync calls with no sql-warehouse-id: %v", tr.paths) + } +} + +// Incremental sync misconfiguration (unknown warehouse, no workspace in scope) must not +// block full syncs, so Validate succeeds without probing the warehouse. +func TestValidateWithWarehouseIDDoesNotProbeIncrementalSync(t *testing.T) { + cases := []struct { + name string + workspaces []string + }{ + {name: "unknown warehouse"}, + {name: "no workspace in scope", workspaces: []string{"not-a-workspace"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + tr := &incrementalTransport{} + d := newValidateConnector(t, &databricks.NoAuth{}, tr) + d.sqlWarehouseID = "wh-missing" + d.workspaces = tc.workspaces + + if _, err := d.Validate(context.Background()); err != nil { + t.Fatalf("Validate: want nil, got %v", err) + } + if tr.hitIncrementalSyncAPI() { + t.Errorf("Validate made incremental-sync calls: %v", tr.paths) + } + }) + } +} + +// A whitespace-only sql-warehouse-id counts as unset, so incremental sync stays off. +func TestNewTreatsBlankWarehouseIDAsDisabled(t *testing.T) { + d, err := New(context.Background(), "cloud.databricks.com", "accounts.cloud.databricks.com", "acct-1", "", &databricks.NoAuth{}, nil, nil, " ") + if err != nil { + t.Fatalf("New: %v", err) + } + if d.sqlWarehouseID != "" { + t.Errorf("sqlWarehouseID = %q, want empty (incremental sync disabled)", d.sqlWarehouseID) + } +} + +// With no sql-warehouse-id the feed is a no-op: no events, no API calls. +func TestListEventsWithoutWarehouseIDIsNoop(t *testing.T) { + tr := &incrementalTransport{} + d := newValidateConnector(t, &databricks.NoAuth{}, tr) + feed := newAuditEventFeed(d.client, nil, "") + + events, state, _, err := feed.ListEvents(context.Background(), nil, &pagination.StreamToken{}) + if err != nil { + t.Fatalf("ListEvents: %v", err) + } + if len(events) != 0 || state.HasMore { + t.Errorf("ListEvents = %d events, HasMore=%v; want none", len(events), state.HasMore) + } + if len(tr.paths) != 0 { + t.Errorf("ListEvents made API calls with incremental sync disabled: %v", tr.paths) + } +} diff --git a/pkg/connector/workspaces.go b/pkg/connector/workspaces.go index 20990ca6..1dee3c4a 100644 --- a/pkg/connector/workspaces.go +++ b/pkg/connector/workspaces.go @@ -269,6 +269,31 @@ func (w *workspaceBuilder) Grants(ctx context.Context, resource *v2.Resource, at return rv, &rs.SyncOpResults{NextPageToken: nextPage, Annotations: annos}, nil } +// Get re-fetches a single workspace, used to re-sync it after a RESOURCE_CHANGE event. +// GetWorkspace excludes it the same way ListWorkspaces does, so a deliberately excluded +// workspace naturally comes back not-found rather than needing a separate check here. +func (w *workspaceBuilder) Get(ctx context.Context, resourceId *v2.ResourceId, parentResourceId *v2.ResourceId) (*v2.Resource, annotations.Annotations, error) { + workspace, rateLimitData, err := w.client.GetWorkspace(databricks.WithoutCache(ctx), resourceId.Resource) + annos := annotations.Annotations{} + if rateLimitData != nil { + annos.WithRateLimiting(rateLimitData) + } + if err != nil { + return nil, annos, fmt.Errorf("databricks-connector: failed to get workspace %s: %w", resourceId.Resource, err) + } + + resource, err := workspaceResource(ctx, workspace, parentResourceId) + if err != nil { + return nil, annos, err + } + + ctxzap.Extract(ctx).Debug("databricks-connector: Get: refreshed workspace", + zap.String("resource_id", resourceId.Resource), + zap.String("parent_resource_id", parentResourceId.GetResource()), + ) + return resource, annos, nil +} + // workspacePrincipalID returns the numeric principal ID the permission assignments API expects. // Groups are only synced under the account, so only "account//group/" group IDs of // the given account are accepted; anything else is rejected. diff --git a/pkg/databricks/client.go b/pkg/databricks/client.go index 19038983..31b99c66 100644 --- a/pkg/databricks/client.go +++ b/pkg/databricks/client.go @@ -11,10 +11,10 @@ import ( "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap" "go.uber.org/zap" - "google.golang.org/grpc/codes" v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" "github.com/conductorone/baton-sdk/pkg/uhttp" + "google.golang.org/grpc/codes" ) const ( @@ -682,6 +682,30 @@ func (c *Client) ListWorkspaces( return filtered, ratelimitData, nil } +// GetWorkspace finds a single workspace by deployment name from the account's +// workspace list (there is no single-workspace GET endpoint). +func (c *Client) GetWorkspace( + ctx context.Context, + deploymentName string, +) ( + *Workspace, + *v2.RateLimitDescription, + error, +) { + workspaces, ratelimitData, err := c.ListWorkspaces(ctx) + if err != nil { + return nil, ratelimitData, err + } + + for _, w := range workspaces { + if w.DeploymentName == deploymentName { + return &w, ratelimitData, nil + } + } + + return nil, ratelimitData, uhttp.WrapErrors(codes.NotFound, fmt.Sprintf("workspace %s not found", deploymentName)) +} + func (c *Client) ListWorkspaceMembers( ctx context.Context, workspaceId string, diff --git a/pkg/databricks/request.go b/pkg/databricks/request.go index 58ade4b5..20c1c094 100644 --- a/pkg/databricks/request.go +++ b/pkg/databricks/request.go @@ -88,6 +88,19 @@ func nameWorkspace403Remedy(workspaceId string, err error) error { return err } +type noCacheKey struct{} + +// WithoutCache marks ctx so GETs made with it bypass the uhttp response cache, for +// callers that need fresh data (statement polling, incremental-sync refreshes). +func WithoutCache(ctx context.Context) context.Context { + return context.WithValue(ctx, noCacheKey{}, true) +} + +func isNoCache(ctx context.Context) bool { + v, _ := ctx.Value(noCacheKey{}).(bool) + return v +} + func (c *Client) Get( ctx context.Context, urlAddress *url.URL, @@ -235,6 +248,9 @@ func (c *Client) doRequestWithOptions( if body != nil { options = append(options, uhttp.WithJSONBody(body)) } + if method == http.MethodGet && isNoCache(ctx) { + options = append(options, uhttp.WithNoCache()) + } options = append(options, extraOptions...) req, err := c.httpClient.NewRequest(ctx, method, uri, options...) diff --git a/pkg/databricks/sql.go b/pkg/databricks/sql.go new file mode 100644 index 00000000..f7818fc6 --- /dev/null +++ b/pkg/databricks/sql.go @@ -0,0 +1,340 @@ +package databricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "strconv" + "time" + + v2 "github.com/conductorone/baton-sdk/pb/c1/connector/v2" + "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" +) + +const ( + statementsEndpoint = "/api/2.0/sql/statements" + warehousesEndpoint = "/api/2.0/sql/warehouses" + + statementWaitTimeout = "30s" + + warehouseStateRunning = "RUNNING" + warehouseStateStarting = "STARTING" +) + +// Vars so tests can shorten them. +var ( + statementPollInterval = 2 * time.Second + statementPollMaxWait = 5 * time.Minute +) + +type StatementState string + +const ( + StatementStatePending StatementState = "PENDING" + StatementStateRunning StatementState = "RUNNING" + StatementStateSucceeded StatementState = "SUCCEEDED" + StatementStateFailed StatementState = "FAILED" + StatementStateCanceled StatementState = "CANCELED" + StatementStateClosed StatementState = "CLOSED" +) + +// StatementParameter binds a named parameter referenced as ":name" in a SQL statement. +type StatementParameter struct { + Name string `json:"name"` + Value string `json:"value"` + Type string `json:"type,omitempty"` +} + +type statementRequestBody struct { + WarehouseID string `json:"warehouse_id"` + Statement string `json:"statement"` + WaitTimeout string `json:"wait_timeout,omitempty"` + Format string `json:"format"` + Disposition string `json:"disposition"` + Parameters []StatementParameter `json:"parameters,omitempty"` +} + +type statementError struct { + ErrorCode string `json:"error_code"` + Message string `json:"message"` +} + +type statementStatus struct { + State StatementState `json:"state"` + Error *statementError `json:"error,omitempty"` +} + +type statementManifest struct { + Schema struct { + Columns []struct { + Name string `json:"name"` + } `json:"columns"` + } `json:"schema"` +} + +type statementResultChunk struct { + NextChunkIndex *int `json:"next_chunk_index,omitempty"` + DataArray [][]string `json:"data_array"` +} + +type statementResponse struct { + StatementID string `json:"statement_id"` + Status statementStatus `json:"status"` + Manifest statementManifest `json:"manifest"` + Result statementResultChunk `json:"result"` +} + +// StatementResult is the flattened result of a SQL statement executed via the +// Statement Execution API, with all result chunks already collected. +type StatementResult struct { + Columns []string + Rows [][]string +} + +// ExecuteStatement runs a SQL statement via the Statement Execution API and returns every +// row, along with the rate-limit info from the last call that reported any. +func (c *Client) ExecuteStatement( + ctx context.Context, + workspaceId string, + warehouseId string, + statement string, + params ...StatementParameter, +) (*StatementResult, *v2.RateLimitDescription, error) { + l := ctxzap.Extract(ctx) + u := c.workspaceUrl(workspaceId).JoinPath(statementsEndpoint) + + body := statementRequestBody{ + WarehouseID: warehouseId, + Statement: statement, + WaitTimeout: statementWaitTimeout, + Format: "JSON_ARRAY", + Disposition: "INLINE", + Parameters: params, + } + + var res statementResponse + rateLimit, err := c.Post(ctx, u, body, &res) + if err != nil { + return nil, rateLimit, fmt.Errorf("failed to submit statement: %w", err) + } + l.Debug("ExecuteStatement: submitted sql statement", + zap.String("workspace_id", workspaceId), + zap.String("warehouse_id", warehouseId), + zap.String("statement_id", res.StatementID), + zap.String("state", string(res.Status.State)), + ) + + res, polledRateLimit, err := c.pollStatement(ctx, workspaceId, warehouseId, res) + if polledRateLimit != nil { + rateLimit = polledRateLimit + } + if err != nil { + return nil, rateLimit, err + } + + if res.Status.State != StatementStateSucceeded { + msg := "" + if res.Status.Error != nil { + msg = res.Status.Error.Message + } + // FAILED is usually a query/permission problem; CANCELED/CLOSED means it was stopped. + code := codes.FailedPrecondition + if res.Status.State != StatementStateFailed { + code = codes.Aborted + } + return nil, rateLimit, uhttp.WrapErrors(code, fmt.Sprintf("statement %s did not succeed: state=%s message=%s", res.StatementID, res.Status.State, msg)) + } + + result, resultRateLimit, err := c.collectStatementResult(ctx, workspaceId, res) + if resultRateLimit != nil { + rateLimit = resultRateLimit + } + if err != nil { + return nil, rateLimit, err + } + + l.Debug("ExecuteStatement: sql statement succeeded", + zap.String("statement_id", res.StatementID), + zap.Int("column_count", len(result.Columns)), + zap.Int("row_count", len(result.Rows)), + ) + return result, rateLimit, nil +} + +// pollStatement blocks until the statement reaches a terminal state, for the case of a +// cold warehouse start still running after the initial statementWaitTimeout. Capped at +// statementPollMaxWait so a warehouse stuck PENDING/RUNNING can't hang the caller +// indefinitely; on giving up (or on ctx cancellation) it cancels the statement so it stops +// occupying the warehouse. +func (c *Client) pollStatement(ctx context.Context, workspaceId, warehouseId string, res statementResponse) (statementResponse, *v2.RateLimitDescription, error) { + l := ctxzap.Extract(ctx) + + pollCtx, cancel := context.WithTimeout(ctx, statementPollMaxWait) + defer cancel() + + var rateLimit *v2.RateLimitDescription + for res.Status.State == StatementStatePending || res.Status.State == StatementStateRunning { + select { + case <-pollCtx.Done(): + return res, rateLimit, c.abandonStatement(ctx, workspaceId, warehouseId, res) + case <-time.After(statementPollInterval): + } + + l.Debug("polling databricks sql statement", zap.String("statement_id", res.StatementID), zap.String("state", string(res.Status.State))) + + u := c.workspaceUrl(workspaceId).JoinPath(statementsEndpoint, res.StatementID) + var polled statementResponse + // No cache: the URL is identical on every poll, so a cached PENDING/RUNNING + // response would otherwise be returned until statementPollMaxWait. + polledRateLimit, err := c.Get(WithoutCache(pollCtx), u, &polled) + if polledRateLimit != nil { + rateLimit = polledRateLimit + } + if err != nil { + // The poll deadline can expire mid-request; that's still a timeout. + if pollCtx.Err() != nil { + return res, rateLimit, c.abandonStatement(ctx, workspaceId, warehouseId, res) + } + return res, rateLimit, fmt.Errorf("failed to poll statement %s: %w", res.StatementID, err) + } + res = polled + } + + return res, rateLimit, nil +} + +// abandonStatement cancels a statement that didn't finish in time and returns ctx's error if +// the caller gave up, or else a DeadlineExceeded error saying why the statement didn't finish. +func (c *Client) abandonStatement(ctx context.Context, workspaceId, warehouseId string, res statementResponse) error { + c.cancelStatement(ctx, workspaceId, res.StatementID) + if err := ctx.Err(); err != nil { + return err + } + + l := ctxzap.Extract(ctx) + l.Debug("sql statement did not reach a terminal state before poll timeout, canceled it", + zap.String("statement_id", res.StatementID), + zap.String("state", string(res.Status.State)), + zap.Duration("max_wait", statementPollMaxWait), + ) + + msg := fmt.Sprintf("statement %s did not finish within %s (state=%s)", res.StatementID, statementPollMaxWait, res.Status.State) + switch res.Status.State { + case StatementStateRunning: + msg += ": the query was still running" + case StatementStatePending: + // PENDING means waiting for compute, so the warehouse state says why. + state, err := c.warehouseState(ctx, workspaceId, warehouseId) + switch { + case err != nil: + l.Debug("failed to get sql warehouse state", zap.String("warehouse_id", warehouseId), zap.Error(err)) + case state == "": + case state == warehouseStateRunning: + msg += fmt.Sprintf(": SQL warehouse %s is running but did not pick up the statement; it may be at capacity", warehouseId) + case state == warehouseStateStarting: + msg += fmt.Sprintf(": SQL warehouse %s was still starting; a serverless warehouse starts much faster", warehouseId) + default: + msg += fmt.Sprintf(": SQL warehouse %s is %s and has not started; check its Monitoring tab for start failures", warehouseId, state) + } + default: + // Terminal states never reach here: polling only times out while PENDING or RUNNING. + } + + return uhttp.WrapErrors(codes.DeadlineExceeded, msg) +} + +// warehouseState returns the warehouse's state (e.g. RUNNING, STARTING, STOPPED). Like +// cancelStatement, it ignores ctx's cancellation. +func (c *Client) warehouseState(ctx context.Context, workspaceId, warehouseId string) (string, error) { + reqCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + + u := c.workspaceUrl(workspaceId).JoinPath(warehousesEndpoint, warehouseId) + var res struct { + State string `json:"state"` + } + if _, err := c.Get(WithoutCache(reqCtx), u, &res); err != nil { + return "", err + } + return res.State, nil +} + +// cancelStatement best-effort cancels a statement we've given up polling on. The request uses +// ctx's values (for the logger) but not its cancellation, since ctx/pollCtx may already be +// done. Uses /cancel, not DELETE (which only closes an already-terminal statement and +// wouldn't stop one still running). +func (c *Client) cancelStatement(ctx context.Context, workspaceId, statementId string) { + l := ctxzap.Extract(ctx) + + reqCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + + u := c.workspaceUrl(workspaceId).JoinPath(statementsEndpoint, statementId, "cancel") + response := struct{}{} + if _, err := c.Post(reqCtx, u, nil, &response); err != nil { + l.Debug("failed to cancel timed-out sql statement", zap.String("statement_id", statementId), zap.Error(err)) + } +} + +func (c *Client) collectStatementResult(ctx context.Context, workspaceId string, res statementResponse) (*StatementResult, *v2.RateLimitDescription, error) { + columns := make([]string, len(res.Manifest.Schema.Columns)) + for i, col := range res.Manifest.Schema.Columns { + columns[i] = col.Name + } + + rows := make([][]string, 0, len(res.Result.DataArray)) + rows = append(rows, res.Result.DataArray...) + + var rateLimit *v2.RateLimitDescription + nextChunk := res.Result.NextChunkIndex + for nextChunk != nil { + u := c.workspaceUrl(workspaceId).JoinPath(statementsEndpoint, res.StatementID, "result", "chunks", strconv.Itoa(*nextChunk)) + var chunk statementResultChunk + chunkRateLimit, err := c.Get(ctx, u, &chunk) + if chunkRateLimit != nil { + rateLimit = chunkRateLimit + } + if err != nil { + return nil, rateLimit, fmt.Errorf("failed to fetch statement result chunk %d: %w", *nextChunk, err) + } + ctxzap.Extract(ctx).Debug("collectStatementResult: fetched sql statement result chunk", + zap.String("statement_id", res.StatementID), + zap.Int("chunk_index", *nextChunk), + zap.Int("row_count", len(chunk.DataArray)), + ) + rows = append(rows, chunk.DataArray...) + nextChunk = chunk.NextChunkIndex + } + + return &StatementResult{Columns: columns, Rows: rows}, rateLimit, nil +} + +// WarehouseExists reports whether warehouseId exists in workspaceId, since SQL warehouses +// are workspace-scoped with no account-level lookup. +func (c *Client) WarehouseExists(ctx context.Context, workspaceId, warehouseId string) (bool, *v2.RateLimitDescription, error) { + u := c.workspaceUrl(workspaceId).JoinPath(warehousesEndpoint, warehouseId) + + var res struct{} + rateLimit, err := c.Get(ctx, u, &res) + if err != nil { + var apiErr *APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound { + ctxzap.Extract(ctx).Debug("WarehouseExists: sql warehouse not found in workspace", + zap.String("workspace_id", workspaceId), + zap.String("warehouse_id", warehouseId), + ) + return false, rateLimit, nil + } + return false, rateLimit, err + } + + ctxzap.Extract(ctx).Debug("WarehouseExists: sql warehouse found in workspace", + zap.String("workspace_id", workspaceId), + zap.String("warehouse_id", warehouseId), + ) + return true, rateLimit, nil +} diff --git a/pkg/databricks/sql_test.go b/pkg/databricks/sql_test.go new file mode 100644 index 00000000..b86d24e3 --- /dev/null +++ b/pkg/databricks/sql_test.go @@ -0,0 +1,130 @@ +package databricks + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type rewriteHostTransport struct{ target *url.URL } + +func (t rewriteHostTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + req.URL.Scheme = t.target.Scheme + req.URL.Host = t.target.Host + return http.DefaultTransport.RoundTrip(req) +} + +func newSQLTestClient(t *testing.T, handler http.HandlerFunc) *Client { + t.Helper() + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + target, err := url.Parse(server.URL) + if err != nil { + t.Fatalf("url.Parse: %v", err) + } + c, err := NewClient(context.Background(), &http.Client{Transport: rewriteHostTransport{target: target}}, + "example.cloud.databricks.com", "accounts.cloud.databricks.com", "acc-1", "", &NoAuth{}, nil) + if err != nil { + t.Fatalf("NewClient: %v", err) + } + return c +} + +func shortenStatementPolling(t *testing.T) { + t.Helper() + interval, maxWait := statementPollInterval, statementPollMaxWait + statementPollInterval, statementPollMaxWait = 10*time.Millisecond, 100*time.Millisecond + t.Cleanup(func() { statementPollInterval, statementPollMaxWait = interval, maxWait }) +} + +func TestExecuteStatementTimeoutExplainsWarehouseState(t *testing.T) { + shortenStatementPolling(t) + + cases := []struct { + name string + statementState StatementState + warehouseState string + want string + }{ + {"stopped warehouse", StatementStatePending, "STOPPED", "SQL warehouse wh-1 is STOPPED and has not started"}, + {"starting warehouse", StatementStatePending, "STARTING", "SQL warehouse wh-1 was still starting"}, + {"running warehouse", StatementStatePending, "RUNNING", "SQL warehouse wh-1 is running but did not pick up the statement"}, + {"running query", StatementStateRunning, "RUNNING", "the query was still running"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var canceled atomic.Bool + c := newSQLTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/cancel"): + canceled.Store(true) + fmt.Fprint(w, `{}`) + case strings.HasSuffix(r.URL.Path, "/sql/warehouses/wh-1"): + fmt.Fprintf(w, `{"id":"wh-1","state":%q}`, tc.warehouseState) + default: + fmt.Fprintf(w, `{"statement_id":"stmt-1","status":{"state":%q}}`, tc.statementState) + } + }) + + _, _, err := c.ExecuteStatement(context.Background(), "dbc-aaa", "wh-1", "SELECT 1") + if err == nil { + t.Fatal("ExecuteStatement() error = nil, want a timeout") + } + if got := status.Code(err); got != codes.DeadlineExceeded { + t.Errorf("error code = %s, want %s", got, codes.DeadlineExceeded) + } + if !strings.Contains(err.Error(), tc.want) { + t.Errorf("error = %q, want it to contain %q", err, tc.want) + } + if !canceled.Load() { + t.Error("statement was not canceled") + } + }) + } +} + +// A poll that is still in flight when the deadline expires must also cancel the statement. +func TestExecuteStatementTimeoutDuringPollCancelsStatement(t *testing.T) { + shortenStatementPolling(t) + + var canceled atomic.Bool + c := newSQLTestClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/cancel"): + canceled.Store(true) + fmt.Fprint(w, `{}`) + case strings.HasSuffix(r.URL.Path, "/sql/warehouses/wh-1"): + fmt.Fprint(w, `{"id":"wh-1","state":"STOPPED"}`) + case r.Method == http.MethodGet: + select { + case <-r.Context().Done(): + case <-time.After(2 * time.Second): + } + default: + fmt.Fprint(w, `{"statement_id":"stmt-1","status":{"state":"PENDING"}}`) + } + }) + + _, _, err := c.ExecuteStatement(context.Background(), "dbc-aaa", "wh-1", "SELECT 1") + if got := status.Code(err); got != codes.DeadlineExceeded { + t.Fatalf("error = %v, want code %s", err, codes.DeadlineExceeded) + } + if !strings.Contains(err.Error(), "has not started") { + t.Errorf("error = %q, want the warehouse state explained", err) + } + if !canceled.Load() { + t.Error("statement was not canceled") + } +} diff --git a/test-server/README.md b/test-server/README.md new file mode 100644 index 00000000..aa6f7189 --- /dev/null +++ b/test-server/README.md @@ -0,0 +1,294 @@ +# Databricks test server + +A local stand-in for the Databricks APIs that baton-databricks calls from `Validate` and the +incremental sync event feed (`databricks_audit_log`, which reads `system.access.audit` through the +SQL Statement Execution API). It lets you run the event feed end to end without a Databricks +account, locally and in CI. + +Go standard library only, built from the root module. State is in memory, seeded at startup and +reset on every start. Full sync and provisioning endpoints are not implemented yet. + +## Running it + +```bash +# Start the server from the repo root; it writes its CA certificate to ./test-server-ca.pem +go run ./test-server/ + +# Build the connector and run the event feed against it; events are printed to stdout as JSON lines +go build ./cmd/baton-databricks +SSL_CERT_FILE=./test-server-ca.pem ./baton-databricks \ + --hostname localhost:8765 --account-hostname localhost:8765 \ + --account-id test-account \ + --databricks-client-id test-client --databricks-client-secret test-secret \ + --sql-warehouse-id wh-serverless \ + --event-feed true --event-feed-id databricks_audit_log \ + --event-feed-start-at "$(date -u -d '2 days ago' +%Y-%m-%dT%H:%M:%SZ)" +``` + +`--event-feed true` is what selects the event feed mode; `--event-feed-id` alone doesn't. The +connector's logs go to stderr, so stdout holds only events. + +To compare with the expected output (event times depend on when the server started, so +`occurredAt` is dropped): + +```bash +normalize() { jq -c -S 'del(.occurredAt)' "$1" | sort; } +diff <(normalize test-server/testdata/expected-events.jsonl) <(normalize events.jsonl) +``` + +### Flags + +| Flag | Default | Meaning | +|---|---|---| +| `--addr` | `localhost:8765` | Listen address | +| `--ca-out` | `./test-server-ca.pem` | Where to write the generated CA certificate | +| `--warehouse-start-delay` | `0s` | How long a stopped warehouse takes to reach `RUNNING` once a statement starts it | +| `--chunk-rows` | `0` | Rows per result chunk; `0` returns every row in one chunk | + +### TLS and hosts + +The connector always builds `https://` URLs, so the server serves TLS. At startup it creates a +throwaway CA and a certificate for `localhost`, `*.localhost` and each seeded workspace host +(`ws-alpha.localhost`, ...), and writes the CA to `--ca-out`. The connector trusts it through +`SSL_CERT_FILE`. The workspace hosts are listed because OpenSSL, and so curl, doesn't match a +`*.localhost` wildcard; Go does. + +The server routes by `Host` header: + +- `localhost:8765` is the account API and OAuth host (`--account-hostname`). +- `.localhost:8765` is that workspace (the connector builds + `.`). Go resolves any `*.localhost` name to loopback, so no DNS setup + is needed. An unknown deployment name gets a 404. + +**macOS:** Go ignores `SSL_CERT_FILE` on macOS and uses the keychain. Either trust the CA in the +keychain or run the connector in a Linux container. + +### Other warehouses + +- `--sql-warehouse-id wh-pro` reads the same events through a stopped warehouse in `ws-beta`. + The first statement starts it. With `--warehouse-start-delay 35s` the connector's first wait (30s) + times out and it then polls until the warehouse is running. +- `--sql-warehouse-id wh-broken` never starts. The connector gives up after its 5-minute limit, + cancels the statement, and fails with "SQL warehouse wh-broken is STOPPED and has not started". + +## Auth + +| | Value | +|---|---| +| Account ID | `test-account` | +| Client ID / secret | `test-client` / `test-secret` | +| Access token | `test-access-token` | + +The token endpoint takes the client ID and secret as HTTP Basic auth, with form fields +`grant_type=client_credentials` and `scope=all-apis`. Every other endpoint (except `/health`) +needs `Authorization: Bearer test-access-token` and returns 401 +`{"error_code": "UNAUTHENTICATED", ...}` without it. + +## Endpoints + +| Host | Method | Path | Docs | +|---|---|---|---| +| account | POST | `/oidc/accounts/{account_id}/v1/token` | [OAuth M2M](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m) | +| account | GET | `/api/2.0/preview/accounts/{account_id}/access-control/assignable-roles` | [Account access control](https://docs.databricks.com/api/account/accountaccesscontrol/getassignablerolesforresource) | +| account | GET | `/api/2.0/accounts/{account_id}/workspaces` | [List workspaces](https://docs.databricks.com/api/account/workspaces/list) | +| account | GET | `/api/2.0/accounts/{account_id}/scim/v2/Users/{id}` | [Get account user](https://docs.databricks.com/api/account/accountusers/get) | +| account | GET | `/api/2.0/accounts/{account_id}/scim/v2/Groups/{id}` | [Get account group](https://docs.databricks.com/api/account/accountgroups/get) | +| account | GET | `/api/2.0/accounts/{account_id}/scim/v2/ServicePrincipals/{id}` | [Get account service principal](https://docs.databricks.com/api/account/accountserviceprincipals/get) | +| workspace | GET | `/api/2.0/sql/warehouses/{id}` | [Get a warehouse](https://docs.databricks.com/api/workspace/warehouses/get) | +| workspace | POST | `/api/2.0/sql/statements` | [Execute a statement](https://docs.databricks.com/api/workspace/statementexecution/executestatement) | +| workspace | GET | `/api/2.0/sql/statements/{id}` | [Get a statement](https://docs.databricks.com/api/workspace/statementexecution/getstatement) | +| workspace | POST | `/api/2.0/sql/statements/{id}/cancel` | [Cancel a statement](https://docs.databricks.com/api/workspace/statementexecution/cancelexecution) | +| workspace | GET | `/api/2.0/sql/statements/{id}/result/chunks/{n}` | [Get result chunk](https://docs.databricks.com/api/workspace/statementexecution/getstatementresultchunkn) | +| any | GET | `/health` | None: local readiness check | + +Every route in `handlers.go` links its doc page. + +## Behavior and provenance + +Code comments label each behavior: + +- `DOC`: stated in the official Databricks docs (with a link). +- `ASSUMPTION`: not documented; our best guess at the real behavior. +- `DECISION`: a choice made for this server, with no real-world counterpart. + +### From the docs + +- Token endpoint: Basic client credentials, `grant_type=client_credentials`, `scope=all-apis`; + returns `{access_token, token_type: "Bearer", expires_in: 3600}`. +- API errors use `{error_code, message}`; a missing or wrong token is 401 `UNAUTHENTICATED`. +- The workspaces list is a bare JSON array (`workspace_id` int64, `workspace_name`, + `deployment_name`, `aws_region`, `workspace_status`, ...). +- SCIM user, group and service principal objects and their fields. +- Warehouse fields and `state` values (`STARTING`, `RUNNING`, `STOPPED`, ...). A statement on a + warehouse that isn't running stays `PENDING`. +- `wait_timeout` is `0s` or `5s`–`50s` (default `10s`); anything else is 400 + `INVALID_PARAMETER_VALUE`. `on_wait_timeout` is `CONTINUE` (default) or `CANCEL`. +- A statement that finishes within `wait_timeout` returns its result; otherwise the response has + its ID and `PENDING`. GET returns the manifest and first chunk once `SUCCEEDED`. Cancel returns + `{}` and the statement becomes `CANCELED`. +- `data_array` values are strings, nulls are JSON `null`, and `next_chunk_index` is absent on the + last chunk. Column `type_name` values (`STRING`, `TIMESTAMP`, `LONG`, `MAP`, ...). +- Parameters are named `:name` markers with an optional `type` (default `STRING`). +- `system.access.audit` columns; account-level events have `workspace_id = 0`; the + `request_params` keys of each event ([audit log reference](https://docs.databricks.com/aws/en/admin/account-settings/audit-logs)), + including workspace-level `createGroup` without `targetGroupId` and `updatePermissionAssignment` + without `workspace_id`. +- Regionality: "Most audit logs are only available in the region of the workspace" + ([system tables: audit logs](https://docs.databricks.com/aws/en/admin/system-tables/audit-logs)). + Here, a warehouse sees workspace-level rows only from workspaces in its own region, and + account-level rows from every region. + +### What's not from the docs + +| Kind | Behavior | +|---|---| +| `ASSUMPTION` | Token endpoint failures use the RFC 6749 body `{error, error_description}` (401 bad client, 400 bad grant or scope). | +| `ASSUMPTION` | An account ID other than `test-account` gets 404 `RESOURCE_DOES_NOT_EXIST`. | +| `ASSUMPTION` | SCIM 404 body uses the SCIM error schema (`schemas`, `detail`, `status: "404"`). | +| `ASSUMPTION` | Unknown API paths get 404 `ENDPOINT_NOT_FOUND`. | +| `ASSUMPTION` | A warehouse that doesn't exist in the request's workspace is 404 `RESOURCE_DOES_NOT_EXIST`, both for GET warehouse and for `warehouse_id` on a statement. The docs only say it's an error. | +| `ASSUMPTION` | A positional (unnamed) parameter is 400 `INVALID_PARAMETER_VALUE`. | +| `ASSUMPTION` | Submitting a statement starts a stopped warehouse, which is `RUNNING` after `--warehouse-start-delay`. | +| `ASSUMPTION` | `JSON_ARRAY` value formats: `TIMESTAMP` as `2006-01-02T15:04:05.000Z` (UTC, milliseconds), `DATE` as `2006-01-02`, `MAP` as a JSON object string. | +| `ASSUMPTION` | An empty result is one chunk with `row_count: 0` and no `data_array`. | +| `ASSUMPTION` | Unknown statement IDs are 404 `RESOURCE_DOES_NOT_EXIST`; an out-of-range chunk or a chunk of a statement without a result is 400. | +| `ASSUMPTION` | An unbound `:name` marker fails the statement with `[UNBOUND_SQL_PARAMETER]`. Accepted `TIMESTAMP` parameter formats: RFC 3339 or `yyyy-mm-dd hh:mm:ss[.ffffff]`. | +| `DECISION` | Hardcoded credentials, account ID and token. | +| `DECISION` | TLS with a generated CA; routing by `Host` header; `/health`. | +| `DECISION` | Assignable roles returns a fixed list. | +| `DECISION` | Seed warehouses: `wh-serverless` running, `wh-pro` stopped, `wh-broken` never starts (stays `STOPPED` with `health.status: FAILED`). | +| `DECISION` | Statements go straight from `PENDING` to `SUCCEEDED`/`FAILED` once the warehouse runs; there's no visible `RUNNING` state. | +| `DECISION` | One result chunk unless `--chunk-rows` is set; only `format: JSON_ARRAY` and `disposition: INLINE` (no `EXTERNAL_LINKS`); no 12-hour statement expiry. | +| `DECISION` | SQL handling (below). | +| `DECISION` | Seed data is synthetic (below). | + +### SQL handling (`DECISION`) + +The server doesn't run SQL. It recognizes `SELECT FROM system.access.audit` and: + +- binds the typed `:name` parameters; +- applies the predicates the connector's query uses, recognized by shape: + `event_date >= :d`, `(event_time > :t OR (event_time = :t AND event_id > :id))`, + `event_time <= :cutoff`, `service_name IN (...)`, `action_name IN (...)` and + `response.status_code = n` (seed rows are 200 unless they set another status); +- requires `ORDER BY event_time ASC, event_id ASC` and applies a trailing `LIMIT n`; +- fails any other statement with `FAILED` and "test-server: unsupported statement". + +This is deliberately tied to the shape of the connector's audit query +(`pkg/connector/audit_event_feed.go`). If that query changes shape, update `statements.go`. + +## Seed data + +All IDs and times are made up. Times are relative to server start. + +**Workspaces** + +| `deployment_name` | `workspace_id` | Region | +|---|---|---| +| `ws-alpha` | 7474645012345671 | us-east-1 | +| `ws-beta` | 7474645012345672 | us-east-1 | +| `ws-gamma` | 8828000011112223 | eu-west-1 | + +**Principals** + +| Kind | ID | Name | +|---|---|---| +| User | 4410000000000001 | alice@example.com | +| User | 4410000000000002 | bob@example.com | +| User | 4410000000000003 | carol@example.com (inactive) | +| User | 4410000000000004 | dave@example.com | +| Group | 5520000000000001 | data-engineers | +| Group | 5520000000000002 | analysts | +| Service principal | 6630000000000001 | ci-bot | +| None (deleted principal) | 9990000000000001 | matches nothing | + +**Warehouses** + +| ID | Workspace | State | +|---|---|---| +| `wh-serverless` | `ws-alpha` | `RUNNING` (serverless) | +| `wh-pro` | `ws-beta` | `STOPPED`; starts on the first statement | +| `wh-broken` | `ws-alpha` | `STOPPED`; never starts | + +**Audit rows and the events they should produce** + +Rows the connector should read fall between 26 and 5 hours before server start: older than its +4-hour lag window and inside an `--event-feed-start-at` of 2 days ago. Event IDs are +`/`, and seed event IDs are `e0000001-0000-4000-8000-0000000000NN`. The expected +events, as protojson, are in `testdata/expected-events.jsonl`. Every principal is parented to the +account, as in full sync. + +| # | Time | Workspace | `service_name` / `action_name` | Key `request_params` | Expected events | +|---|---|---|---|---|---| +| 1 | −26h | 0 | accounts / `add` | targetUserId dave | dave changed | +| 2 | −25h | 0 | accounts / `activateUser` | targetUserId bob | bob changed | +| 3 | −24h | 0 | accounts / `deactivateUser` | targetUserId carol | carol changed | +| 4 | −23h | 0 | accounts / `createGroup` | targetGroupId analysts | analysts changed | +| 5 | −22h | 0 | accounts / `addPrincipalToGroup` | data-engineers ← alice | grant: alice gets data-engineers `member` | +| 6 | −21h | 0 | accounts / `addPrincipalToGroup` | data-engineers ← analysts | grant: group analysts gets data-engineers `member` | +| 7 | −20h | 0 | accounts / `addPrincipalsToGroup` | analysts ← ci-bot | grant: service principal ci-bot gets analysts `member` | +| 8 | −19h | 0 | accounts / `removePrincipalFromGroup` | data-engineers ← bob | revoke: bob loses data-engineers `member` | +| 9 | −18h | 0 | accounts / `removePrincipalFromGroup` | data-engineers ← deleted principal | data-engineers changed (member can't be resolved) | +| 10 | −17h | 0 | accounts / `setAccountAdmin` | targetUserId alice | alice changed; `account_admin` role changed | +| 11 | −16h | ws-alpha | accounts / `setAdmin` | targetUserId bob | bob changed; `account_admin` role changed (the connector refreshes it in case `setAdmin` is account admin, which the reference is ambiguous about) | +| 12 | −15h | ws-alpha | accounts / `removeAdmin` | targetUserId bob | bob changed | +| 13 | −14h | ws-alpha | accounts / `createGroup` (workspace-level, no `targetGroupId`) | targetUserId alice | none | +| 14 | −13h | ws-beta | accounts / `delete` | targetUserId carol | carol changed | +| 15 | −12h | 0 | workspace / `addPermissionAssignment` | workspace_id ws-alpha | ws-alpha changed | +| 16 | −11h | 0 | workspace / `updatePermissionAssignment` (no `workspace_id`) | principal_id dave | none | +| 17 | −10h | ws-beta | workspace / `deletePermissionAssignment` | workspace_id ws-beta | ws-beta changed | +| 18 | −9h | ws-gamma | accounts / `add` | targetUserId alice | none: eu-west-1 isn't visible from a us-east-1 warehouse | +| 19 | −8h | ws-alpha | accounts / `updateUser` | targetUserId alice | alice changed; `ws-alpha:workspace-access`, `ws-alpha:databricks-sql-access`, `ws-alpha:allow-cluster-create` and `ws-alpha:allow-instance-pool-create` changed | +| 20 | −7h | ws-beta | accounts / `updateGroup` | targetGroupId analysts | analysts changed; `ws-beta:workspace-access`, `ws-beta:databricks-sql-access`, `ws-beta:allow-cluster-create` and `ws-beta:allow-instance-pool-create` changed | +| 21 | −6h | 0 | accounts / `removeGroup` | targetGroupId data-engineers | data-engineers changed | +| 22 | −6h (same time as 21) | 0 | accounts / `deactivateUser` | targetUserId dave | dave changed | +| 23 | −5h30m | ws-alpha | accounts / `changeDatabricksWorkspaceAcl` | targetUserId carol | ws-alpha changed; `ws-alpha:workspace-access` changed | +| 24 | −5h | ws-alpha | clusters / `create` | | none: not requested | +| 25 | −2h | 0 | accounts / `add` | targetUserId bob | none: newer than the 4-hour lag cutoff | +| 26 | −72h | 0 | accounts / `add` | targetUserId carol | none: older than the feed start | +| 27 | −18h30m | 0 | accounts / `removePrincipalFromGroup`, `response.status_code` 403 | data-engineers ← alice | none: the request failed, so alice is still a member | + +The table lists what each row maps to, 31 events in all. Within one poll, `ListEvents` keeps +only the last change for each resource (by resource and parent ID), because a resource change +makes C1 re-read the resource's current state anyway. Grant and revoke events are never +collapsed. Several resources appear more than once (bob in rows 2, 11 and 12, `account_admin` in +10 and 11, the ws-alpha roles in 19 and 23, and others), so the poll emits 21 events, each with +the ID of the last row that named its resource. + +## curl examples + +```bash +CA="--cacert ./test-server-ca.pem" + +curl -s $CA https://localhost:8765/health + +TOKEN=$(curl -s $CA -u test-client:test-secret \ + -d grant_type=client_credentials -d scope=all-apis \ + https://localhost:8765/oidc/accounts/test-account/v1/token | jq -r .access_token) + +curl -s $CA -H "Authorization: Bearer $TOKEN" https://localhost:8765/api/2.0/accounts/test-account/workspaces | jq +curl -s $CA -H "Authorization: Bearer $TOKEN" https://localhost:8765/api/2.0/accounts/test-account/scim/v2/Users/4410000000000001 | jq +curl -s $CA -H "Authorization: Bearer $TOKEN" https://ws-alpha.localhost:8765/api/2.0/sql/warehouses/wh-serverless | jq + +curl -s $CA -H "Authorization: Bearer $TOKEN" https://ws-alpha.localhost:8765/api/2.0/sql/statements \ + -d '{ + "warehouse_id": "wh-serverless", + "statement": "SELECT event_id, event_time, action_name FROM system.access.audit WHERE action_name IN ('\''add'\'') ORDER BY event_time ASC, event_id ASC LIMIT 10", + "wait_timeout": "10s" + }' | jq +``` + +## Tests and CI + +`main_test.go` tests the server in process: auth, routing, `wait_timeout` validation, warehouse +and statement state transitions (including the stopped and broken warehouses), cancel and +`on_wait_timeout: CANCEL`, chunking, regionality and the audit filter. It runs with +`go test ./...`. + +The `test-server` job in `.github/workflows/ci.yaml` starts the server, runs the event feed +against `wh-serverless` and diffs the events with `testdata/expected-events.jsonl`. It then runs +against `wh-broken` and checks for the "has not started" message. That step waits out the +connector's 5-minute statement limit. The job needs no secrets. + +If a diff shows up, either the connector or the expectation is wrong; check the row's documented +meaning in the table above before updating `expected-events.jsonl`. diff --git a/test-server/handlers.go b/test-server/handlers.go new file mode 100644 index 00000000..1b88e348 --- /dev/null +++ b/test-server/handlers.go @@ -0,0 +1,262 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" + "strconv" + "time" +) + +func (s *server) accountRoutes() *http.ServeMux { + mux := http.NewServeMux() + // DOC: https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m + mux.HandleFunc("POST /oidc/accounts/{account_id}/v1/token", requireAccount(s.handleToken)) + // DOC: https://docs.databricks.com/api/account/accountaccesscontrol/getassignablerolesforresource + mux.HandleFunc("GET /api/2.0/preview/accounts/{account_id}/access-control/assignable-roles", + requireBearer(requireAccount(s.handleAssignableRoles))) + // DOC: https://docs.databricks.com/api/account/workspaces/list + mux.HandleFunc("GET /api/2.0/accounts/{account_id}/workspaces", requireBearer(requireAccount(s.handleListWorkspaces))) + // DOC: https://docs.databricks.com/api/account/accountusers/get + mux.HandleFunc("GET /api/2.0/accounts/{account_id}/scim/v2/Users/{id}", requireBearer(requireAccount(s.handleGetUser))) + // DOC: https://docs.databricks.com/api/account/accountgroups/get + mux.HandleFunc("GET /api/2.0/accounts/{account_id}/scim/v2/Groups/{id}", requireBearer(requireAccount(s.handleGetGroup))) + // DOC: https://docs.databricks.com/api/account/accountserviceprincipals/get + mux.HandleFunc("GET /api/2.0/accounts/{account_id}/scim/v2/ServicePrincipals/{id}", + requireBearer(requireAccount(s.handleGetServicePrincipal))) + mux.HandleFunc("/", handleNotFound) + return mux +} + +func (s *server) workspaceRoutes() *http.ServeMux { + mux := http.NewServeMux() + // DOC: https://docs.databricks.com/api/workspace/warehouses/get + mux.HandleFunc("GET /api/2.0/sql/warehouses/{id}", requireBearer(s.handleGetWarehouse)) + // DOC: https://docs.databricks.com/api/workspace/statementexecution/executestatement + mux.HandleFunc("POST /api/2.0/sql/statements", requireBearer(s.handleExecuteStatement)) + // DOC: https://docs.databricks.com/api/workspace/statementexecution/getstatement + mux.HandleFunc("GET /api/2.0/sql/statements/{id}", requireBearer(s.handleGetStatement)) + // DOC: https://docs.databricks.com/api/workspace/statementexecution/cancelexecution + mux.HandleFunc("POST /api/2.0/sql/statements/{id}/cancel", requireBearer(s.handleCancelStatement)) + // DOC: https://docs.databricks.com/api/workspace/statementexecution/getstatementresultchunkn + mux.HandleFunc("GET /api/2.0/sql/statements/{id}/result/chunks/{n}", requireBearer(s.handleGetResultChunk)) + mux.HandleFunc("/", handleNotFound) + return mux +} + +// handleNotFound answers any route this server doesn't implement. +// ASSUMPTION: Databricks answers unknown API paths with 404 ENDPOINT_NOT_FOUND. +func handleNotFound(w http.ResponseWriter, r *http.Request) { + writeError(w, http.StatusNotFound, "ENDPOINT_NOT_FOUND", "test-server: no route for "+r.Method+" "+r.URL.Path) +} + +// handleToken implements the OAuth M2M client-credentials token endpoint. +// DOC: HTTP Basic client ID/secret, grant_type=client_credentials, scope=all-apis; returns +// {access_token, token_type: "Bearer", expires_in: 3600}. +// ASSUMPTION: failures use the RFC 6749 error body ({error, error_description}) with 400/401. +func (s *server) handleToken(w http.ResponseWriter, r *http.Request) { + clientID, clientSecret, ok := r.BasicAuth() + if !ok || clientID != testClientID || clientSecret != testClientSecret { + writeJSON(w, http.StatusUnauthorized, map[string]string{ + "error": "invalid_client", + "error_description": "Client authentication failed", + }) + return + } + if err := r.ParseForm(); err != nil { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request", "error_description": err.Error()}) + return + } + if r.PostForm.Get("grant_type") != "client_credentials" { + writeJSON(w, http.StatusBadRequest, map[string]string{ + "error": "unsupported_grant_type", + "error_description": "grant_type must be client_credentials", + }) + return + } + if r.PostForm.Get("scope") != "all-apis" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_scope", "error_description": "scope must be all-apis"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "access_token": testAccessToken, + "token_type": "Bearer", + "expires_in": 3600, + "scope": "all-apis", + }) +} + +// handleAssignableRoles returns the roles assignable on a resource. +// DOC: response shape {roles: [{name}]}. DECISION: a fixed list, whatever the resource. +func (s *server) handleAssignableRoles(w http.ResponseWriter, _ *http.Request) { + writeJSON(w, http.StatusOK, map[string]any{ + "roles": []map[string]string{ + {"name": "roles/marketplace.admin"}, + }, + }) +} + +// handleListWorkspaces returns the account's workspaces. +// DOC: a bare JSON array of workspace objects. +func (s *server) handleListWorkspaces(w http.ResponseWriter, _ *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + + out := make([]map[string]any, 0, len(s.st.workspaces)) + for _, ws := range s.st.workspaces { + out = append(out, map[string]any{ + "account_id": testAccountID, + "workspace_id": ws.ID, + "workspace_name": ws.Name, + "deployment_name": ws.DeploymentName, + "aws_region": ws.Region, + "workspace_status": "RUNNING", + "pricing_tier": "PREMIUM", + "creation_time": s.start.Add(-90 * 24 * time.Hour).UnixMilli(), + }) + } + writeJSON(w, http.StatusOK, out) +} + +// DOC: SCIM user, group and service principal objects, per the account SCIM API pages. +func (s *server) handleGetUser(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + u, ok := s.st.users[r.PathValue("id")] + s.mu.Unlock() + if !ok { + writeSCIMNotFound(w, "User "+r.PathValue("id")+" not found") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:User"}, + "id": u.ID, + "userName": u.UserName, + "displayName": u.DisplayName, + "active": u.Active, + "emails": []map[string]any{{"value": u.UserName, "type": "work", "primary": true}}, + }) +} + +func (s *server) handleGetGroup(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + g, ok := s.st.groups[r.PathValue("id")] + s.mu.Unlock() + if !ok { + writeSCIMNotFound(w, "Group "+r.PathValue("id")+" not found") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:Group"}, + "id": g.ID, + "displayName": g.DisplayName, + }) +} + +func (s *server) handleGetServicePrincipal(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + sp, ok := s.st.servicePrincipals[r.PathValue("id")] + s.mu.Unlock() + if !ok { + writeSCIMNotFound(w, "ServicePrincipal "+r.PathValue("id")+" not found") + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "schemas": []string{"urn:ietf:params:scim:schemas:core:2.0:ServicePrincipal"}, + "id": sp.ID, + "applicationId": sp.ApplicationID, + "displayName": sp.DisplayName, + "active": sp.Active, + }) +} + +// writeSCIMNotFound writes a SCIM 404. +// ASSUMPTION: the SCIM error schema (schemas, detail, status); the 404 body is not documented. +func writeSCIMNotFound(w http.ResponseWriter, detail string) { + writeJSON(w, http.StatusNotFound, map[string]any{ + "schemas": []string{"urn:ietf:params:scim:api:messages:2.0:Error"}, + "detail": detail, + "status": "404", + }) +} + +// handleGetWarehouse returns a warehouse in the request's workspace. +// DOC: warehouse fields and state values (STARTING, RUNNING, STOPPING, STOPPED, DELETING, DELETED). +// ASSUMPTION: a warehouse that isn't in this workspace is 404 RESOURCE_DOES_NOT_EXIST. +func (s *server) handleGetWarehouse(w http.ResponseWriter, r *http.Request) { + ws := requestWorkspace(r) + + s.mu.Lock() + defer s.mu.Unlock() + + wh, ok := s.st.warehouses[r.PathValue("id")] + if !ok || wh.DeploymentName != ws.DeploymentName { + writeError(w, http.StatusNotFound, "RESOURCE_DOES_NOT_EXIST", "Warehouse "+r.PathValue("id")+" does not exist.") + return + } + + state := s.warehouseState(wh) + health := map[string]any{"status": "HEALTHY"} + if wh.NeverStarts { + // DECISION: the broken warehouse reports why it can't start. + health = map[string]any{ + "status": "FAILED", + "summary": "test-server: this warehouse never starts", + "failure_reason": map[string]any{ + "code": "INSTANCE_UNREACHABLE", + "type": "CLOUD_FAILURE", + }, + } + } + + writeJSON(w, http.StatusOK, map[string]any{ + "id": wh.ID, + "name": wh.Name, + "warehouse_type": wh.WarehouseType, + "enable_serverless_compute": wh.Serverless, + "cluster_size": "2X-Small", + "min_num_clusters": 1, + "max_num_clusters": 1, + "auto_stop_mins": 10, + "state": state, + "health": health, + "num_clusters": boolToInt(state == warehouseRunning), + "creator_name": "admin@example.com", + "jdbc_url": "jdbc:spark://" + ws.DeploymentName + ".localhost:443/default;transportMode=http;ssl=1;httpPath=/sql/1.0/warehouses/" + wh.ID, + "odbc_params": map[string]any{ + "hostname": ws.DeploymentName + ".localhost", + "path": "/sql/1.0/warehouses/" + wh.ID, + "protocol": "https", + "port": 443, + }, + }) +} + +func boolToInt(b bool) int { + if b { + return 1 + } + return 0 +} + +// apiError is the documented error body: https://docs.databricks.com/api/workspace/introduction. +type apiError struct { + ErrorCode string `json:"error_code"` + Message string `json:"message"` +} + +func writeError(w http.ResponseWriter, status int, code, message string) { + writeJSON(w, status, apiError{ErrorCode: code, Message: message}) +} + +func writeJSON(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(body); err != nil { + log.Printf("test-server: writing response: %v", err) + } +} + +func parseChunkIndex(s string) (int, bool) { + n, err := strconv.Atoi(s) + return n, err == nil && n >= 0 +} diff --git a/test-server/main.go b/test-server/main.go new file mode 100644 index 00000000..8e23a73d --- /dev/null +++ b/test-server/main.go @@ -0,0 +1,160 @@ +// Command test-server is a local stand-in for the Databricks APIs that baton-databricks calls +// from Validate and the incremental sync event feed (system.access.audit). It serves TLS on +// one address and routes by Host header: "localhost" is the account API and OAuth host, and +// ".localhost" is that workspace. See README.md for usage, endpoints, seed +// data and which behaviors come from the Databricks docs. +package main + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "flag" + "fmt" + "log" + "math/big" + "net" + "net/http" + "os" + "time" +) + +type config struct { + addr string + caOut string + warehouseStartDelay time.Duration + chunkRows int +} + +func main() { + var cfg config + flag.StringVar(&cfg.addr, "addr", "localhost:8765", "address to listen on") + flag.StringVar(&cfg.caOut, "ca-out", "./test-server-ca.pem", "file to write the generated CA certificate to (PEM)") + flag.DurationVar(&cfg.warehouseStartDelay, "warehouse-start-delay", 0, + "how long a stopped warehouse takes to reach RUNNING after a statement starts it") + flag.IntVar(&cfg.chunkRows, "chunk-rows", 0, "rows per result chunk; 0 returns every row in a single chunk") + flag.Parse() + + if err := run(cfg); err != nil { + fmt.Fprintf(os.Stderr, "test-server: %v\n", err) + os.Exit(1) + } +} + +func run(cfg config) error { + if cfg.chunkRows < 0 { + return errors.New("--chunk-rows must be >= 0") + } + + srv := newServer(cfg, time.Now()) + + hosts := []string{"localhost", "*.localhost"} + for _, ws := range srv.st.workspaces { + hosts = append(hosts, ws.DeploymentName+".localhost") + } + caPEM, cert, err := generateCertificates(hosts) + if err != nil { + return err + } + if err := os.WriteFile(cfg.caOut, caPEM, 0o600); err != nil { + return fmt.Errorf("writing CA certificate: %w", err) + } + httpServer := &http.Server{ + Addr: cfg.addr, + Handler: logRequests(srv), + ReadHeaderTimeout: 10 * time.Second, + TLSConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + Certificates: []tls.Certificate{cert}, + }, + } + + log.Printf("test-server: listening on https://%s (CA written to %s)", cfg.addr, cfg.caOut) + log.Printf("test-server: account API at https://%s, workspaces at https://.%s", cfg.addr, cfg.addr) + return httpServer.ListenAndServeTLS("", "") +} + +// generateCertificates creates a throwaway CA and a server certificate for hosts (DECISION: the +// connector always builds https:// URLs, so the server needs TLS; clients trust the CA through +// SSL_CERT_FILE). Go accepts the *.localhost wildcard, but OpenSSL (and so curl) doesn't match a +// wildcard that close to the top level, so each seeded workspace host is listed too. +func generateCertificates(hosts []string) ([]byte, tls.Certificate, error) { + now := time.Now() + + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, tls.Certificate{}, fmt.Errorf("generating CA key: %w", err) + } + caTemplate := &x509.Certificate{ + SerialNumber: randomSerial(), + Subject: pkix.Name{CommonName: "baton-databricks test-server CA"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(7 * 24 * time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + IsCA: true, + } + caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) + if err != nil { + return nil, tls.Certificate{}, fmt.Errorf("creating CA certificate: %w", err) + } + caCert, err := x509.ParseCertificate(caDER) + if err != nil { + return nil, tls.Certificate{}, fmt.Errorf("parsing CA certificate: %w", err) + } + + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, tls.Certificate{}, fmt.Errorf("generating server key: %w", err) + } + leafTemplate := &x509.Certificate{ + SerialNumber: randomSerial(), + Subject: pkix.Name{CommonName: "localhost"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(7 * 24 * time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: hosts, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, + } + leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, caCert, &leafKey.PublicKey, caKey) + if err != nil { + return nil, tls.Certificate{}, fmt.Errorf("creating server certificate: %w", err) + } + + caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}) + return caPEM, tls.Certificate{Certificate: [][]byte{leafDER, caDER}, PrivateKey: leafKey}, nil +} + +func randomSerial() *big.Int { + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 62)) + if err != nil { + return big.NewInt(time.Now().UnixNano()) + } + return serial +} + +type statusRecorder struct { + http.ResponseWriter + status int +} + +func (r *statusRecorder) WriteHeader(status int) { + r.status = status + r.ResponseWriter.WriteHeader(status) +} + +func logRequests(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} + started := time.Now() + next.ServeHTTP(rec, r) + //nolint:gosec // G706: local test-server log; request values are %q-quoted, so they cannot forge log lines. + log.Printf("%q %q -> %d (%s)", r.Method, r.Host+r.URL.Path, rec.status, time.Since(started).Round(time.Millisecond)) + }) +} diff --git a/test-server/main_test.go b/test-server/main_test.go new file mode 100644 index 00000000..9c7b33a5 --- /dev/null +++ b/test-server/main_test.go @@ -0,0 +1,492 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +var testStart = time.Date(2026, 1, 15, 12, 0, 0, 0, time.UTC) + +// testServer is a server whose clock only moves when the test advances it. +type testServer struct { + *server + clock time.Time +} + +func newTestServer(cfg config) *testServer { + ts := &testServer{server: newServer(cfg, testStart), clock: testStart} + ts.now = func() time.Time { return ts.clock } + return ts +} + +func (ts *testServer) do(t *testing.T, method, url, body string) (int, map[string]any) { + t.Helper() + rec := ts.raw(t, method, url, body, "Bearer "+testAccessToken) + return rec.Code, decodeObject(t, rec) +} + +func (ts *testServer) raw(t *testing.T, method, url, body, authorization string) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(t.Context(), method, url, strings.NewReader(body)) + if authorization != "" { + req.Header.Set("Authorization", authorization) + } + if method == http.MethodPost && strings.Contains(url, "/oidc/") { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + rec := httptest.NewRecorder() + ts.ServeHTTP(rec, req) + return rec +} + +func decodeObject(t *testing.T, rec *httptest.ResponseRecorder) map[string]any { + t.Helper() + var out map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("response is not a JSON object: %v: %s", err, rec.Body.String()) + } + return out +} + +const ( + accountURL = "https://localhost:8765" + alphaURL = "https://ws-alpha.localhost:8765" + betaURL = "https://ws-beta.localhost:8765" +) + +// connectorStatement has the shape of the connector's audit query (pkg/connector/audit_event_feed.go). +const connectorStatement = ` + SELECT event_id, event_time, workspace_id, action_name, service_name, request_params + FROM system.access.audit + WHERE event_date >= :start_date + AND (event_time > :start_time OR (event_time = :start_time AND event_id > :start_after_event_id)) + AND event_time <= :lag_cutoff + AND service_name IN ('accounts', 'workspace') + AND action_name IN (%s) + AND response.status_code = 200 + ORDER BY event_time ASC, event_id ASC + LIMIT %d + ` + +const connectorActions = `'activateUser', 'add', 'addPermissionAssignment', 'addPrincipalToGroup', 'addPrincipalsToGroup', + 'changeDatabricksSqlAcl', 'changeDatabricksWorkspaceAcl', 'createGroup', 'deactivateUser', 'delete', + 'deletePermissionAssignment', 'removeAccountAdmin', 'removeAdmin', 'removeGroup', 'removePrincipalFromGroup', + 'removePrincipalsFromGroup', 'setAccountAdmin', 'setAdmin', 'updateGroup', 'updatePermissionAssignment', 'updateUser'` + +func statementRequest(t *testing.T, warehouseID, waitTimeout string, startTime time.Time, startAfter string, limit int) string { + t.Helper() + cutoff := testStart.Add(-4 * time.Hour) + body := map[string]any{ + "warehouse_id": warehouseID, + "statement": fmt.Sprintf(connectorStatement, connectorActions, limit), + "wait_timeout": waitTimeout, + "format": "JSON_ARRAY", + "disposition": "INLINE", + "parameters": []map[string]string{ + {"name": "start_date", "value": startTime.Format(time.DateOnly), "type": "DATE"}, + {"name": "start_time", "value": startTime.Format(time.RFC3339Nano), "type": "TIMESTAMP"}, + {"name": "start_after_event_id", "value": startAfter, "type": "STRING"}, + {"name": "lag_cutoff", "value": cutoff.Format(time.RFC3339Nano), "type": "TIMESTAMP"}, + }, + } + b, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func eventID(n int) string { + return fmt.Sprintf("e0000001-0000-4000-8000-%012d", n) +} + +func eventIDs(t *testing.T, body map[string]any) []string { + t.Helper() + result, _ := body["result"].(map[string]any) + rows, _ := result["data_array"].([]any) + ids := make([]string, 0, len(rows)) + for _, r := range rows { + row, _ := r.([]any) + id, _ := row[0].(string) + ids = append(ids, id) + } + return ids +} + +func stmtState(body map[string]any) string { + status, _ := body["status"].(map[string]any) + s, _ := status["state"].(string) + return s +} + +func TestHealth(t *testing.T) { + ts := newTestServer(config{}) + for _, url := range []string{accountURL + "/health", alphaURL + "/health"} { + if rec := ts.raw(t, http.MethodGet, url, "", ""); rec.Code != http.StatusOK { + t.Errorf("%s: got %d", url, rec.Code) + } + } +} + +func TestToken(t *testing.T) { + ts := newTestServer(config{}) + tokenURL := accountURL + "/oidc/accounts/test-account/v1/token" + form := "grant_type=client_credentials&scope=all-apis" + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, tokenURL, strings.NewReader(form)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.SetBasicAuth(testClientID, testClientSecret) + rec := httptest.NewRecorder() + ts.ServeHTTP(rec, req) + body := decodeObject(t, rec) + if rec.Code != http.StatusOK || body["access_token"] != testAccessToken || body["token_type"] != "Bearer" { + t.Fatalf("good credentials: got %d %v", rec.Code, body) + } + + req = httptest.NewRequestWithContext(t.Context(), http.MethodPost, tokenURL, strings.NewReader(form)) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.SetBasicAuth(testClientID, "wrong") + rec = httptest.NewRecorder() + ts.ServeHTTP(rec, req) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("bad secret: got %d", rec.Code) + } +} + +func TestBearerRequired(t *testing.T) { + ts := newTestServer(config{}) + for _, auth := range []string{"", "Bearer wrong"} { + rec := ts.raw(t, http.MethodGet, accountURL+"/api/2.0/accounts/test-account/workspaces", "", auth) + body := decodeObject(t, rec) + if rec.Code != http.StatusUnauthorized || body["error_code"] != "UNAUTHENTICATED" { + t.Errorf("auth %q: got %d %v", auth, rec.Code, body) + } + } +} + +func TestAccountEndpoints(t *testing.T) { + ts := newTestServer(config{}) + + rec := ts.raw(t, http.MethodGet, accountURL+"/api/2.0/accounts/test-account/workspaces", "", "Bearer "+testAccessToken) + var workspaces []map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &workspaces); err != nil || len(workspaces) != 3 { + t.Fatalf("workspaces: want a bare array of 3, got %d %s", rec.Code, rec.Body.String()) + } + // Large IDs must come out as exact integers, not floats in scientific notation. + if !strings.Contains(rec.Body.String(), `"workspace_id":7474645012345671`) { + t.Errorf("workspace_id not rendered as an exact integer: %s", rec.Body.String()) + } + + if code, _ := ts.do(t, http.MethodGet, accountURL+"/api/2.0/preview/accounts/test-account/access-control/assignable-roles", ""); code != http.StatusOK { + t.Errorf("assignable roles: got %d", code) + } + if code, _ := ts.do(t, http.MethodGet, accountURL+"/api/2.0/accounts/other-account/workspaces", ""); code != http.StatusNotFound { + t.Errorf("other account: got %d", code) + } + + scim := accountURL + "/api/2.0/accounts/test-account/scim/v2/" + cases := []struct { + path string + want int + }{ + {"Users/" + userAlice, http.StatusOK}, + {"Groups/" + groupAnalysts, http.StatusOK}, + {"ServicePrincipals/" + spCIBot, http.StatusOK}, + {"Users/" + groupAnalysts, http.StatusNotFound}, + {"Users/" + deletedPrincipal, http.StatusNotFound}, + {"Groups/" + deletedPrincipal, http.StatusNotFound}, + {"ServicePrincipals/" + deletedPrincipal, http.StatusNotFound}, + } + for _, c := range cases { + code, body := ts.do(t, http.MethodGet, scim+c.path, "") + if code != c.want { + t.Errorf("%s: got %d, want %d", c.path, code, c.want) + } + if c.want == http.StatusNotFound && body["status"] != "404" { + t.Errorf("%s: want a SCIM error body, got %v", c.path, body) + } + } +} + +func TestRouting(t *testing.T) { + ts := newTestServer(config{}) + if code, _ := ts.do(t, http.MethodGet, "https://ws-nope.localhost:8765/api/2.0/sql/warehouses/wh-serverless", ""); code != http.StatusNotFound { + t.Errorf("unknown workspace host: got %d", code) + } + if code, _ := ts.do(t, http.MethodGet, alphaURL+"/api/2.0/sql/warehouses/wh-serverless", ""); code != http.StatusOK { + t.Errorf("warehouse in its workspace: got %d", code) + } + if code, _ := ts.do(t, http.MethodGet, betaURL+"/api/2.0/sql/warehouses/wh-serverless", ""); code != http.StatusNotFound { + t.Errorf("warehouse from another workspace: got %d", code) + } + if code, _ := ts.do(t, http.MethodGet, accountURL+"/api/2.0/sql/warehouses/wh-serverless", ""); code != http.StatusNotFound { + t.Errorf("workspace API on the account host: got %d", code) + } +} + +func TestWaitTimeoutValidation(t *testing.T) { + ts := newTestServer(config{}) + for _, wait := range []string{"0s", "5s", "50s"} { + code, _ := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-serverless", wait, testStart.Add(-48*time.Hour), "", 10)) + if code != http.StatusOK { + t.Errorf("wait_timeout %s: got %d", wait, code) + } + } + for _, wait := range []string{"1s", "4s", "51s", "10", "5m", "-5s"} { + code, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-serverless", wait, testStart.Add(-48*time.Hour), "", 10)) + if code != http.StatusBadRequest || body["error_code"] != "INVALID_PARAMETER_VALUE" { + t.Errorf("wait_timeout %s: got %d %v", wait, code, body) + } + } +} + +func TestStatementErrors(t *testing.T) { + ts := newTestServer(config{}) + url := alphaURL + "/api/2.0/sql/statements" + + code, _ := ts.do(t, http.MethodPost, url, statementRequest(t, "wh-missing", "0s", testStart, "", 10)) + if code != http.StatusNotFound { + t.Errorf("unknown warehouse: got %d", code) + } + code, _ = ts.do(t, http.MethodPost, url, `{"warehouse_id":"wh-serverless","statement":"SELECT ?","parameters":[{"value":"1"}]}`) + if code != http.StatusBadRequest { + t.Errorf("positional parameter: got %d", code) + } + + code, body := ts.do(t, http.MethodPost, url, `{"warehouse_id":"wh-serverless","statement":"SELECT 1","wait_timeout":"0s"}`) + status, _ := body["status"].(map[string]any) + errBody, _ := status["error"].(map[string]any) + msg, _ := errBody["message"].(string) + if code != http.StatusOK || stmtState(body) != statementFailed || !strings.Contains(msg, "test-server: unsupported statement") { + t.Errorf("unsupported statement: got %d %v", code, body) + } + + code, body = ts.do(t, http.MethodPost, url, + `{"warehouse_id":"wh-serverless","statement":"SELECT event_id FROM system.access.audit WHERE event_time > :t ORDER BY event_time, event_id","wait_timeout":"0s"}`) + if code != http.StatusOK || stmtState(body) != statementFailed { + t.Errorf("unbound parameter: got %d %v", code, body) + } + + if code, _ := ts.do(t, http.MethodGet, url+"/no-such-statement", ""); code != http.StatusNotFound { + t.Errorf("unknown statement: got %d", code) + } +} + +func TestAuditQueryRunningWarehouse(t *testing.T) { + ts := newTestServer(config{}) + code, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", + statementRequest(t, "wh-serverless", "30s", testStart.Add(-48*time.Hour), "", 1000)) + if code != http.StatusOK || stmtState(body) != statementSucceeded { + t.Fatalf("got %d %v", code, body) + } + + // Visible from us-east-1, inside (start-48h, start-4h], in the requested service/action + // lists: every seed row except 18 (eu-west-1), 24 (clusters), 25 (too new) and 26 (too old). + var want []string + for n := 1; n <= 23; n++ { + if n != 18 { + want = append(want, eventID(n)) + } + } + if got := eventIDs(t, body); strings.Join(got, ",") != strings.Join(want, ",") { + t.Errorf("rows:\n got %v\nwant %v", got, want) + } + + manifest, _ := body["manifest"].(map[string]any) + schema, _ := manifest["schema"].(map[string]any) + columns, _ := schema["columns"].([]any) + if len(columns) != 6 { + t.Errorf("want 6 columns, got %v", columns) + } + result, _ := body["result"].(map[string]any) + if _, ok := result["next_chunk_index"]; ok { + t.Errorf("single chunk must not have next_chunk_index: %v", result) + } + + rows, _ := result["data_array"].([]any) + first, _ := rows[0].([]any) + if first[1] != testStart.Add(-26*time.Hour).Format("2006-01-02T15:04:05.000Z") || first[2] != "0" { + t.Errorf("unexpected value formats: %v", first) + } + var params map[string]string + if s, _ := first[5].(string); json.Unmarshal([]byte(s), ¶ms) != nil || params["targetUserId"] != userDave { + t.Errorf("request_params is not a JSON object string: %v", first[5]) + } +} + +func TestAuditQueryPaging(t *testing.T) { + ts := newTestServer(config{}) + rowTime := func(n int) time.Time { + for _, r := range ts.st.audit { + if r.EventID == eventID(n) { + return r.EventTime + } + } + t.Fatalf("no seed row %d", n) + return time.Time{} + } + + _, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-serverless", "10s", rowTime(5), eventID(5), 3)) + if got := eventIDs(t, body); strings.Join(got, ",") != strings.Join([]string{eventID(6), eventID(7), eventID(8)}, ",") { + t.Errorf("page after row 5: got %v", got) + } + + // Rows 21 and 22 share an event_time: the event_id tiebreaker must return only 22. + _, body = ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-serverless", "10s", rowTime(21), eventID(21), 1)) + if got := eventIDs(t, body); len(got) != 1 || got[0] != eventID(22) { + t.Errorf("tiebreak after row 21: got %v", got) + } +} + +func TestAuditQueryStatusCode(t *testing.T) { + ts := newTestServer(config{}) + params := []statementParameter{ + {Name: "start_date", Value: ptr(testStart.Add(-48 * time.Hour).Format(time.DateOnly)), Type: "DATE"}, + {Name: "start_time", Value: ptr(testStart.Add(-48 * time.Hour).Format(time.RFC3339Nano)), Type: "TIMESTAMP"}, + {Name: "start_after_event_id", Value: ptr(""), Type: "STRING"}, + {Name: "lag_cutoff", Value: ptr(testStart.Add(-4 * time.Hour).Format(time.RFC3339Nano)), Type: "TIMESTAMP"}, + } + ids := func(stmt string) map[string]bool { + t.Helper() + _, rows, err := ts.st.runAuditQuery(stmt, params, "us-east-1") + if err != nil { + t.Fatal(err.message) + } + got := map[string]bool{} + for _, r := range rows { + got[*r[0]] = true + } + return got + } + + filtered := ids(fmt.Sprintf(connectorStatement, connectorActions, 1000)) + if filtered[eventID(27)] { + t.Error("response.status_code = 200 should exclude the failed row 27") + } + if !filtered[eventID(8)] { + t.Error("response.status_code = 200 should keep the successful row 8") + } + + unfiltered := ids(strings.Replace(fmt.Sprintf(connectorStatement, connectorActions, 1000), "AND response.status_code = 200", "", 1)) + if !unfiltered[eventID(27)] { + t.Error("without a status filter the failed row 27 should be returned") + } +} + +func TestRegionality(t *testing.T) { + ts := newTestServer(config{}) + stmt := fmt.Sprintf(connectorStatement, connectorActions, 1000) + params := []statementParameter{ + {Name: "start_date", Value: ptr(testStart.Add(-48 * time.Hour).Format(time.DateOnly)), Type: "DATE"}, + {Name: "start_time", Value: ptr(testStart.Add(-48 * time.Hour).Format(time.RFC3339Nano)), Type: "TIMESTAMP"}, + {Name: "start_after_event_id", Value: ptr(""), Type: "STRING"}, + {Name: "lag_cutoff", Value: ptr(testStart.Add(-4 * time.Hour).Format(time.RFC3339Nano)), Type: "TIMESTAMP"}, + } + _, rows, err := ts.st.runAuditQuery(stmt, params, "eu-west-1") + if err != nil { + t.Fatal(err.message) + } + got := map[string]bool{} + for _, r := range rows { + got[*r[0]] = true + } + if !got[eventID(18)] { + t.Error("eu-west-1 should see the ws-gamma row") + } + if !got[eventID(1)] { + t.Error("eu-west-1 should see account-level rows") + } + for _, n := range []int{11, 14, 19} { + if got[eventID(n)] { + t.Errorf("eu-west-1 should not see us-east-1 workspace row %d", n) + } + } +} + +func ptr(s string) *string { return &s } + +func TestStoppedWarehouseColdStart(t *testing.T) { + ts := newTestServer(config{warehouseStartDelay: time.Minute}) + _, body := ts.do(t, http.MethodPost, betaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-pro", "0s", testStart.Add(-48*time.Hour), "", 1000)) + if stmtState(body) != statementPending { + t.Fatalf("want PENDING while the warehouse starts, got %v", body) + } + id, _ := body["statement_id"].(string) + + if _, wh := ts.do(t, http.MethodGet, betaURL+"/api/2.0/sql/warehouses/wh-pro", ""); wh["state"] != warehouseStarting { + t.Errorf("want STARTING, got %v", wh["state"]) + } + if _, polled := ts.do(t, http.MethodGet, betaURL+"/api/2.0/sql/statements/"+id, ""); stmtState(polled) != statementPending { + t.Errorf("want PENDING before the start delay, got %v", polled) + } + + ts.clock = ts.clock.Add(time.Minute) + if _, wh := ts.do(t, http.MethodGet, betaURL+"/api/2.0/sql/warehouses/wh-pro", ""); wh["state"] != warehouseRunning { + t.Errorf("want RUNNING, got %v", wh["state"]) + } + _, polled := ts.do(t, http.MethodGet, betaURL+"/api/2.0/sql/statements/"+id, "") + if stmtState(polled) != statementSucceeded || len(eventIDs(t, polled)) != 22 { + t.Errorf("want SUCCEEDED with 22 rows after the start delay, got %v", polled) + } +} + +func TestBrokenWarehouseAndCancel(t *testing.T) { + ts := newTestServer(config{}) + _, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-broken", "0s", testStart.Add(-48*time.Hour), "", 1000)) + id, _ := body["statement_id"].(string) + + ts.clock = ts.clock.Add(time.Hour) + if _, polled := ts.do(t, http.MethodGet, alphaURL+"/api/2.0/sql/statements/"+id, ""); stmtState(polled) != statementPending { + t.Errorf("want PENDING forever, got %v", polled) + } + _, wh := ts.do(t, http.MethodGet, alphaURL+"/api/2.0/sql/warehouses/wh-broken", "") + health, _ := wh["health"].(map[string]any) + if wh["state"] != warehouseStopped || health["status"] != "FAILED" { + t.Errorf("want STOPPED with FAILED health, got %v", wh) + } + + code, cancel := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements/"+id+"/cancel", "") + if code != http.StatusOK || len(cancel) != 0 { + t.Errorf("cancel: want 200 {}, got %d %v", code, cancel) + } + if _, polled := ts.do(t, http.MethodGet, alphaURL+"/api/2.0/sql/statements/"+id, ""); stmtState(polled) != statementCanceled { + t.Errorf("want CANCELED after cancel, got %v", polled) + } +} + +func TestOnWaitTimeoutCancel(t *testing.T) { + ts := newTestServer(config{}) + req := strings.Replace(statementRequest(t, "wh-broken", "5s", testStart.Add(-48*time.Hour), "", 1000), + `"wait_timeout":"5s"`, `"wait_timeout":"5s","on_wait_timeout":"CANCEL"`, 1) + if _, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", req); stmtState(body) != statementCanceled { + t.Errorf("want CANCELED after wait_timeout with on_wait_timeout=CANCEL, got %v", body) + } +} + +func TestChunks(t *testing.T) { + ts := newTestServer(config{chunkRows: 10}) + _, body := ts.do(t, http.MethodPost, alphaURL+"/api/2.0/sql/statements", statementRequest(t, "wh-serverless", "10s", testStart.Add(-48*time.Hour), "", 1000)) + id, _ := body["statement_id"].(string) + manifest, _ := body["manifest"].(map[string]any) + if manifest["total_chunk_count"] != float64(3) || manifest["total_row_count"] != float64(22) { + t.Fatalf("want 3 chunks / 22 rows, got %v", manifest) + } + + all := eventIDs(t, body) + next, _ := body["result"].(map[string]any)["next_chunk_index"].(float64) + for next > 0 { + _, chunk := ts.do(t, http.MethodGet, fmt.Sprintf("%s/api/2.0/sql/statements/%s/result/chunks/%d", alphaURL, id, int(next)), "") + all = append(all, eventIDs(t, map[string]any{"result": chunk})...) + next, _ = chunk["next_chunk_index"].(float64) + } + if len(all) != 22 { + t.Errorf("want 22 rows across chunks, got %d", len(all)) + } + if code, _ := ts.do(t, http.MethodGet, fmt.Sprintf("%s/api/2.0/sql/statements/%s/result/chunks/3", alphaURL, id), ""); code != http.StatusBadRequest { + t.Errorf("out-of-range chunk: got %d", code) + } +} diff --git a/test-server/seeds.go b/test-server/seeds.go new file mode 100644 index 00000000..3daab451 --- /dev/null +++ b/test-server/seeds.go @@ -0,0 +1,153 @@ +package main + +import "time" + +// Seed IDs. DECISION: all made up; numeric IDs are 16 digits like real Databricks IDs. +const ( + wsAlphaID int64 = 7474645012345671 + wsBetaID int64 = 7474645012345672 + wsGammaID int64 = 8828000011112223 + + userAlice = "4410000000000001" + userBob = "4410000000000002" + userCarol = "4410000000000003" + userDave = "4410000000000004" + + groupDataEngineers = "5520000000000001" + groupAnalysts = "5520000000000002" + + spCIBot = "6630000000000001" + + // deletedPrincipal is named in an audit row but matches no user, group or service principal. + deletedPrincipal = "9990000000000001" +) + +// seedState builds the in-memory account. Audit row times are relative to start. +func seedState(start time.Time) *state { + st := &state{ + // DOC: deployment_name is the workspace hostname prefix; aws_region per workspace. + workspaces: []workspace{ + {ID: wsAlphaID, Name: "Alpha", DeploymentName: "ws-alpha", Region: "us-east-1"}, + {ID: wsBetaID, Name: "Beta", DeploymentName: "ws-beta", Region: "us-east-1"}, + {ID: wsGammaID, Name: "Gamma", DeploymentName: "ws-gamma", Region: "eu-west-1"}, + }, + users: map[string]scimUser{ + userAlice: {ID: userAlice, UserName: "alice@example.com", DisplayName: "Alice Anders", Active: true}, + userBob: {ID: userBob, UserName: "bob@example.com", DisplayName: "Bob Brown", Active: true}, + userCarol: {ID: userCarol, UserName: "carol@example.com", DisplayName: "Carol Chen", Active: false}, + userDave: {ID: userDave, UserName: "dave@example.com", DisplayName: "Dave Diaz", Active: true}, + }, + groups: map[string]scimGroup{ + groupDataEngineers: {ID: groupDataEngineers, DisplayName: "data-engineers"}, + groupAnalysts: {ID: groupAnalysts, DisplayName: "analysts"}, + }, + servicePrincipals: map[string]scimServicePrincipal{ + spCIBot: {ID: spCIBot, ApplicationID: "0d1c2b3a-0000-4000-8000-000000000001", DisplayName: "ci-bot", Active: true}, + }, + // DECISION: one running serverless warehouse, one stopped pro warehouse, one that never starts. + warehouses: map[string]*warehouse{ + "wh-serverless": { + ID: "wh-serverless", Name: "Serverless Starter Warehouse", DeploymentName: "ws-alpha", + WarehouseType: "PRO", Serverless: true, InitialState: warehouseRunning, + }, + "wh-pro": { + ID: "wh-pro", Name: "Pro Warehouse", DeploymentName: "ws-beta", + WarehouseType: "PRO", InitialState: warehouseStopped, + }, + "wh-broken": { + ID: "wh-broken", Name: "Broken Warehouse", DeploymentName: "ws-alpha", + WarehouseType: "PRO", InitialState: warehouseStopped, NeverStarts: true, + }, + }, + statements: map[string]*statement{}, + } + st.audit = seedAudit(start) + return st +} + +// seedAudit returns synthetic system.access.audit rows. +// DOC: request_params keys per action follow https://docs.databricks.com/aws/en/admin/account-settings/audit-logs, +// and account-level events have workspace_id 0. +// DECISION: IDs and times are made up. Rows the connector should read fall between 26 and 5 +// hours before start: older than its 4-hour lag window and inside an --event-feed-start-at +// of 2 days ago. Two extra rows sit outside that window on purpose. +func seedAudit(start time.Time) []auditRow { + at := func(h, m int) time.Time { + return start.Add(-time.Duration(h)*time.Hour - time.Duration(m)*time.Minute).UTC().Truncate(time.Millisecond) + } + user := func(endpoint, id, name string) map[string]string { + return map[string]string{"endpoint": endpoint, "targetUserId": id, "targetUserName": name} + } + membership := func(groupID, groupName, memberID, memberName string) map[string]string { + return map[string]string{ + "endpoint": "scim", "targetGroupId": groupID, "targetGroupName": groupName, + "targetUserId": memberID, "targetUserName": memberName, + } + } + tie := at(6, 0) + + return []auditRow{ + {EventID: "e0000001-0000-4000-8000-000000000001", EventTime: at(26, 0), ServiceName: "accounts", ActionName: "add", + RequestParams: user("scim", userDave, "dave@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000002", EventTime: at(25, 0), ServiceName: "accounts", ActionName: "activateUser", + RequestParams: user("scim", userBob, "bob@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000003", EventTime: at(24, 0), ServiceName: "accounts", ActionName: "deactivateUser", + RequestParams: user("scim", userCarol, "carol@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000004", EventTime: at(23, 0), ServiceName: "accounts", ActionName: "createGroup", + RequestParams: map[string]string{"endpoint": "scim", "targetGroupId": groupAnalysts, "targetGroupName": "analysts"}}, + {EventID: "e0000001-0000-4000-8000-000000000005", EventTime: at(22, 0), ServiceName: "accounts", ActionName: "addPrincipalToGroup", + RequestParams: membership(groupDataEngineers, "data-engineers", userAlice, "alice@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000006", EventTime: at(21, 0), ServiceName: "accounts", ActionName: "addPrincipalToGroup", + RequestParams: membership(groupDataEngineers, "data-engineers", groupAnalysts, "analysts")}, + {EventID: "e0000001-0000-4000-8000-000000000007", EventTime: at(20, 0), ServiceName: "accounts", ActionName: "addPrincipalsToGroup", + RequestParams: membership(groupAnalysts, "analysts", spCIBot, "0d1c2b3a-0000-4000-8000-000000000001")}, + {EventID: "e0000001-0000-4000-8000-000000000008", EventTime: at(19, 0), ServiceName: "accounts", ActionName: "removePrincipalFromGroup", + RequestParams: membership(groupDataEngineers, "data-engineers", userBob, "bob@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000009", EventTime: at(18, 0), ServiceName: "accounts", ActionName: "removePrincipalFromGroup", + RequestParams: membership(groupDataEngineers, "data-engineers", deletedPrincipal, "gone@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000010", EventTime: at(17, 0), ServiceName: "accounts", ActionName: "setAccountAdmin", + RequestParams: user("adminConsole", userAlice, "alice@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000011", EventTime: at(16, 0), WorkspaceID: wsAlphaID, ServiceName: "accounts", ActionName: "setAdmin", + RequestParams: user("adminConsole", userBob, "bob@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000012", EventTime: at(15, 0), WorkspaceID: wsAlphaID, ServiceName: "accounts", ActionName: "removeAdmin", + RequestParams: user("adminConsole", userBob, "bob@example.com")}, + // DOC: workspace-level createGroup has no targetGroupId. + {EventID: "e0000001-0000-4000-8000-000000000013", EventTime: at(14, 0), WorkspaceID: wsAlphaID, ServiceName: "accounts", ActionName: "createGroup", + RequestParams: user("scim", userAlice, "alice@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000014", EventTime: at(13, 0), WorkspaceID: wsBetaID, ServiceName: "accounts", ActionName: "delete", + RequestParams: user("scim", userCarol, "carol@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000015", EventTime: at(12, 0), ServiceName: "workspace", ActionName: "addPermissionAssignment", + RequestParams: map[string]string{"principal_id": userDave, "account_id": testAccountID, "workspace_id": "7474645012345671"}}, + // DOC: updatePermissionAssignment has no workspace_id. + {EventID: "e0000001-0000-4000-8000-000000000016", EventTime: at(11, 0), ServiceName: "workspace", ActionName: "updatePermissionAssignment", + RequestParams: map[string]string{"principal_id": userDave, "permissions": `["ADMIN"]`}}, + {EventID: "e0000001-0000-4000-8000-000000000017", EventTime: at(10, 0), WorkspaceID: wsBetaID, ServiceName: "workspace", ActionName: "deletePermissionAssignment", + RequestParams: map[string]string{"principal_id": userBob, "account_id": testAccountID, "workspace_id": "7474645012345672"}}, + // ws-gamma is in eu-west-1, so this row is invisible from a us-east-1 warehouse. + {EventID: "e0000001-0000-4000-8000-000000000018", EventTime: at(9, 0), WorkspaceID: wsGammaID, ServiceName: "accounts", ActionName: "add", + RequestParams: user("scim", userAlice, "alice@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000019", EventTime: at(8, 0), WorkspaceID: wsAlphaID, ServiceName: "accounts", ActionName: "updateUser", + RequestParams: user("scim", userAlice, "alice@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000020", EventTime: at(7, 0), WorkspaceID: wsBetaID, ServiceName: "accounts", ActionName: "updateGroup", + RequestParams: map[string]string{"endpoint": "scim", "targetGroupId": groupAnalysts, "targetGroupName": "analysts"}}, + // Two rows with the same event_time, to exercise the (event_time, event_id) ordering. + {EventID: "e0000001-0000-4000-8000-000000000021", EventTime: tie, ServiceName: "accounts", ActionName: "removeGroup", + RequestParams: map[string]string{"endpoint": "scim", "targetGroupId": groupDataEngineers, "targetGroupName": "data-engineers"}}, + {EventID: "e0000001-0000-4000-8000-000000000022", EventTime: tie, ServiceName: "accounts", ActionName: "deactivateUser", + RequestParams: user("scim", userDave, "dave@example.com")}, + {EventID: "e0000001-0000-4000-8000-000000000023", EventTime: at(5, 30), WorkspaceID: wsAlphaID, ServiceName: "accounts", ActionName: "changeDatabricksWorkspaceAcl", + RequestParams: map[string]string{"shardName": "ws-alpha", "targetUserId": userCarol, "resourceId": "7474645012345671", "aclPermissionSet": "workspace-access"}}, + // Not an action the connector asks for. + {EventID: "e0000001-0000-4000-8000-000000000024", EventTime: at(5, 0), WorkspaceID: wsAlphaID, ServiceName: "clusters", ActionName: "create", + RequestParams: map[string]string{"cluster_name": "etl"}}, + // Outside the window: newer than the connector's 4-hour lag cutoff. + {EventID: "e0000001-0000-4000-8000-000000000025", EventTime: at(2, 0), ServiceName: "accounts", ActionName: "add", + RequestParams: user("scim", userBob, "bob@example.com")}, + // Outside the window: older than an --event-feed-start-at of 2 days ago. + {EventID: "e0000001-0000-4000-8000-000000000026", EventTime: at(72, 0), ServiceName: "accounts", ActionName: "add", + RequestParams: user("scim", userCarol, "carol@example.com")}, + // A request Databricks rejected: alice stays in data-engineers, so it must not become a revoke. + {EventID: "e0000001-0000-4000-8000-000000000027", EventTime: at(18, 30), ServiceName: "accounts", ActionName: "removePrincipalFromGroup", + RequestParams: membership(groupDataEngineers, "data-engineers", userAlice, "alice@example.com"), StatusCode: 403}, + } +} diff --git a/test-server/state.go b/test-server/state.go new file mode 100644 index 00000000..c0965637 --- /dev/null +++ b/test-server/state.go @@ -0,0 +1,189 @@ +package main + +import ( + "context" + "net" + "net/http" + "strings" + "sync" + "time" +) + +// DECISION: hardcoded test credentials. +const ( + testAccountID = "test-account" + testClientID = "test-client" + testClientSecret = "test-secret" + testAccessToken = "test-access-token" +) + +type workspace struct { + ID int64 + Name string + DeploymentName string + Region string +} + +type scimUser struct { + ID string + UserName string + DisplayName string + Active bool +} + +type scimGroup struct { + ID string + DisplayName string +} + +type scimServicePrincipal struct { + ID string + ApplicationID string + DisplayName string + Active bool +} + +type warehouse struct { + ID string + Name string + DeploymentName string // workspace hosting the warehouse + WarehouseType string + Serverless bool + InitialState string + // NeverStarts makes start attempts fail: the warehouse stays STOPPED with a FAILED health status. + NeverStarts bool + + startRequestedAt time.Time +} + +type auditRow struct { + EventID string + EventTime time.Time + WorkspaceID int64 + ServiceName string + ActionName string + RequestParams map[string]string + // StatusCode is response.status_code. Zero means 200; seedAudit fills it in. + StatusCode int +} + +// state is the in-memory account, seeded at startup (see seeds.go) and reset on every start. +type state struct { + workspaces []workspace + users map[string]scimUser + groups map[string]scimGroup + servicePrincipals map[string]scimServicePrincipal + warehouses map[string]*warehouse + audit []auditRow + statements map[string]*statement + nextStatement int +} + +func (st *state) workspaceByDeployment(name string) *workspace { + for i := range st.workspaces { + if st.workspaces[i].DeploymentName == name { + return &st.workspaces[i] + } + } + return nil +} + +func (st *state) workspaceByID(id int64) *workspace { + for i := range st.workspaces { + if st.workspaces[i].ID == id { + return &st.workspaces[i] + } + } + return nil +} + +type server struct { + cfg config + start time.Time + now func() time.Time + + mu sync.Mutex + st *state + + account *http.ServeMux + workspace *http.ServeMux +} + +func newServer(cfg config, start time.Time) *server { + s := &server{ + cfg: cfg, + start: start, + now: time.Now, + st: seedState(start), + } + s.account = s.accountRoutes() + s.workspace = s.workspaceRoutes() + return s +} + +type workspaceKey struct{} + +func requestWorkspace(r *http.Request) *workspace { + ws, _ := r.Context().Value(workspaceKey{}).(*workspace) + return ws +} + +// ServeHTTP routes by Host header (DECISION): localhost is the account host, and +// .localhost is a workspace host, mirroring .. +func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // DECISION: local readiness check on every host; not a Databricks endpoint. + if r.URL.Path == "/health" && r.Method == http.MethodGet { + writeJSON(w, http.StatusOK, map[string]string{"status": "ok"}) + return + } + + host := r.Host + if h, _, err := net.SplitHostPort(r.Host); err == nil { + host = h + } + host = strings.ToLower(strings.TrimSuffix(host, ".")) + + switch { + case host == "localhost" || host == "127.0.0.1" || host == "::1": + s.account.ServeHTTP(w, r) + case strings.HasSuffix(host, ".localhost"): + deployment := strings.TrimSuffix(host, ".localhost") + s.mu.Lock() + ws := s.st.workspaceByDeployment(deployment) + s.mu.Unlock() + if ws == nil { + // DECISION: a real unknown deployment name doesn't resolve in DNS at all. + writeError(w, http.StatusNotFound, "ENDPOINT_NOT_FOUND", "test-server: no workspace with deployment name "+deployment) + return + } + s.workspace.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), workspaceKey{}, ws))) + default: + writeError(w, http.StatusNotFound, "ENDPOINT_NOT_FOUND", "test-server: unknown host "+host) + } +} + +// requireBearer enforces the access token on every API call except the token endpoint. +// DOC: https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m (Authorization: Bearer ). +// DOC: error body {error_code, message}, https://docs.databricks.com/api/workspace/introduction. +func requireBearer(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + if !ok || token != testAccessToken { + writeError(w, http.StatusUnauthorized, "UNAUTHENTICATED", "Credential was not sent or was of an unsupported type for this API.") + return + } + next(w, r) + } +} + +// requireAccount rejects account API paths for any account other than testAccountID. +// ASSUMPTION: the exact status and code for another account's ID are not documented. +func requireAccount(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.PathValue("account_id") != testAccountID { + writeError(w, http.StatusNotFound, "RESOURCE_DOES_NOT_EXIST", "Account "+r.PathValue("account_id")+" does not exist.") + return + } + next(w, r) + } +} diff --git a/test-server/statements.go b/test-server/statements.go new file mode 100644 index 00000000..41abaa06 --- /dev/null +++ b/test-server/statements.go @@ -0,0 +1,649 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "regexp" + "sort" + "strconv" + "strings" + "time" +) + +// Warehouse states. DOC: https://docs.databricks.com/api/workspace/warehouses/get +const ( + warehouseStarting = "STARTING" + warehouseRunning = "RUNNING" + warehouseStopped = "STOPPED" +) + +// Statement states. DOC: https://docs.databricks.com/api/workspace/statementexecution/getstatement +const ( + statementPending = "PENDING" + statementSucceeded = "SUCCEEDED" + statementFailed = "FAILED" + statementCanceled = "CANCELED" +) + +// warehouseState returns wh's state now. Callers hold s.mu. +// ASSUMPTION: submitting a statement starts a stopped warehouse, which is RUNNING after +// --warehouse-start-delay. DECISION: a NeverStarts warehouse stays STOPPED. +func (s *server) warehouseState(wh *warehouse) string { + if wh.InitialState != warehouseStopped { + return wh.InitialState + } + if wh.startRequestedAt.IsZero() || wh.NeverStarts { + return warehouseStopped + } + if s.now().Sub(wh.startRequestedAt) >= s.cfg.warehouseStartDelay { + return warehouseRunning + } + return warehouseStarting +} + +type column struct { + Name string `json:"name"` + TypeName string `json:"type_name"` + TypeText string `json:"type_text"` + Position int `json:"position"` +} + +type statement struct { + ID string + DeploymentName string + WarehouseID string + State string + ErrorCode string + ErrorMessage string + + // The outcome, decided at submit time and revealed once the warehouse is running. + outcomeState string + outcomeCode string + outcomeMessage string + columns []column + rows [][]*string +} + +// refresh moves a PENDING statement to its outcome once its warehouse is running. +// DOC: a statement on a warehouse that isn't running stays PENDING, waiting for the warehouse. +// DECISION: statements go straight from PENDING to SUCCEEDED/FAILED (no visible RUNNING). +func (s *server) refresh(stmt *statement) { + if stmt.State != statementPending { + return + } + if s.warehouseState(s.st.warehouses[stmt.WarehouseID]) != warehouseRunning { + return + } + stmt.State = stmt.outcomeState + stmt.ErrorCode = stmt.outcomeCode + stmt.ErrorMessage = stmt.outcomeMessage +} + +func isTerminal(state string) bool { + return state != statementPending +} + +type statementParameter struct { + Name string `json:"name"` + Value *string `json:"value"` + Type string `json:"type"` +} + +type executeRequest struct { + WarehouseID string `json:"warehouse_id"` + Statement string `json:"statement"` + WaitTimeout *string `json:"wait_timeout"` + OnWaitTimeout string `json:"on_wait_timeout"` + Format string `json:"format"` + Disposition string `json:"disposition"` + Parameters []statementParameter `json:"parameters"` +} + +var waitTimeoutRe = regexp.MustCompile(`^(\d+)s$`) + +// parseWaitTimeout validates wait_timeout. +// DOC: 0s, or between 5s and 50s; the default is 10s. +func parseWaitTimeout(v *string) (time.Duration, bool) { + if v == nil { + return 10 * time.Second, true + } + m := waitTimeoutRe.FindStringSubmatch(*v) + if m == nil { + return 0, false + } + n, err := strconv.Atoi(m[1]) + if err != nil || (n != 0 && (n < 5 || n > 50)) { + return 0, false + } + return time.Duration(n) * time.Second, true +} + +// handleExecuteStatement submits a statement. +// DOC: if it finishes within wait_timeout the response has the result; otherwise it has the +// statement ID with PENDING or RUNNING, and on_wait_timeout=CANCEL cancels it instead. +func (s *server) handleExecuteStatement(w http.ResponseWriter, r *http.Request) { + ws := requestWorkspace(r) + + var req executeRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeError(w, http.StatusBadRequest, "MALFORMED_REQUEST", "Could not parse request body: "+err.Error()) + return + } + + wait, ok := parseWaitTimeout(req.WaitTimeout) + if !ok { + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", + "wait_timeout must be 0 seconds (disables wait), or between 5 seconds and 50 seconds.") + return + } + switch req.OnWaitTimeout { + case "", "CONTINUE", "CANCEL": + default: + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", "on_wait_timeout must be CONTINUE or CANCEL.") + return + } + // DECISION: only the JSON_ARRAY format and INLINE disposition are implemented. + if req.Format != "" && req.Format != "JSON_ARRAY" { + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", "test-server: only format JSON_ARRAY is supported") + return + } + if req.Disposition != "" && req.Disposition != "INLINE" { + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", "test-server: only disposition INLINE is supported") + return + } + // DOC: parameters are named (:name) markers. ASSUMPTION: the status and code for a + // positional (unnamed) parameter. + for _, p := range req.Parameters { + if p.Name == "" { + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", "Positional parameters are not supported; use named parameter markers.") + return + } + } + + s.mu.Lock() + wh, ok := s.st.warehouses[req.WarehouseID] + if !ok || wh.DeploymentName != ws.DeploymentName { + s.mu.Unlock() + // DOC: an unknown warehouse_id is an error. ASSUMPTION: its status and code. + writeError(w, http.StatusNotFound, "RESOURCE_DOES_NOT_EXIST", "Warehouse "+req.WarehouseID+" does not exist.") + return + } + if wh.InitialState == warehouseStopped && wh.startRequestedAt.IsZero() { + wh.startRequestedAt = s.now() + } + + s.st.nextStatement++ + stmt := &statement{ + ID: fmt.Sprintf("01f00000-0000-4000-8000-%012d", s.st.nextStatement), + DeploymentName: ws.DeploymentName, + WarehouseID: wh.ID, + State: statementPending, + } + s.st.statements[stmt.ID] = stmt + + region := "" + if hostWS := s.st.workspaceByDeployment(wh.DeploymentName); hostWS != nil { + region = hostWS.Region + } + cols, rows, err := s.st.runAuditQuery(req.Statement, req.Parameters, region) + if err != nil { + stmt.outcomeState = statementFailed + stmt.outcomeCode = err.code + stmt.outcomeMessage = err.message + } else { + stmt.outcomeState = statementSucceeded + stmt.columns = cols + stmt.rows = rows + } + s.refresh(stmt) + s.mu.Unlock() + + deadline := time.NewTimer(wait) + defer deadline.Stop() + tick := time.NewTicker(20 * time.Millisecond) + defer tick.Stop() + for { + s.mu.Lock() + s.refresh(stmt) + if isTerminal(stmt.State) { + body := s.statementBody(stmt) + s.mu.Unlock() + writeJSON(w, http.StatusOK, body) + return + } + s.mu.Unlock() + + select { + case <-r.Context().Done(): + return + case <-deadline.C: + s.mu.Lock() + if req.OnWaitTimeout == "CANCEL" { + stmt.State = statementCanceled + } + body := s.statementBody(stmt) + s.mu.Unlock() + writeJSON(w, http.StatusOK, body) + return + case <-tick.C: + } + } +} + +// lookupStatement finds a statement submitted in the request's workspace. Callers hold s.mu. +// ASSUMPTION: an unknown statement ID is 404 RESOURCE_DOES_NOT_EXIST. +func (s *server) lookupStatement(w http.ResponseWriter, r *http.Request) *statement { + stmt, ok := s.st.statements[r.PathValue("id")] + if !ok || stmt.DeploymentName != requestWorkspace(r).DeploymentName { + writeError(w, http.StatusNotFound, "RESOURCE_DOES_NOT_EXIST", "Statement "+r.PathValue("id")+" does not exist.") + return nil + } + return stmt +} + +// handleGetStatement returns a statement's status. +// DOC: once SUCCEEDED it includes the manifest and the first chunk; terminal states are HTTP 200. +func (s *server) handleGetStatement(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + + stmt := s.lookupStatement(w, r) + if stmt == nil { + return + } + s.refresh(stmt) + writeJSON(w, http.StatusOK, s.statementBody(stmt)) +} + +// handleCancelStatement requests cancellation. +// DOC: returns {}; the caller polls the statement to see CANCELED. +func (s *server) handleCancelStatement(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + + stmt := s.lookupStatement(w, r) + if stmt == nil { + return + } + s.refresh(stmt) + if !isTerminal(stmt.State) { + stmt.State = statementCanceled + } + writeJSON(w, http.StatusOK, map[string]any{}) +} + +// handleGetResultChunk returns one result chunk of a SUCCEEDED statement. +// DOC: same shape as the result object, with next_chunk_index absent on the last chunk. +// ASSUMPTION: the status and code for an out-of-range chunk or a statement without a result. +func (s *server) handleGetResultChunk(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + defer s.mu.Unlock() + + stmt := s.lookupStatement(w, r) + if stmt == nil { + return + } + s.refresh(stmt) + if stmt.State != statementSucceeded { + writeError(w, http.StatusBadRequest, "INVALID_STATE", "Statement "+stmt.ID+" has no result: state is "+stmt.State+".") + return + } + n, ok := parseChunkIndex(r.PathValue("n")) + if !ok || n >= s.chunkCount(stmt) { + writeError(w, http.StatusBadRequest, "INVALID_PARAMETER_VALUE", "Chunk index "+r.PathValue("n")+" is out of range.") + return + } + writeJSON(w, http.StatusOK, s.chunkBody(stmt, n)) +} + +// chunkCount is how many chunks stmt's result has. DECISION: one chunk unless --chunk-rows is set. +// ASSUMPTION: an empty result is reported as a single empty chunk. +func (s *server) chunkCount(stmt *statement) int { + if s.cfg.chunkRows <= 0 || len(stmt.rows) == 0 { + return 1 + } + return (len(stmt.rows) + s.cfg.chunkRows - 1) / s.cfg.chunkRows +} + +func (s *server) chunkBounds(stmt *statement, n int) (int, int) { + if s.cfg.chunkRows <= 0 { + return 0, len(stmt.rows) + } + start := n * s.cfg.chunkRows + return start, min(start+s.cfg.chunkRows, len(stmt.rows)) +} + +// chunkBody renders result chunk n. DOC: data_array values are strings and nulls are JSON null. +func (s *server) chunkBody(stmt *statement, n int) map[string]any { + start, end := s.chunkBounds(stmt, n) + body := map[string]any{ + "chunk_index": n, + "row_offset": start, + "row_count": end - start, + } + if end > start { + body["data_array"] = stmt.rows[start:end] + } + if n+1 < s.chunkCount(stmt) { + body["next_chunk_index"] = n + 1 + body["next_chunk_internal_link"] = fmt.Sprintf("/api/2.0/sql/statements/%s/result/chunks/%d", stmt.ID, n+1) + } + return body +} + +// statementBody renders a statement as the Execute/Get responses do. Callers hold s.mu. +func (s *server) statementBody(stmt *statement) map[string]any { + status := map[string]any{"state": stmt.State} + if stmt.ErrorMessage != "" { + status["error"] = map[string]string{"error_code": stmt.ErrorCode, "message": stmt.ErrorMessage} + } + body := map[string]any{"statement_id": stmt.ID, "status": status} + if stmt.State != statementSucceeded { + return body + } + + count := s.chunkCount(stmt) + chunks := make([]map[string]any, 0, count) + for n := range count { + start, end := s.chunkBounds(stmt, n) + chunks = append(chunks, map[string]any{"chunk_index": n, "row_offset": start, "row_count": end - start}) + } + body["manifest"] = map[string]any{ + "format": "JSON_ARRAY", + "schema": map[string]any{ + "column_count": len(stmt.columns), + "columns": stmt.columns, + }, + "total_chunk_count": count, + "chunks": chunks, + "total_row_count": len(stmt.rows), + "truncated": false, + } + body["result"] = s.chunkBody(stmt, 0) + return body +} + +// SQL handling (DECISION): the server doesn't run SQL. It recognizes the shape of the +// connector's query against system.access.audit and evaluates just that. +var ( + auditFromRe = regexp.MustCompile(`(?is)^\s*SELECT\s+(.+?)\s+FROM\s+system\.access\.audit\b`) + paramMarkerRe = regexp.MustCompile(`(?:^|[^:\w]):([A-Za-z_]\w*)`) + eventDateRe = regexp.MustCompile(`(?i)\bevent_date\s*>=\s*:(\w+)`) + afterRe = regexp.MustCompile( + `(?i)\(\s*event_time\s*>\s*:(\w+)\s+OR\s*\(\s*event_time\s*=\s*:(\w+)\s+AND\s+event_id\s*>\s*:(\w+)\s*\)\s*\)`) + cutoffRe = regexp.MustCompile(`(?i)\bevent_time\s*<=\s*:(\w+)`) + serviceListRe = regexp.MustCompile(`(?i)\bservice_name\s+IN\s*\(([^)]*)\)`) + actionListRe = regexp.MustCompile(`(?i)\baction_name\s+IN\s*\(([^)]*)\)`) + statusCodeRe = regexp.MustCompile(`(?i)\bresponse\.status_code\s*=\s*(\d+)\b`) + orderByRe = regexp.MustCompile(`(?i)\bORDER\s+BY\s+event_time(\s+ASC)?\s*,\s*event_id(\s+ASC)?\b`) + limitRe = regexp.MustCompile(`(?i)\bLIMIT\s+(\d+)\s*;?\s*$`) +) + +// auditColumns are the documented system.access.audit columns this server serves. +// DOC: https://docs.databricks.com/aws/en/admin/system-tables/audit-logs +// DOC: type_name values, https://docs.databricks.com/api/workspace/statementexecution/executestatement +var auditColumns = map[string]column{ + "event_id": {Name: "event_id", TypeName: "STRING", TypeText: "STRING"}, + "event_time": {Name: "event_time", TypeName: "TIMESTAMP", TypeText: "TIMESTAMP"}, + "event_date": {Name: "event_date", TypeName: "DATE", TypeText: "DATE"}, + "workspace_id": {Name: "workspace_id", TypeName: "LONG", TypeText: "BIGINT"}, + "service_name": {Name: "service_name", TypeName: "STRING", TypeText: "STRING"}, + "action_name": {Name: "action_name", TypeName: "STRING", TypeText: "STRING"}, + "request_params": {Name: "request_params", TypeName: "MAP", TypeText: "MAP"}, +} + +type sqlError struct { + code string + message string +} + +func unsupported(detail string) *sqlError { + return &sqlError{code: "BAD_REQUEST", message: "test-server: unsupported statement: " + detail} +} + +type boundParam struct { + typ string + value string + time time.Time +} + +// bindParameters binds typed named parameters. +// DOC: named markers with an optional type; the default type is STRING. +// ASSUMPTION: the accepted TIMESTAMP and DATE literal formats. +func bindParameters(params []statementParameter) (map[string]boundParam, *sqlError) { + bound := make(map[string]boundParam, len(params)) + for _, p := range params { + typ := strings.ToUpper(p.Type) + if typ == "" { + typ = "STRING" + } + if p.Value == nil { + return nil, &sqlError{code: "BAD_REQUEST", message: "test-server: NULL parameter values are not supported"} + } + bp := boundParam{typ: typ, value: *p.Value} + switch typ { + case "STRING": + case "TIMESTAMP": + t, err := time.Parse(time.RFC3339Nano, bp.value) + if err != nil { + t, err = time.Parse("2006-01-02 15:04:05.999999", bp.value) + } + if err != nil { + return nil, &sqlError{code: "INVALID_PARAMETER_VALUE", message: fmt.Sprintf("Cannot parse %q as TIMESTAMP for parameter %s.", bp.value, p.Name)} + } + bp.time = t.UTC() + case "DATE": + t, err := time.Parse(time.DateOnly, bp.value) + if err != nil { + return nil, &sqlError{code: "INVALID_PARAMETER_VALUE", message: fmt.Sprintf("Cannot parse %q as DATE for parameter %s.", bp.value, p.Name)} + } + bp.time = t + default: + return nil, &sqlError{code: "BAD_REQUEST", message: "test-server: unsupported parameter type " + typ} + } + bound[p.Name] = bp + } + return bound, nil +} + +func parseInList(list string) []string { + var values []string + for _, v := range strings.Split(list, ",") { + values = append(values, strings.Trim(strings.TrimSpace(v), "'")) + } + return values +} + +func contains(values []string, v string) bool { + for _, x := range values { + if x == v { + return true + } + } + return false +} + +// timeParam returns a bound TIMESTAMP/DATE parameter. Callers check names against bound first. +func timeParam(bound map[string]boundParam, name string, want string) (time.Time, *sqlError) { + p := bound[name] + if p.typ != want { + return time.Time{}, unsupported(fmt.Sprintf("parameter %s must be bound with type %s", name, want)) + } + return p.time, nil +} + +// runAuditQuery evaluates the connector's audit query against the seed rows visible from a +// warehouse in region. Callers hold s.mu. +// DOC: workspace-level events are only visible from the workspace's region ("Most audit logs +// are only available in the region of the workspace"); account-level events (workspace_id 0) +// are visible from every region. +func (st *state) runAuditQuery(sql string, params []statementParameter, region string) ([]column, [][]*string, *sqlError) { + m := auditFromRe.FindStringSubmatch(sql) + if m == nil { + return nil, nil, unsupported("only SELECT ... FROM system.access.audit is supported") + } + + var cols []column + for i, name := range strings.Split(m[1], ",") { + col, ok := auditColumns[strings.ToLower(strings.TrimSpace(name))] + if !ok { + return nil, nil, unsupported(fmt.Sprintf("column %q", strings.TrimSpace(name))) + } + col.Position = i + cols = append(cols, col) + } + + bound, bindErr := bindParameters(params) + if bindErr != nil { + return nil, nil, bindErr + } + // ASSUMPTION: the error for a marker with no bound parameter (UNBOUND_SQL_PARAMETER). + for _, mm := range paramMarkerRe.FindAllStringSubmatch(sql, -1) { + if _, ok := bound[mm[1]]; !ok { + return nil, nil, &sqlError{code: "BAD_REQUEST", message: fmt.Sprintf("[UNBOUND_SQL_PARAMETER] Found the unbound parameter: %s.", mm[1])} + } + } + + if !orderByRe.MatchString(sql) { + return nil, nil, unsupported("ORDER BY event_time ASC, event_id ASC is required") + } + + var ( + startDate, startTime, cutoff time.Time + startAfterID string + hasStartDate, hasAfter bool + hasCutoff bool + services, actions []string + statusCode = -1 + limit = -1 + err *sqlError + ) + if mm := eventDateRe.FindStringSubmatch(sql); mm != nil { + if startDate, err = timeParam(bound, mm[1], "DATE"); err != nil { + return nil, nil, err + } + hasStartDate = true + } + if mm := afterRe.FindStringSubmatch(sql); mm != nil { + if mm[1] != mm[2] { + return nil, nil, unsupported("the two event_time comparisons must use the same parameter") + } + if startTime, err = timeParam(bound, mm[1], "TIMESTAMP"); err != nil { + return nil, nil, err + } + startAfterID = bound[mm[3]].value + hasAfter = true + } + if mm := cutoffRe.FindStringSubmatch(sql); mm != nil { + if cutoff, err = timeParam(bound, mm[1], "TIMESTAMP"); err != nil { + return nil, nil, err + } + hasCutoff = true + } + if mm := serviceListRe.FindStringSubmatch(sql); mm != nil { + services = parseInList(mm[1]) + } + if mm := actionListRe.FindStringSubmatch(sql); mm != nil { + actions = parseInList(mm[1]) + } + if mm := statusCodeRe.FindStringSubmatch(sql); mm != nil { + statusCode, _ = strconv.Atoi(mm[1]) + } + if mm := limitRe.FindStringSubmatch(sql); mm != nil { + limit, _ = strconv.Atoi(mm[1]) + } + + matched := make([]auditRow, 0, len(st.audit)) + for _, row := range st.audit { + if row.WorkspaceID != 0 { + ws := st.workspaceByID(row.WorkspaceID) + if ws == nil || ws.Region != region { + continue + } + } + eventTime := row.EventTime.UTC() + eventDate := time.Date(eventTime.Year(), eventTime.Month(), eventTime.Day(), 0, 0, 0, 0, time.UTC) + if hasStartDate && eventDate.Before(startDate) { + continue + } + afterCursor := eventTime.After(startTime) || (eventTime.Equal(startTime) && row.EventID > startAfterID) + if hasAfter && !afterCursor { + continue + } + if hasCutoff && eventTime.After(cutoff) { + continue + } + if services != nil && !contains(services, row.ServiceName) { + continue + } + if actions != nil && !contains(actions, row.ActionName) { + continue + } + if statusCode >= 0 && row.statusCode() != statusCode { + continue + } + matched = append(matched, row) + } + + sort.Slice(matched, func(i, j int) bool { + if !matched[i].EventTime.Equal(matched[j].EventTime) { + return matched[i].EventTime.Before(matched[j].EventTime) + } + return matched[i].EventID < matched[j].EventID + }) + if limit >= 0 && len(matched) > limit { + matched = matched[:limit] + } + + rows := make([][]*string, 0, len(matched)) + for _, row := range matched { + values := make([]*string, len(cols)) + for i, col := range cols { + values[i] = formatValue(row, col.Name) + } + rows = append(rows, values) + } + return cols, rows, nil +} + +// statusCode is the row's response.status_code, where an unset value means 200. +func (row auditRow) statusCode() int { + if row.StatusCode == 0 { + return 200 + } + return row.StatusCode +} + +// formatValue renders a column value as JSON_ARRAY does. +// ASSUMPTION: TIMESTAMP as ISO 8601 UTC with milliseconds, DATE as yyyy-mm-dd, and MAP as a +// JSON object string. +func formatValue(row auditRow, name string) *string { + var v string + switch name { + case "event_id": + v = row.EventID + case "event_time": + v = row.EventTime.UTC().Format("2006-01-02T15:04:05.000Z") + case "event_date": + v = row.EventTime.UTC().Format(time.DateOnly) + case "workspace_id": + v = strconv.FormatInt(row.WorkspaceID, 10) + case "service_name": + v = row.ServiceName + case "action_name": + v = row.ActionName + case "request_params": + if row.RequestParams == nil { + return nil + } + b, err := json.Marshal(row.RequestParams) + if err != nil { + return nil + } + v = string(b) + default: + return nil + } + return &v +} diff --git a/test-server/testdata/expected-events.jsonl b/test-server/testdata/expected-events.jsonl new file mode 100644 index 00000000..0bdf0411 --- /dev/null +++ b/test-server/testdata/expected-events.jsonl @@ -0,0 +1,21 @@ +{"id":"e0000001-0000-4000-8000-000000000005/0","createGrantEvent":{"entitlement":{"resource":{"id":{"resourceType":"group","resource":"account/test-account/group/5520000000000001"},"parentResourceId":{"resourceType":"account","resource":"test-account"}},"id":"group:account/test-account/group/5520000000000001:member","displayName":"member","purpose":"PURPOSE_VALUE_ASSIGNMENT","slug":"member"},"principal":{"id":{"resourceType":"user","resource":"4410000000000001"}}}} +{"id":"e0000001-0000-4000-8000-000000000006/0","createGrantEvent":{"entitlement":{"resource":{"id":{"resourceType":"group","resource":"account/test-account/group/5520000000000001"},"parentResourceId":{"resourceType":"account","resource":"test-account"}},"id":"group:account/test-account/group/5520000000000001:member","displayName":"member","purpose":"PURPOSE_VALUE_ASSIGNMENT","slug":"member"},"principal":{"id":{"resourceType":"group","resource":"account/test-account/group/5520000000000002"}}}} +{"id":"e0000001-0000-4000-8000-000000000007/0","createGrantEvent":{"entitlement":{"resource":{"id":{"resourceType":"group","resource":"account/test-account/group/5520000000000002"},"parentResourceId":{"resourceType":"account","resource":"test-account"}},"id":"group:account/test-account/group/5520000000000002:member","displayName":"member","purpose":"PURPOSE_VALUE_ASSIGNMENT","slug":"member"},"principal":{"id":{"resourceType":"service_principal","resource":"6630000000000001"}}}} +{"id":"e0000001-0000-4000-8000-000000000008/0","createRevokeEvent":{"entitlement":{"resource":{"id":{"resourceType":"group","resource":"account/test-account/group/5520000000000001"},"parentResourceId":{"resourceType":"account","resource":"test-account"}},"id":"group:account/test-account/group/5520000000000001:member","displayName":"member","purpose":"PURPOSE_VALUE_ASSIGNMENT","slug":"member"},"principal":{"id":{"resourceType":"user","resource":"4410000000000002"}}}} +{"id":"e0000001-0000-4000-8000-000000000011/1","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"account_admin"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000012/0","resourceChangeEvent":{"resourceId":{"resourceType":"user","resource":"4410000000000002"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000003/0","resourceChangeEvent":{"resourceId":{"resourceType":"user","resource":"4410000000000003"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000017/0","resourceChangeEvent":{"resourceId":{"resourceType":"workspace","resource":"ws-beta"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000019/0","resourceChangeEvent":{"resourceId":{"resourceType":"user","resource":"4410000000000001"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000019/2","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-alpha:databricks-sql-access"},"parentResourceId":{"resourceType":"workspace","resource":"ws-alpha"}}} +{"id":"e0000001-0000-4000-8000-000000000019/3","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-alpha:allow-cluster-create"},"parentResourceId":{"resourceType":"workspace","resource":"ws-alpha"}}} +{"id":"e0000001-0000-4000-8000-000000000019/4","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-alpha:allow-instance-pool-create"},"parentResourceId":{"resourceType":"workspace","resource":"ws-alpha"}}} +{"id":"e0000001-0000-4000-8000-000000000020/0","resourceChangeEvent":{"resourceId":{"resourceType":"group","resource":"account/test-account/group/5520000000000002"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000020/1","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-beta:workspace-access"},"parentResourceId":{"resourceType":"workspace","resource":"ws-beta"}}} +{"id":"e0000001-0000-4000-8000-000000000020/2","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-beta:databricks-sql-access"},"parentResourceId":{"resourceType":"workspace","resource":"ws-beta"}}} +{"id":"e0000001-0000-4000-8000-000000000020/3","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-beta:allow-cluster-create"},"parentResourceId":{"resourceType":"workspace","resource":"ws-beta"}}} +{"id":"e0000001-0000-4000-8000-000000000020/4","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-beta:allow-instance-pool-create"},"parentResourceId":{"resourceType":"workspace","resource":"ws-beta"}}} +{"id":"e0000001-0000-4000-8000-000000000021/0","resourceChangeEvent":{"resourceId":{"resourceType":"group","resource":"account/test-account/group/5520000000000001"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000022/0","resourceChangeEvent":{"resourceId":{"resourceType":"user","resource":"4410000000000004"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000023/0","resourceChangeEvent":{"resourceId":{"resourceType":"workspace","resource":"ws-alpha"},"parentResourceId":{"resourceType":"account","resource":"test-account"}}} +{"id":"e0000001-0000-4000-8000-000000000023/1","resourceChangeEvent":{"resourceId":{"resourceType":"role","resource":"ws-alpha:workspace-access"},"parentResourceId":{"resourceType":"workspace","resource":"ws-alpha"}}}