diff --git a/Dockerfile.test b/Dockerfile.test index 5302b52..9ae8dc4 100644 --- a/Dockerfile.test +++ b/Dockerfile.test @@ -37,6 +37,36 @@ RUN curl -fsSL -o /tmp/databricks.zip \ rm /tmp/databricks.zip && \ databricks --version +# Terraform plus a local mirror of the Databricks provider, for +# tests/terraform/test_terraform_conformance.py. Both are pinned: the conformance test +# is only meaningful if it keeps testing the same provider, and a floating version would +# turn an upstream release into a mysterious CI failure. +# +# `terraform init` normally reaches registry.terraform.io. Warming the plugin cache here +# — where the build already has network — lets the test run `init -plugin-dir` against a +# local mirror instead, so the suite needs no network for this. +ARG TERRAFORM_VERSION=1.16.2 +ARG DATABRICKS_PROVIDER_VERSION=1.132.0 +# Deliberately NOT TF_PLUGIN_CACHE_DIR at runtime: the test passes this directory to +# `terraform init -plugin-dir`, and if it were also the plugin cache, terraform would try +# to install the provider from the directory into itself and fail. The cache variable is +# set only for the warm-up below, which is what populates the mirror. +ENV MINILAKE_TF_PROVIDER_MIRROR=/opt/tf-providers +RUN curl -fsSL -o /tmp/terraform.zip \ + "https://releases.hashicorp.com/terraform/${TERRAFORM_VERSION}/terraform_${TERRAFORM_VERSION}_linux_amd64.zip" && \ + python -c "import zipfile; zipfile.ZipFile('/tmp/terraform.zip').extract('terraform', '/usr/local/bin')" && \ + chmod 755 /usr/local/bin/terraform && \ + rm /tmp/terraform.zip && \ + terraform version && \ + mkdir -p "$MINILAKE_TF_PROVIDER_MIRROR" /tmp/tf-warmup && \ + printf 'terraform {\n required_providers {\n databricks = {\n source = "databricks/databricks"\n version = "%s"\n }\n }\n}\n' \ + "${DATABRICKS_PROVIDER_VERSION}" > /tmp/tf-warmup/main.tf && \ + cd /tmp/tf-warmup && \ + TF_PLUGIN_CACHE_DIR="$MINILAKE_TF_PROVIDER_MIRROR" terraform init -input=false -no-color > /dev/null && \ + rm -rf /tmp/tf-warmup && \ + find "$MINILAKE_TF_PROVIDER_MIRROR" -name 'terraform-provider-databricks*' | grep -q . && \ + chmod -R a+rX "$MINILAKE_TF_PROVIDER_MIRROR" + # Copy project files COPY pyproject.toml pyproject.toml COPY src/ src/ diff --git a/FEATURES.md b/FEATURES.md index d8ce0c2..db70bdc 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -4,7 +4,8 @@ **minilake** is a local Databricks API emulator backed by DuckDB for real SQL execution. This document details all implemented features, APIs, and their current status. -**Coverage:** 208 of the 1168 endpoints the `databricks-sdk` calls (17.8%), measured — see +**Coverage:** 267 of the 1168 endpoints the `databricks-sdk` calls (22.9%) — or ~47% of +the *reachable* surface, once the blocks this project deliberately skips are excluded. Measured — see [docs/CLI_COVERAGE.md](docs/CLI_COVERAGE.md) for the generated map and [docs/EMULATION_ROADMAP.md](docs/EMULATION_ROADMAP.md) for what to build next. @@ -877,6 +878,81 @@ plus `GET` / `PUT` / `PATCH` / `DELETE` on `/{id}` for each — 18 routes. --- +### 17d. **Unity Catalog — Grants** ✅ + +**Module:** `minilake/services/grants.py` +**Endpoints:** `GET`/`PATCH` `/api/2.1/unity-catalog/permissions/{securable_type}/{full_name}`, +`GET /api/2.1/unity-catalog/effective-permissions/{securable_type}/{full_name}` + +**Key Features:** + +- ✅ Real add/remove deltas; dropping a principal's last privilege drops the principal, + as a real workspace does +- ✅ **Real inheritance.** A grant on a catalog is effective on its schemas and their + tables, and `get_effective` tags each privilege with the ancestor it came from. This + is the whole reason `effective-permissions` is a separate endpoint — without it the + route would look correct while hiding the one behaviour it exists for +- ✅ Rejects a securable whose name does not match its type (a `TABLE` addressed by a + one-part name would sit in the store matching nothing) +- ⚠️ The SDK sends `securable_type` as an `Enum` that is not a `str` subclass, so the + wire carries `SecurableType.CATALOG`, not `CATALOG`. Both are accepted +- 🚫 **Never enforced.** No privilege is checked anywhere; a passing test here says + nothing about grants in a real workspace + +**Status:** ✅ Complete and tested — `tests/unity_catalog/test_grants.py` + +--- + +### 17e. **Workspace Admin** ✅ + +**Module:** `minilake/services/workspace_admin.py` +**Endpoints:** `/api/2.0/git-credentials`, `/api/2.0/ip-access-lists`, +`/api/2.0/global-init-scripts`, `/api/2.0/notification-destinations`, +`/api/2.0/instance-profiles/*`, `/api/2.0/workspace-conf` + +**Key Features:** + +- ✅ Real CRUD for all six. Individually dull; together they are what a realistic + `terraform apply` touches before it reaches a catalog, and one 501 fails a whole plan +- ✅ A git credential's `personal_access_token` is stored but **never returned** +- ✅ `list` omits the fields that can carry secrets — the script body for init scripts, + `config` for notification destinations +- ✅ `workspace-conf` values are coerced to strings, because the real API only ever + stores strings; an unset key reads back as `""` rather than being omitted, which is + what lets Terraform see a value it set and later cleared +- 🚫 **Nothing is enforced.** No IP is blocked, no init script runs, no notification is + sent, and an instance profile grants nothing + +**Status:** ✅ Complete and tested — `tests/test_workspace_admin.py` + +--- + +### 17f. **Legacy SQL (`preview/sql`)** ✅ + +**Module:** `minilake/services/preview_sql.py` +**Endpoints:** `/api/2.0/preview/sql/{queries,alerts,dashboards,widgets,visualizations,data_sources}` + +**Key Features:** + +- ✅ **Adapters, not a second store.** Queries and alerts delegate to `saved_queries.py` + and `alerts.py`, translating wire shapes; an object created through either surface is + visible and editable from the other +- ✅ Translates the flat legacy alert condition (`options.column`/`op`/`value`) to the + modern nested one, including the operator symbol — an untranslated `>` would leave an + alert that silently never fires +- ✅ Correct trash semantics: `DELETE` trashes, `POST .../trash/{id}` **restores**. A + trashed query is hidden from both list surfaces and still retrievable by id +- ✅ The list endpoints are page-numbered. This is not a nicety: the SDK walks them by + incrementing `page` until a response is empty, so a handler that ignores the parameter + never terminates +- ✅ `data_sources` projects the real warehouses, so a legacy client picks an id here and + uses it as `data_source_id` +- 🚫 Dashboards, widgets and visualizations are metadata — nothing renders them + +**Status:** ✅ Complete and tested — `tests/test_preview_sql.py` + +--- + ### 18. **MCP Server — LLM agent interface** ✅ (optional) **Modules:** `minilake/mcp/` (`server.py`, `client.py`, `introspect.py`, `resources.py`, diff --git a/README.md b/README.md index 045f855..a813e8d 100644 --- a/README.md +++ b/README.md @@ -99,13 +99,16 @@ More in [Getting Started](https://github.com/dmux/minilake/blob/main/docs/gettin | **Clusters** | ✅ Real state machine | CRUD + timed lifecycle transitions, `update`/`pin`/`unpin`; **no real Spark compute** (by design) | | **Cluster policies & instance pools** | ✅ Real CRUD | Resolve and validate against clusters; never enforced — there is no compute to constrain | | **Permissions** | ✅ Real CRUD | Single-user "allow-all" default (by design — see Gaps) | +| **UC Grants** | ✅ Real CRUD | `w.grants.*` and `databricks_grants`, with real privilege **inheritance** (a catalog grant is effective on its schemas and tables); never enforced | +| **Workspace admin** | ✅ Real CRUD | Git credentials, IP access lists, global init scripts, notification destinations, instance profiles, `workspace-conf` — stored and read back, never enforced | +| **Legacy SQL (`preview/sql`)** | ✅ Real | Queries, alerts, dashboards, widgets, visualizations, data sources — adapters over the modern stores, so both surfaces see one object | | **Identity & SCIM** | ✅ Real CRUD | Current user, plus Users/Groups/ServicePrincipals CRUD, SCIM `PATCH` and filtering. Identities are records, not credentials — see Gaps | | **Tokens** | ✅ Real | `w.tokens.*`; the value is returned once, as in the real API — but authenticates nothing | | **Persistence** (`MINILAKE_PERSIST=1`) | ✅ Real | JSON snapshot on shutdown, restored on startup | | **Unity Catalog protocol for Spark** | ✅ Real | `spark.table("cat.sch.tbl")` resolves against minilake — see [Spark & Delta Lake](https://github.com/dmux/minilake/blob/main/docs/spark-and-delta.md#reading-by-name-with-unity-catalog) | | **JupyterLab + PySpark + Delta** (optional) | ✅ Real | `docker compose --profile notebook up` | | **MCP Server** (optional, `MINILAKE_MCP=1`) | ✅ Real | 67 tools + resources + prompts at `/mcp` — see [MCP Server](https://github.com/dmux/minilake/blob/main/docs/mcp/index.md) | -| Repos/Git, multi-language notebooks, DBT/pipeline tasks, DLT, Model Registry, Vector Search, Dashboards, Delta Sharing | 🚫 Not implemented | Returns `501 NOT_IMPLEMENTED`. For the measured picture, see [API coverage](https://github.com/dmux/minilake/blob/main/docs/CLI_COVERAGE.md) | +| Repos, multi-language notebooks, DBT/pipeline tasks, DLT, Model Registry, Vector Search, Lakeview/Genie, Delta Sharing | 🚫 Not implemented | Returns `501 NOT_IMPLEMENTED`. For the measured picture, see [API coverage](https://github.com/dmux/minilake/blob/main/docs/CLI_COVERAGE.md) | ## Known Gaps diff --git a/docs/CLI_COVERAGE.md b/docs/CLI_COVERAGE.md index 83a8b3f..c28ff7c 100644 --- a/docs/CLI_COVERAGE.md +++ b/docs/CLI_COVERAGE.md @@ -1,6 +1,6 @@ # Databricks API coverage map -Generated by `scripts/cli_coverage.py` on 2026-09-14 using Databricks CLI v1.16.1 against a local minilake (databricks-sdk 0.133.0). +Generated by `scripts/cli_coverage.py` on 2026-09-15 using Databricks CLI v1.16.1 against a local minilake (databricks-sdk 0.133.0). Every row is measured, not hand-written: the real `databricks` CLI is pointed at a disposable minilake and each endpoint the `databricks-sdk` is known to call is issued through `databricks api `. An endpoint counts as **missing** only when minilake answers with the `catchall` 501; any other reply (including a 400 or 404 on the probe's synthetic arguments) means the route exists. @@ -11,10 +11,10 @@ Note on the answered count: `services/permissions.py` registers a single wildcar | | Count | |---|---:| | Endpoints the `databricks-sdk` calls | 1168 | -| Answered by minilake | 208 | -| Returning `501 NOT_IMPLEMENTED` | 960 | -| **Coverage** | **17.8%** | -| Routes registered in `src/minilake/services/` | 155 | +| Answered by minilake | 267 | +| Returning `501 NOT_IMPLEMENTED` | 901 | +| **Coverage** | **22.9%** | +| Routes registered in `src/minilake/services/` | 209 | ## CLI command groups @@ -27,7 +27,7 @@ What `databricks --help` exposes, under the CLI's own section headers. The statu | Command group | Subcommands | Probe | Result | |---|---:|---|---| | `fs` | 5 | — | — not probed | -| `git-credentials` | 5 | `databricks git-credentials list` | 🚫 501 | +| `git-credentials` | 5 | `databricks git-credentials list` | ✅ works | | `repos` | 8 | `databricks repos list` | 🚫 501 | | `secrets` | 10 | `databricks secrets list-scopes` | ✅ works | | `workspace` | 11 | — | — not probed | @@ -38,9 +38,9 @@ What `databricks --help` exposes, under the CLI's own section headers. The statu |---|---:|---|---| | `cluster-policies` | 8 | `databricks cluster-policies list` | ✅ works | | `clusters` | 20 | `databricks clusters list` | ✅ works | -| `global-init-scripts` | 5 | `databricks global-init-scripts list` | 🚫 501 | +| `global-init-scripts` | 5 | `databricks global-init-scripts list` | ✅ works | | `instance-pools` | 8 | `databricks instance-pools list` | ✅ works | -| `instance-profiles` | 4 | `databricks instance-profiles list` | 🚫 501 | +| `instance-profiles` | 4 | `databricks instance-profiles list` | ✅ works | | `libraries` | 3 | — | — not probed | | `policy-compliance-for-clusters` | 3 | — | — not probed | | `policy-families` | 2 | `databricks policy-families list` | 🚫 501 | @@ -104,12 +104,12 @@ What `databricks --help` exposes, under the CLI's own section headers. The statu | Command group | Subcommands | Probe | Result | |---|---:|---|---| | `alerts` | 5 | `databricks alerts list` | ✅ works | -| `alerts-legacy` | 5 | `databricks alerts-legacy list` | 🚫 501 | +| `alerts-legacy` | 5 | `databricks alerts-legacy list` | ✅ works | | `alerts-v2` | 3 | `databricks alerts-v2 list-alerts` | 🚫 501 | -| `dashboards` | 5 | `databricks dashboards list` | 🚫 501 | -| `data-sources` | 1 | `databricks data-sources list` | 🚫 501 | +| `dashboards` | 5 | `databricks dashboards list` | ✅ works | +| `data-sources` | 1 | `databricks data-sources list` | ✅ works | | `queries` | 5 | `databricks queries list` | ✅ works | -| `queries-legacy` | 6 | `databricks queries-legacy list` | 🚫 501 | +| `queries-legacy` | 6 | `databricks queries-legacy list` | ✅ works | | `query-history` | 1 | `databricks query-history list` | ✅ works | | `warehouses` | 15 | `databricks warehouses list` | ✅ works | @@ -170,8 +170,8 @@ What `databricks --help` exposes, under the CLI's own section headers. The statu | Command group | Subcommands | Probe | Result | |---|---:|---|---| -| `ip-access-lists` | 6 | `databricks ip-access-lists list` | 🚫 501 | -| `notification-destinations` | 5 | `databricks notification-destinations list` | 🚫 501 | +| `ip-access-lists` | 6 | `databricks ip-access-lists list` | ✅ works | +| `notification-destinations` | 5 | `databricks notification-destinations list` | ✅ works | | `settings` | 13 | — | — not probed | | `token-management` | 8 | `databricks token-management list` | 🚫 501 | | `tokens` | 4 | `databricks tokens list` | ✅ works | @@ -286,12 +286,11 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the | API group | Answered | Missing | minilake service | |---|---:|---:|---| | `/api/2.0/accounts` | 0 | 140 | — | -| `/api/2.1/unity-catalog` | 30 | 116 | `unity_catalog` | +| `/api/2.1/unity-catalog` | 33 | 113 | `grants`, `unity_catalog` | | `/api/2.0/identity` | 0 | 73 | — | | `/api/2.0/mlflow` | 0 | 68 | — | | `/api/2.0/settings` | 0 | 42 | — | | `/api/2.0/postgres` | 0 | 37 | — | -| `/api/2.0/preview` | 19 | 32 | `identity`, `scim` | | `/api/2.0/genie` | 0 | 29 | — | | `/api/2.0/database` | 0 | 27 | — | | `/api/2.0/vector-search` | 0 | 23 | — | @@ -309,25 +308,20 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the | `/api/2.0/ai-search` | 0 | 12 | — | | `/api/2.0/bundle` | 0 | 12 | — | | `/api/2.0/lineage-tracking` | 0 | 9 | — | -| `/api/2.0/fs` | 0 | 8 | `files` | +| `/api/2.0/preview` | 42 | 9 | `identity`, `preview_sql`, `scim` | | `/api/2.0/policies` | 5 | 7 | `cluster_policies` | | `/api/2.0/sql` | 21 | 7 | `alerts`, `saved_queries`, `sql_statements`, `sql_warehouses` | | `/api/2.0/app-spaces` | 0 | 6 | — | | `/api/2.0/custom-llms` | 0 | 6 | — | -| `/api/2.0/ip-access-lists` | 0 | 6 | — | | `/api/2.0/alerts` | 0 | 5 | — | | `/api/2.0/apps-settings` | 0 | 5 | — | | `/api/2.0/data-sharing` | 0 | 5 | — | | `/api/2.0/default-base-environments` | 0 | 5 | — | | `/api/2.0/entity-tag-assignments` | 0 | 5 | — | -| `/api/2.0/git-credentials` | 0 | 5 | — | -| `/api/2.0/global-init-scripts` | 0 | 5 | — | -| `/api/2.0/notification-destinations` | 0 | 5 | — | | `/api/2.0/quality-monitors` | 0 | 5 | — | | `/api/2.0/repos` | 0 | 5 | — | | `/api/2.0/token-management` | 0 | 5 | — | | `/api/2.1/tag-policies` | 0 | 5 | — | -| `/api/2.0/instance-profiles` | 0 | 4 | — | | `/api/2.0/libraries` | 0 | 4 | — | | `/api/1.2/commands` | 0 | 3 | — | | `/api/1.2/contexts` | 0 | 3 | — | @@ -336,8 +330,8 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the | `/api/2.2/jobs` | 13 | 3 | `jobs` | | `/api/3.0/rfa` | 0 | 3 | — | | `/api/2.0/automl` | 0 | 2 | — | +| `/api/2.0/fs` | 6 | 2 | `files` | | `/api/2.0/policy-families` | 0 | 2 | — | -| `/api/2.0/workspace-conf` | 0 | 2 | — | | `/api/2.1/knowledge-assistants` | 0 | 2 | — | | `/api/2.1/settings` | 0 | 2 | — | | `/api/2.1/supervisor-agents` | 0 | 2 | — | @@ -353,10 +347,16 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the | `/api/2.1/quality-monitoring` | 0 | 1 | — | | `/api/2.1/settings-metadata` | 0 | 1 | — | | `/api/2.0/dbfs` | 10 | 0 | `dbfs` | +| `/api/2.0/git-credentials` | 5 | 0 | `workspace_admin` | +| `/api/2.0/global-init-scripts` | 5 | 0 | `workspace_admin` | | `/api/2.0/instance-pools` | 5 | 0 | `instance_pools` | +| `/api/2.0/instance-profiles` | 4 | 0 | `workspace_admin` | +| `/api/2.0/ip-access-lists` | 6 | 0 | `workspace_admin` | +| `/api/2.0/notification-destinations` | 5 | 0 | `workspace_admin` | | `/api/2.0/permissions` | 68 | 0 | `permissions` | | `/api/2.0/secrets` | 11 | 0 | `secrets` | | `/api/2.0/workspace` | 6 | 0 | `workspace` | +| `/api/2.0/workspace-conf` | 2 | 0 | `workspace_admin` | | `/api/2.1/clusters` | 17 | 0 | `clusters` | ## Missing endpoints, by group @@ -506,7 +506,7 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the -
/api/2.1/unity-catalog — 116 missing +
/api/2.1/unity-catalog — 113 missing - `DELETE /api/2.1/unity-catalog/__probe__` - `DELETE /api/2.1/unity-catalog/connections/__probe__` @@ -535,7 +535,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the - `GET /api/2.1/unity-catalog/connections/__probe__` - `GET /api/2.1/unity-catalog/credentials` - `GET /api/2.1/unity-catalog/credentials/__probe__` -- `GET /api/2.1/unity-catalog/effective-permissions/__probe__/__probe__` - `GET /api/2.1/unity-catalog/effective-privilege-assignments/__probe__/__probe__` - `GET /api/2.1/unity-catalog/entity-tag-assignments/__probe__/__probe__/tags` - `GET /api/2.1/unity-catalog/entity-tag-assignments/__probe__/__probe__/tags/__probe__` @@ -550,7 +549,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the - `GET /api/2.1/unity-catalog/models/__probe__/aliases/__probe__` - `GET /api/2.1/unity-catalog/models/__probe__/versions` - `GET /api/2.1/unity-catalog/models/__probe__/versions/__probe__` -- `GET /api/2.1/unity-catalog/permissions/__probe__/__probe__` - `GET /api/2.1/unity-catalog/policies/__probe__/__probe__` - `GET /api/2.1/unity-catalog/policies/__probe__/__probe__/__probe__` - `GET /api/2.1/unity-catalog/privilege-assignments/__probe__/__probe__` @@ -585,7 +583,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the - `PATCH /api/2.1/unity-catalog/metastores/__probe__` - `PATCH /api/2.1/unity-catalog/models/__probe__` - `PATCH /api/2.1/unity-catalog/models/__probe__/versions/__probe__` -- `PATCH /api/2.1/unity-catalog/permissions/__probe__/__probe__` - `PATCH /api/2.1/unity-catalog/policies/__probe__/__probe__/__probe__` - `PATCH /api/2.1/unity-catalog/providers/__probe__` - `PATCH /api/2.1/unity-catalog/recipients/__probe__` @@ -867,43 +864,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/preview — 32 missing - -- `DELETE /api/2.0/preview/sql/alerts/__probe__` -- `DELETE /api/2.0/preview/sql/dashboards/__probe__` -- `DELETE /api/2.0/preview/sql/queries/__probe__` -- `DELETE /api/2.0/preview/sql/visualizations/__probe__` -- `DELETE /api/2.0/preview/sql/widgets/__probe__` -- `GET /api/2.0/preview/accounts/__probe__/access-control/assignable-roles` -- `GET /api/2.0/preview/accounts/__probe__/access-control/rule-sets` -- `GET /api/2.0/preview/accounts/access-control/assignable-roles` -- `GET /api/2.0/preview/accounts/access-control/rule-sets` -- `GET /api/2.0/preview/sql/alerts` -- `GET /api/2.0/preview/sql/alerts/__probe__` -- `GET /api/2.0/preview/sql/dashboards` -- `GET /api/2.0/preview/sql/dashboards/__probe__` -- `GET /api/2.0/preview/sql/data_sources` -- `GET /api/2.0/preview/sql/permissions/__probe__/__probe__` -- `GET /api/2.0/preview/sql/queries` -- `GET /api/2.0/preview/sql/queries/__probe__` -- `POST /api/2.0/preview/sql/alerts` -- `POST /api/2.0/preview/sql/dashboards/__probe__` -- `POST /api/2.0/preview/sql/dashboards/trash/__probe__` -- `POST /api/2.0/preview/sql/permissions/__probe__/__probe__` -- `POST /api/2.0/preview/sql/permissions/__probe__/__probe__/transfer` -- `POST /api/2.0/preview/sql/queries` -- `POST /api/2.0/preview/sql/queries/__probe__` -- `POST /api/2.0/preview/sql/queries/trash/__probe__` -- `POST /api/2.0/preview/sql/visualizations` -- `POST /api/2.0/preview/sql/visualizations/__probe__` -- `POST /api/2.0/preview/sql/widgets` -- `POST /api/2.0/preview/sql/widgets/__probe__` -- `PUT /api/2.0/preview/accounts/__probe__/access-control/rule-sets` -- `PUT /api/2.0/preview/accounts/access-control/rule-sets` -- `PUT /api/2.0/preview/sql/alerts/__probe__` - -
-
/api/2.0/genie — 29 missing - `DELETE /api/2.0/genie/spaces/__probe__` @@ -1292,16 +1252,17 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/fs — 8 missing +
/api/2.0/preview — 9 missing -- `DELETE /api/2.0/fs/directories__probe__` -- `DELETE /api/2.0/fs/files__probe__` -- `GET /api/2.0/fs/directories__probe__` -- `GET /api/2.0/fs/files__probe__` -- `HEAD /api/2.0/fs/directories__probe__` -- `HEAD /api/2.0/fs/files__probe__` -- `PUT /api/2.0/fs/directories__probe__` -- `PUT /api/2.0/fs/files__probe__` +- `GET /api/2.0/preview/accounts/__probe__/access-control/assignable-roles` +- `GET /api/2.0/preview/accounts/__probe__/access-control/rule-sets` +- `GET /api/2.0/preview/accounts/access-control/assignable-roles` +- `GET /api/2.0/preview/accounts/access-control/rule-sets` +- `GET /api/2.0/preview/sql/permissions/__probe__/__probe__` +- `POST /api/2.0/preview/sql/permissions/__probe__/__probe__` +- `POST /api/2.0/preview/sql/permissions/__probe__/__probe__/transfer` +- `PUT /api/2.0/preview/accounts/__probe__/access-control/rule-sets` +- `PUT /api/2.0/preview/accounts/access-control/rule-sets`
@@ -1351,17 +1312,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/ip-access-lists — 6 missing - -- `DELETE /api/2.0/ip-access-lists/__probe__` -- `GET /api/2.0/ip-access-lists` -- `GET /api/2.0/ip-access-lists/__probe__` -- `PATCH /api/2.0/ip-access-lists/__probe__` -- `POST /api/2.0/ip-access-lists` -- `PUT /api/2.0/ip-access-lists/__probe__` - -
-
/api/2.0/alerts — 5 missing - `DELETE /api/2.0/alerts/__probe__` @@ -1412,36 +1362,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/git-credentials — 5 missing - -- `DELETE /api/2.0/git-credentials/__probe__` -- `GET /api/2.0/git-credentials` -- `GET /api/2.0/git-credentials/__probe__` -- `PATCH /api/2.0/git-credentials/__probe__` -- `POST /api/2.0/git-credentials` - -
- -
/api/2.0/global-init-scripts — 5 missing - -- `DELETE /api/2.0/global-init-scripts/__probe__` -- `GET /api/2.0/global-init-scripts` -- `GET /api/2.0/global-init-scripts/__probe__` -- `PATCH /api/2.0/global-init-scripts/__probe__` -- `POST /api/2.0/global-init-scripts` - -
- -
/api/2.0/notification-destinations — 5 missing - -- `DELETE /api/2.0/notification-destinations/__probe__` -- `GET /api/2.0/notification-destinations` -- `GET /api/2.0/notification-destinations/__probe__` -- `PATCH /api/2.0/notification-destinations/__probe__` -- `POST /api/2.0/notification-destinations` - -
-
/api/2.0/quality-monitors — 5 missing - `DELETE /api/2.0/quality-monitors/__probe__/__probe__` @@ -1482,15 +1402,6 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/instance-profiles — 4 missing - -- `GET /api/2.0/instance-profiles/list` -- `POST /api/2.0/instance-profiles/add` -- `POST /api/2.0/instance-profiles/edit` -- `POST /api/2.0/instance-profiles/remove` - -
-
/api/2.0/libraries — 4 missing - `GET /api/2.0/libraries/all-cluster-statuses` @@ -1555,17 +1466,17 @@ Ordered by number of missing endpoints. `—` means no minilake service owns the
-
/api/2.0/policy-families — 2 missing +
/api/2.0/fs — 2 missing -- `GET /api/2.0/policy-families` -- `GET /api/2.0/policy-families/__probe__` +- `HEAD /api/2.0/fs/directories/__probe__` +- `HEAD /api/2.0/fs/files/__probe__`
-
/api/2.0/workspace-conf — 2 missing +
/api/2.0/policy-families — 2 missing -- `GET /api/2.0/workspace-conf` -- `PATCH /api/2.0/workspace-conf` +- `GET /api/2.0/policy-families` +- `GET /api/2.0/policy-families/__probe__`
diff --git a/docs/EMULATION_ROADMAP.md b/docs/EMULATION_ROADMAP.md index 11f42d0..c5b001a 100644 --- a/docs/EMULATION_ROADMAP.md +++ b/docs/EMULATION_ROADMAP.md @@ -9,16 +9,16 @@ overwritten on the next run. ## Where we stand -minilake answers **208 of the 1168 endpoints** the `databricks-sdk` calls — **17.8%**, -up from 13.3% before the work described in "Done" below. Of the 127 command groups the -`databricks` CLI exposes, **21** now work end-to-end: `alerts`, `catalogs`, -`cluster-policies`, `clusters`, `current-user`, `groups`, `groups-v2`, -`instance-pools`, `jobs`, `metastores`, `queries`, `query-history`, `secrets`, -`service-principals`, `service-principals-v2`, `tokens`, `users`, `users-v2`, -`warehouses`, plus the CLI-local `aitools` and `labs`. +minilake answers **267 of the 1168 endpoints** the `databricks-sdk` calls — 22.9%. -The tiers below are ordered by value per unit of work for the project's actual goal — -one developer running Databricks-dependent code locally — not by endpoint count. +That headline number understates things, and the roadmap used to repeat it without +the qualification. **604 of the missing endpoints are in blocks this project has +deliberately decided not to emulate** (MLflow, the Account API, identity v2, +marketplace, Genie, Lakebase, vector search, serving, clean rooms, apps). Against the +*reachable* surface, coverage is **267 of 564 — about 47%**. That is the number worth +tracking. + +Of the 127 command groups the `databricks` CLI exposes, **30** work end to end. --- @@ -26,6 +26,33 @@ one developer running Databricks-dependent code locally — not by endpoint coun Delivered, with tests driven through the real `databricks-sdk` (suite: 339 passing). +### 1.7.8 — Terraform conformance and the admin belt + +- **A Terraform conformance test** (`tests/terraform/`). `docs/terraform.md` promised + the provider worked; nothing verified it. The first run found three defects that + every SDK-driven test had missed, because they are in behaviour only the provider + exercises — see the file's docstring. It runs `apply` → `plan` → `destroy` against a + realistic 15-resource config, and the empty second plan is the assertion that + matters: it is what proves minilake reports back what it was given. +- **UC grants** (`w.grants.*`, `databricks_grants`) — with real **inheritance**: a + grant on a catalog is effective on its schemas and tables, tagged with its source. + `tests/unity_catalog/test_grants.py` +- **The workspace-admin belt** — git credentials, IP access lists, global init + scripts, notification destinations, instance profiles and `workspace-conf`. Each is + trivial; together they are what a `terraform apply` touches before it reaches + anything interesting, and one 501 fails a whole plan. + `tests/test_workspace_admin.py` +- **Legacy `preview/sql`** — queries, alerts, dashboards, widgets, visualizations and + data sources, as **adapters over the modern stores** rather than a second copy. A + query created through either surface is visible from the other. + `tests/test_preview_sql.py` +- **Coverage harness fix.** It had been scoring all 8 Files API endpoints as missing: + the SDK writes `/api/2.0/fs/files{path}` with the parameter carrying its own leading + slash, and the normalizer produced a path matching no route. Those two paths are the + only ones in the SDK shaped that way. + +### 1.7.7 — the first coverage pass + **Things that already had an engine, and only lacked a door:** - **`sql_task.query`** — a sql_task now resolves a saved query's text through diff --git a/docs/terraform.md b/docs/terraform.md index 842188a..c10209f 100644 --- a/docs/terraform.md +++ b/docs/terraform.md @@ -29,8 +29,31 @@ resource "databricks_sql_endpoint" "compute" { `terraform apply` creates real catalogs and real DuckDB databases. `terraform destroy` removes them. +This is **tested, not asserted**: `tests/terraform/` runs the real provider through +`apply` → `plan` → `destroy` against a 15-resource config on every suite run, and fails +if the second plan is not empty. Permanent drift — a resource minilake accepts but +reports back differently — is worse than a 501, because it looks like it works until +someone runs `plan` twice. + +Resources covered by that test, and therefore known to work: + +| | | +|---|---| +| Unity Catalog | `databricks_catalog`, `databricks_schema`, `databricks_grants` | +| SQL | `databricks_sql_endpoint` | +| Identity | `databricks_user`, `databricks_group`, `databricks_group_member`, `databricks_service_principal`, `databricks_token` | +| Secrets | `databricks_secret_scope`, `databricks_secret`, `databricks_secret_acl` | +| Compute | `databricks_cluster_policy`, `databricks_instance_pool` | +| Workspace | `databricks_git_credential` | + Resource types that depend on APIs minilake does not emulate — pipelines/DLT, model -serving, dashboards — fail with `501 NOT_IMPLEMENTED` rather than silently succeeding. +serving, Lakeview dashboards — fail with `501 NOT_IMPLEMENTED` rather than silently +succeeding. + +> Nothing Terraform creates here is enforced. A `databricks_grants` block is stored and +> read back faithfully, but no privilege is ever checked; the same goes for secret ACLs, +> cluster policies and IP access lists. A plan that applies cleanly against minilake +> says the *shape* of your config is right, not that its access control is. > The Databricks CLI and provider prefer an `https://` host. minilake can serve TLS itself > — see [Configuration → Native HTTPS](configuration.md#native-https). diff --git a/docs/testing.md b/docs/testing.md index 8d308ac..0794045 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -105,3 +105,24 @@ If it should also be agent-reachable, add `mcp/tools/.py` exporting service, so `MINILAKE_SERVICES` filtering applies automatically. See [CONTRIBUTING.md](../CONTRIBUTING.md) for the PR checklist. + +## Terraform conformance + +`tests/terraform/` runs the **real** Databricks Terraform provider against minilake: +`apply` → `plan` → `destroy` over a realistic 15-resource config, asserting that the +second plan is empty. + +It needs two things the test image bakes in (see `Dockerfile.test`): the `terraform` +binary, and a local mirror of the provider at `$MINILAKE_TF_PROVIDER_MIRROR`, warmed at +build time so the suite needs no network. Running pytest on the host without terraform +installed **skips** these tests rather than failing; without the mirror, `init` falls +back to the registry, which works but needs network. + +Both versions are pinned. A conformance test is only meaningful if it keeps testing the +same provider — a floating version turns an upstream release into a mysterious CI +failure. + +The empty second plan is the assertion that earns its keep. A resource minilake accepts +but reports back differently is permanent drift, which is worse than a 501: it looks +like it works until someone runs `plan` twice. The first run of this test found three +such defects that every SDK-driven test in the suite had missed. diff --git a/scripts/cli_coverage.py b/scripts/cli_coverage.py index 4301265..2471dc4 100644 --- a/scripts/cli_coverage.py +++ b/scripts/cli_coverage.py @@ -187,6 +187,20 @@ def sdk_service_dir() -> Path: API_CALL_RE = re.compile(r'\.do\(\s*"([A-Z]+)"\s*,\s*f?"(/api/[0-9.]+/[^"]+)"', re.S) +# A handful of SDK paths concatenate the parameter straight onto the segment, because the +# value carries its own leading slash: `/api/2.0/fs/files{file_path}` is really +# `/api/2.0/fs/files/Volumes/...`. Substituting the placeholder verbatim would produce +# `fs/files__probe__`, which matches no route, and the endpoint would be scored missing +# when it is implemented. Insert the separator those paths leave to the parameter. +_GLUED_PARAM_RE = re.compile(r"(?<=[A-Za-z0-9])\{") + + +def _normalize(raw: str) -> str: + """Turn an SDK path template into a concrete path to probe.""" + raw = _GLUED_PARAM_RE.sub("/{", raw) + return re.sub(r"\{[^}]+\}", PROBE_PLACEHOLDER, raw).rstrip("/") + + def extract_sdk_endpoints(service_dir: Path) -> dict[str, set[tuple[str, str]]]: """Map each SDK service module to the (method, path) endpoints it calls.""" by_module: dict[str, set[tuple[str, str]]] = {} @@ -197,8 +211,7 @@ def extract_sdk_endpoints(service_dir: Path) -> dict[str, set[tuple[str, str]]]: for method, raw in API_CALL_RE.findall(path.read_text()): if JUNK_PATH_RE.match(raw): continue - normalized = re.sub(r"\{[^}]+\}", PROBE_PLACEHOLDER, raw).rstrip("/") - found.add((method, normalized)) + found.add((method, _normalize(raw))) if found: by_module[path.stem] = found return by_module diff --git a/src/minilake/app.py b/src/minilake/app.py index 2b8b819..68b8471 100644 --- a/src/minilake/app.py +++ b/src/minilake/app.py @@ -62,7 +62,9 @@ "sql_warehouses": "SQL Warehouses", "saved_queries": "Saved Queries", "alerts": "Alerts", + "preview_sql": "SQL (legacy preview)", "unity_catalog": "Unity Catalog", + "grants": "UC Grants", "workspace": "Workspace", "clusters": "Clusters", "cluster_policies": "Cluster Policies", @@ -70,6 +72,7 @@ "jobs": "Jobs", "secrets": "Secrets", "permissions": "Permissions", + "workspace_admin": "Workspace Admin", } diff --git a/src/minilake/models/grants.py b/src/minilake/models/grants.py new file mode 100644 index 0000000..6267216 --- /dev/null +++ b/src/minilake/models/grants.py @@ -0,0 +1,52 @@ +"""Unity Catalog grant models (Databricks Grants API 2.1).""" + +from typing import List, Optional + +from pydantic import BaseModel + + +class PrivilegeAssignment(BaseModel): + """The privileges one principal holds on a securable.""" + + principal: str + privileges: List[str] = [] + + +class GetPermissionsResponse(BaseModel): + privilege_assignments: List[PrivilegeAssignment] = [] + next_page_token: Optional[str] = None + + +class PermissionsChange(BaseModel): + """One principal's delta: privileges to add, privileges to remove.""" + + principal: Optional[str] = None + add: Optional[List[str]] = None + remove: Optional[List[str]] = None + + +class UpdatePermissionsRequest(BaseModel): + changes: Optional[List[PermissionsChange]] = None + omit_permissions_in_response: Optional[bool] = None + + +class EffectivePrivilege(BaseModel): + """A privilege, plus where it came from. + + `inherited_from_name`/`inherited_from_type` are unset for a grant made directly + on the securable, and name the ancestor otherwise. + """ + + privilege: str + inherited_from_name: Optional[str] = None + inherited_from_type: Optional[str] = None + + +class EffectivePrivilegeAssignment(BaseModel): + principal: str + privileges: List[EffectivePrivilege] = [] + + +class EffectivePermissionsList(BaseModel): + privilege_assignments: List[EffectivePrivilegeAssignment] = [] + next_page_token: Optional[str] = None diff --git a/src/minilake/models/sql.py b/src/minilake/models/sql.py index 6ac6b57..ed2aa35 100644 --- a/src/minilake/models/sql.py +++ b/src/minilake/models/sql.py @@ -21,8 +21,26 @@ class CreateWarehouseResponse(BaseModel): id: Optional[str] = None +class OdbcParams(BaseModel): + """Connection parameters a BI tool would use. Reported because the Terraform + provider treats a missing `odbc_params` as a change to apply on every plan.""" + + hostname: Optional[str] = None + host: Optional[str] = None + path: Optional[str] = None + port: Optional[int] = None + protocol: Optional[str] = None + + class GetWarehouseResponse(BaseModel): - """Warehouse metadata.""" + """Warehouse metadata. + + The config fields below are accepted, stored and reported back, but none of them + changes behaviour: statements run on DuckDB regardless of cluster size, photon or + autostop. They are here because a client that sets a value and reads back a + different one sees drift — `terraform plan` reported a permanent in-place update + for every warehouse until these were returned. + """ id: str name: str @@ -31,6 +49,16 @@ class GetWarehouseResponse(BaseModel): comment: Optional[str] = None created_at: Optional[int] = None updated_at: Optional[int] = None + auto_stop_mins: Optional[int] = None + min_num_clusters: Optional[int] = None + max_num_clusters: Optional[int] = None + num_clusters: Optional[int] = None + enable_photon: Optional[bool] = None + enable_serverless_compute: Optional[bool] = None + spot_instance_policy: Optional[str] = None + warehouse_type: Optional[str] = None + creator_name: Optional[str] = None + odbc_params: Optional[OdbcParams] = None class Config: extra = "allow" @@ -42,6 +70,18 @@ class CreateWarehouseRequest(BaseModel): name: str cluster_size: str = "Small" comment: Optional[str] = None + auto_stop_mins: Optional[int] = None + min_num_clusters: Optional[int] = None + max_num_clusters: Optional[int] = None + enable_photon: Optional[bool] = None + enable_serverless_compute: Optional[bool] = None + spot_instance_policy: Optional[str] = None + warehouse_type: Optional[str] = None + tags: Optional[dict] = None + channel: Optional[dict] = None + + class Config: + extra = "allow" class ListWarehousesResponse(BaseModel): diff --git a/src/minilake/models/workspace_admin.py b/src/minilake/models/workspace_admin.py new file mode 100644 index 0000000..00340f5 --- /dev/null +++ b/src/minilake/models/workspace_admin.py @@ -0,0 +1,188 @@ +"""Models for the small workspace-admin APIs Terraform reaches for. + +Git credentials, IP access lists, global init scripts, notification destinations, +instance profiles and workspace conf. Each is tiny on its own; together they are what +a realistic `terraform apply` touches before it gets to anything interesting. +""" + +from typing import Any, Dict, List, Optional + +from pydantic import BaseModel + +# ------------------------------------------------------------------ git credentials + + +class CreateCredentialRequest(BaseModel): + git_provider: str + git_username: Optional[str] = None + git_email: Optional[str] = None + personal_access_token: Optional[str] = None + name: Optional[str] = None + is_default_for_provider: Optional[bool] = None + + class Config: + extra = "allow" + + +class UpdateCredentialRequest(BaseModel): + git_provider: Optional[str] = None + git_username: Optional[str] = None + git_email: Optional[str] = None + personal_access_token: Optional[str] = None + name: Optional[str] = None + is_default_for_provider: Optional[bool] = None + + class Config: + extra = "allow" + + +class CredentialInfo(BaseModel): + """A stored git credential. The token itself is never returned, matching the real + API — only the metadata around it.""" + + credential_id: int + git_provider: Optional[str] = None + git_username: Optional[str] = None + git_email: Optional[str] = None + name: Optional[str] = None + is_default_for_provider: Optional[bool] = None + + +class ListCredentialsResponse(BaseModel): + credentials: List[CredentialInfo] = [] + + +# ------------------------------------------------------------------ IP access lists + + +class CreateIpAccessListRequest(BaseModel): + label: str + list_type: str + ip_addresses: Optional[List[str]] = None + + +class UpdateIpAccessListRequest(BaseModel): + label: Optional[str] = None + list_type: Optional[str] = None + ip_addresses: Optional[List[str]] = None + enabled: Optional[bool] = None + + +class IpAccessListInfo(BaseModel): + list_id: str + label: Optional[str] = None + list_type: Optional[str] = None + ip_addresses: Optional[List[str]] = None + address_count: Optional[int] = None + enabled: Optional[bool] = None + created_at: Optional[int] = None + created_by: Optional[int] = None + updated_at: Optional[int] = None + updated_by: Optional[int] = None + + +class IpAccessListResponse(BaseModel): + ip_access_list: Optional[IpAccessListInfo] = None + + +class GetIpAccessListsResponse(BaseModel): + ip_access_lists: List[IpAccessListInfo] = [] + + +# ------------------------------------------------------------- global init scripts + + +class CreateGlobalInitScriptRequest(BaseModel): + name: str + script: str + position: Optional[int] = None + enabled: Optional[bool] = None + + +class UpdateGlobalInitScriptRequest(BaseModel): + name: Optional[str] = None + script: Optional[str] = None + position: Optional[int] = None + enabled: Optional[bool] = None + + +class GlobalInitScriptDetails(BaseModel): + """Script metadata. `script` (the base64 body) is returned only by `get`, as in the + real API — `list` omits it.""" + + script_id: str + name: Optional[str] = None + position: Optional[int] = None + enabled: Optional[bool] = None + script: Optional[str] = None + created_at: Optional[int] = None + created_by: Optional[str] = None + updated_at: Optional[int] = None + updated_by: Optional[str] = None + + +class CreateGlobalInitScriptResponse(BaseModel): + script_id: str + + +class ListGlobalInitScriptsResponse(BaseModel): + scripts: List[GlobalInitScriptDetails] = [] + + +# ------------------------------------------------------ notification destinations + + +class NotificationDestinationRequest(BaseModel): + display_name: Optional[str] = None + config: Optional[Dict[str, Any]] = None + + +class NotificationDestination(BaseModel): + id: str + display_name: Optional[str] = None + destination_type: Optional[str] = None + config: Optional[Dict[str, Any]] = None + + +class ListNotificationDestinationsResult(BaseModel): + """The list entry is deliberately narrower than the full object: the real API omits + `config` here, because it can carry secrets.""" + + id: str + display_name: Optional[str] = None + destination_type: Optional[str] = None + + +class ListNotificationDestinationsResponse(BaseModel): + results: List[ListNotificationDestinationsResult] = [] + next_page_token: Optional[str] = None + + +# ---------------------------------------------------------------- instance profiles + + +class AddInstanceProfileRequest(BaseModel): + instance_profile_arn: str + iam_role_arn: Optional[str] = None + is_meta_instance_profile: Optional[bool] = None + skip_validation: Optional[bool] = None + + +class EditInstanceProfileRequest(BaseModel): + instance_profile_arn: str + iam_role_arn: Optional[str] = None + is_meta_instance_profile: Optional[bool] = None + + +class RemoveInstanceProfileRequest(BaseModel): + instance_profile_arn: str + + +class InstanceProfile(BaseModel): + instance_profile_arn: str + iam_role_arn: Optional[str] = None + is_meta_instance_profile: Optional[bool] = None + + +class ListInstanceProfilesResponse(BaseModel): + instance_profiles: List[InstanceProfile] = [] diff --git a/src/minilake/services/__init__.py b/src/minilake/services/__init__.py index 33ad797..e1b5871 100644 --- a/src/minilake/services/__init__.py +++ b/src/minilake/services/__init__.py @@ -30,7 +30,9 @@ "sql_warehouses": "minilake.services.sql_warehouses", "saved_queries": "minilake.services.saved_queries", "alerts": "minilake.services.alerts", + "preview_sql": "minilake.services.preview_sql", "unity_catalog": "minilake.services.unity_catalog", + "grants": "minilake.services.grants", "workspace": "minilake.services.workspace", "clusters": "minilake.services.clusters", "cluster_policies": "minilake.services.cluster_policies", @@ -38,6 +40,7 @@ "jobs": "minilake.services.jobs", "secrets": "minilake.services.secrets", "permissions": "minilake.services.permissions", + "workspace_admin": "minilake.services.workspace_admin", "catchall": "minilake.services.catchall", } diff --git a/src/minilake/services/grants.py b/src/minilake/services/grants.py new file mode 100644 index 0000000..dcae6a7 --- /dev/null +++ b/src/minilake/services/grants.py @@ -0,0 +1,240 @@ +"""Unity Catalog Grants API (Databricks Grants API 2.1). + +`w.grants.get/update/get_effective` and Terraform's `databricks_grants` talk to these +routes. After catalogs, schemas and tables, this is the UC surface real code touches +most, and every call to it used to hit the 501 catch-all. + +Grants are recorded, never enforced — minilake has one user and no authentication, so +there is nobody for a privilege to exclude (the same bargain `permissions.py` makes). +A test that passes here still says nothing about grants in a real workspace. + +What *is* real is **inheritance**. A grant on a catalog is inherited by its schemas and +their tables, which is the whole reason `get_effective` exists as a separate endpoint +from `get`. Emulating that costs a walk up the name, and without it `get_effective` +would just be `get` under another name — worse than not implementing it, because it +would look right while hiding the one behaviour it is for. +""" + +import logging +from typing import Any, Dict, List, Optional, Tuple + +from fastapi import APIRouter +from fastapi import Query as QueryParam + +from minilake.errors import DatabricksError +from minilake.models.grants import ( + EffectivePermissionsList, + EffectivePrivilege, + EffectivePrivilegeAssignment, + GetPermissionsResponse, + PrivilegeAssignment, + UpdatePermissionsRequest, +) + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/2.1/unity-catalog", tags=["grants"]) + +# (securable_type, full_name) -> {principal: sorted set of privileges} +_state: Dict[str, Any] = {"grants": {}} + +# Securable types whose names are dotted and therefore nest. Anything else (METASTORE, +# and the securables minilake does not model) simply has no parent. +_NESTED = {"CATALOG": 1, "SCHEMA": 2, "TABLE": 3, "VOLUME": 3, "FUNCTION": 3} + +# The root securable: a grant here is inherited by everything. +_METASTORE = ("METASTORE", None) + + +def _normalize_securable(securable_type: str) -> str: + """Accept both `CATALOG` and `SecurableType.CATALOG` in the path. + + `SecurableType` is a plain `Enum`, not a `str` mixin, so the SDK's + `f"/permissions/{securable_type}/..."` puts the *repr* on the wire — + `SecurableType.CATALOG`. Taking the segment after the last dot handles both that + and a caller who sends the bare name. Without this the type never matches, which + fails silently: grants are stored under an unrecognised key, inheritance finds + nothing, and validation is skipped because the type looks unknown. + """ + return securable_type.rsplit(".", 1)[-1].upper() + + +def _key(securable_type: str, full_name: str) -> Tuple[str, str]: + return (_normalize_securable(securable_type), full_name) + + +def _validate(securable_type: str, full_name: str) -> str: + """Reject a securable whose name does not match its type. + + A `TABLE` addressed by a one-part name is a caller bug that would otherwise sit in + the store forever, granting nothing and matching nothing. + """ + securable = _normalize_securable(securable_type) + expected = _NESTED.get(securable) + if expected is None: + return securable + parts = full_name.split(".") + if len(parts) != expected: + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message=(f"A {securable} is addressed by a {expected}-part name; got '{full_name}'"), + status_code=400, + ) + return securable + + +def _ancestors(securable_type: str, full_name: str) -> List[Tuple[str, Optional[str]]]: + """Every securable a grant could be inherited from, nearest first.""" + chain: List[Tuple[str, Optional[str]]] = [] + depth = _NESTED.get(_normalize_securable(securable_type)) + if depth is not None: + parts = full_name.split(".") + # A table's parents are its schema then its catalog; a schema's is its catalog. + for length, kind in ((2, "SCHEMA"), (1, "CATALOG")): + if length < depth: + chain.append((kind, ".".join(parts[:length]))) + chain.append(_METASTORE) + return chain + + +def _assignments(key: Tuple[str, Optional[str]]) -> Dict[str, List[str]]: + return _state["grants"].get(key, {}) + + +@router.get("/permissions/{securable_type}/{full_name}", response_model=GetPermissionsResponse) +async def get_permissions( + securable_type: str, + full_name: str, + principal: Optional[str] = QueryParam(None), +) -> GetPermissionsResponse: + """Grants made directly on this securable — inherited ones are not included.""" + securable = _validate(securable_type, full_name) + stored = _assignments(_key(securable, full_name)) + + assignments = [ + PrivilegeAssignment(principal=who, privileges=sorted(privileges)) + for who, privileges in sorted(stored.items()) + if principal is None or who == principal + ] + return GetPermissionsResponse(privilege_assignments=assignments) + + +@router.patch("/permissions/{securable_type}/{full_name}", response_model=GetPermissionsResponse) +async def update_permissions( + securable_type: str, + full_name: str, + req: UpdatePermissionsRequest, +) -> GetPermissionsResponse: + """Apply add/remove deltas for one or more principals.""" + securable = _validate(securable_type, full_name) + key = _key(securable, full_name) + stored = _state["grants"].setdefault(key, {}) + + for change in req.changes or []: + who = change.principal + if not who: + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message="Each change requires a principal", + status_code=400, + ) + privileges = set(stored.get(who, [])) + privileges |= {p.upper() for p in (change.add or [])} + privileges -= {p.upper() for p in (change.remove or [])} + + # Dropping the last privilege drops the principal: a real workspace lists no + # assignment for someone who holds nothing, rather than an empty one. + if privileges: + stored[who] = sorted(privileges) + else: + stored.pop(who, None) + + if not stored: + _state["grants"].pop(key, None) + + logger.info(f"Updated grants on {securable} '{full_name}'") + + if req.omit_permissions_in_response: + return GetPermissionsResponse() + return await get_permissions(securable_type, full_name, principal=None) + + +@router.get( + "/effective-permissions/{securable_type}/{full_name}", + response_model=EffectivePermissionsList, +) +async def get_effective_permissions( + securable_type: str, + full_name: str, + principal: Optional[str] = QueryParam(None), +) -> EffectivePermissionsList: + """Direct grants plus everything inherited from ancestors, tagged with its source.""" + securable = _validate(securable_type, full_name) + + # principal -> privilege -> (inherited_from_type, inherited_from_name). The nearest + # source wins, so direct grants are recorded first and ancestors never overwrite. + effective: Dict[str, Dict[str, Tuple[Optional[str], Optional[str]]]] = {} + + def absorb(source: Tuple[str, Optional[str]], inherited: bool) -> None: + for who, privileges in _assignments(source).items(): + for privilege in privileges: + effective.setdefault(who, {}).setdefault( + privilege, (source[0], source[1]) if inherited else (None, None) + ) + + absorb(_key(securable, full_name), inherited=False) + for ancestor in _ancestors(securable, full_name): + absorb(ancestor, inherited=True) + + assignments = [] + for who, privileges in sorted(effective.items()): + if principal is not None and who != principal: + continue + assignments.append( + EffectivePrivilegeAssignment( + principal=who, + privileges=[ + EffectivePrivilege( + privilege=privilege, + inherited_from_type=source_type, + inherited_from_name=source_name, + ) + for privilege, (source_type, source_name) in sorted(privileges.items()) + ], + ) + ) + return EffectivePermissionsList(privilege_assignments=assignments) + + +# ============================================================================ +# State Management +# ============================================================================ + + +def get_state() -> Dict[str, Any]: + """Get state for snapshotting. + + Keys are tuples, which JSON cannot represent — flatten them for the snapshot and + rebuild on restore. Without this, `MINILAKE_PERSIST=1` silently drops every grant. + """ + return { + "grants": { + f"{securable}\t{name or ''}": assignments for (securable, name), assignments in _state["grants"].items() + } + } + + +def restore_state(data: Dict[str, Any]) -> None: + """Restore state from snapshot.""" + global _state + restored = {} + for flat, assignments in (data.get("grants") or {}).items(): + securable, _, name = flat.partition("\t") + restored[(securable, name or None)] = assignments + _state = {"grants": restored} + + +async def reset() -> None: + """Reset grant state.""" + global _state + _state = {"grants": {}} diff --git a/src/minilake/services/preview_sql.py b/src/minilake/services/preview_sql.py new file mode 100644 index 0000000..26d1985 --- /dev/null +++ b/src/minilake/services/preview_sql.py @@ -0,0 +1,524 @@ +"""Legacy `/api/2.0/preview/sql/*` endpoints. + +Deprecated upstream, but still what `databricks dashboards`, older Terraform provider +versions and a lot of existing code actually call. The SDK reaches them through +`w.queries_legacy`, `w.alerts_legacy` and `w.dashboards`. + +**These are adapters, not a second implementation.** Queries and alerts delegate to the +modern stores in `saved_queries.py` and `alerts.py`, translating between the two wire +shapes; there is exactly one copy of each object, so a query created through the legacy +route is visible through the modern one and vice versa. Keeping separate state would +have been less code today and a source of "I created it but it isn't there" forever. + +The shape differences that matter: + +- legacy uses `name`, modern uses `display_name`; legacy uses `query` for the SQL text, + modern uses `query_text` +- legacy `create`/`update` take a flat body, modern nests under `query`/`alert` +- legacy `delete` is a POST to `.../trash/{id}` (it moves to trash), and there is no + restore here — minilake deletes outright, which is the honest simplification + +Dashboards, widgets and visualizations have no modern counterpart in minilake, so those +are stored here directly. They are metadata: nothing renders a dashboard. +""" + +import logging +import uuid +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional + +from fastapi import APIRouter +from fastapi import Query as QueryParam + +from minilake.errors import DatabricksError +from minilake.services import alerts as alerts_service +from minilake.services import identity +from minilake.services import saved_queries as queries_service + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/2.0/preview/sql", tags=["preview_sql"]) + +# Only the objects with no modern equivalent live here. +_state: Dict[str, Any] = {"dashboards": {}, "widgets": {}, "visualizations": {}} + + +def _now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +# ------------------------------------------------------------------- translation + + +def _query_to_legacy(stored: Dict[str, Any]) -> Dict[str, Any]: + """Render a modern saved query in the legacy wire shape.""" + return { + "id": stored.get("id"), + "name": stored.get("display_name"), + "description": stored.get("description"), + "query": stored.get("query_text"), + "data_source_id": stored.get("warehouse_id"), + "options": stored.get("options") or {}, + "tags": stored.get("tags") or [], + "user_id": 1, + "created_at": stored.get("create_time"), + "updated_at": stored.get("update_time"), + "is_archived": False, + "is_draft": False, + } + + +def _legacy_to_query(body: Dict[str, Any]) -> Dict[str, Any]: + """Translate a legacy create/update body into modern saved-query fields.""" + mapped: Dict[str, Any] = {} + if "name" in body: + mapped["display_name"] = body["name"] + if "description" in body: + mapped["description"] = body["description"] + if "query" in body: + mapped["query_text"] = body["query"] + if "data_source_id" in body: + mapped["warehouse_id"] = body["data_source_id"] + if "tags" in body: + mapped["tags"] = body["tags"] + if "options" in body: + mapped["options"] = body["options"] + return mapped + + +# The legacy alert API names its comparison with a symbol; the modern one uses an enum. +# Translating is not cosmetic: an untranslated ">" reaches `alerts.evaluate_alert`, which +# does not recognise it, and the alert silently never fires. +_LEGACY_TO_MODERN_OP = { + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + "==": "EQUAL", + "=": "EQUAL", + "!=": "NOT_EQUAL", +} +_MODERN_TO_LEGACY_OP = { + "GREATER_THAN": ">", + "GREATER_THAN_OR_EQUAL": ">=", + "LESS_THAN": "<", + "LESS_THAN_OR_EQUAL": "<=", + "EQUAL": "==", + "NOT_EQUAL": "!=", +} + + +def _alert_to_legacy(stored: Dict[str, Any]) -> Dict[str, Any]: + """Render a modern alert in the legacy wire shape. + + The legacy condition is flat (`options.column`/`op`/`value`) where the modern one + nests under `condition`; the SDK's legacy models read the flat form. + """ + condition = stored.get("condition") or {} + column = ((condition.get("operand") or {}).get("column") or {}).get("name") + threshold = ((condition.get("threshold") or {}).get("value")) or {} + value = next( + (threshold[k] for k in ("double_value", "string_value", "bool_value") if threshold.get(k) is not None), + None, + ) + return { + "id": stored.get("id"), + "name": stored.get("display_name"), + "query": {"id": stored.get("query_id")}, + "state": (stored.get("state") or "unknown").lower(), + "options": { + "column": column, + "op": _MODERN_TO_LEGACY_OP.get(condition.get("op"), condition.get("op")), + "value": value, + "custom_body": stored.get("custom_body"), + "custom_subject": stored.get("custom_subject"), + }, + "rearm": stored.get("seconds_to_retrigger"), + "created_at": stored.get("create_time"), + "updated_at": stored.get("update_time"), + "last_triggered_at": stored.get("trigger_time"), + "user": {"id": 1, "name": identity.DISPLAY_NAME}, + } + + +def _legacy_to_alert(body: Dict[str, Any]) -> Dict[str, Any]: + """Translate a legacy alert body into modern alert fields.""" + mapped: Dict[str, Any] = {} + if "name" in body: + mapped["display_name"] = body["name"] + if "query_id" in body: + mapped["query_id"] = body["query_id"] + if "rearm" in body: + mapped["seconds_to_retrigger"] = body["rearm"] + + options = body.get("options") or {} + if options: + value = options.get("value") + threshold: Dict[str, Any] = {} + if isinstance(value, bool): + threshold["bool_value"] = value + elif isinstance(value, (int, float)): + threshold["double_value"] = float(value) + elif value is not None: + threshold["string_value"] = str(value) + + condition: Dict[str, Any] = {} + if options.get("op"): + legacy_op = options["op"] + condition["op"] = _LEGACY_TO_MODERN_OP.get(legacy_op, str(legacy_op).upper()) + if options.get("column"): + condition["operand"] = {"column": {"name": options["column"]}} + if threshold: + condition["threshold"] = {"value": threshold} + if condition: + mapped["condition"] = condition + + for legacy_key, modern_key in (("custom_body", "custom_body"), ("custom_subject", "custom_subject")): + if options.get(legacy_key) is not None: + mapped[modern_key] = options[legacy_key] + return mapped + + +# The legacy list endpoints are page-numbered, and the SDK walks them by incrementing +# `page` until a response comes back with an empty `results`. A handler that ignores the +# parameter and always returns everything therefore never terminates — the client loops +# forever on a full first page. Paging is not a nicety here; it is what ends the loop. +_DEFAULT_PAGE_SIZE = 25 + + +def _paginate(entries: list, page: Optional[int], page_size: Optional[int]) -> Dict[str, Any]: + size = page_size or _DEFAULT_PAGE_SIZE + number = page or 1 + if size < 1 or number < 1: + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message="page and page_size must be positive", + status_code=400, + ) + start = (number - 1) * size + return { + "count": len(entries), + "page": number, + "page_size": size, + "results": entries[start : start + size], + } + + +# ----------------------------------------------------------------------- queries + + +@router.post("/queries", response_model=None) +async def create_query_legacy(body: Dict[str, Any]) -> Dict[str, Any]: + """Create a saved query through the legacy route.""" + from minilake.models.saved_queries import CreateQueryRequest, CreateQueryRequestQuery + + mapped = _legacy_to_query(body) + created = await queries_service.create_query( + CreateQueryRequest(query=CreateQueryRequestQuery(**mapped), auto_resolve_display_name=True) + ) + return _query_to_legacy(queries_service._state["queries"][created.id]) + + +@router.get("/queries", response_model=None) +async def list_queries_legacy( + page: Optional[int] = QueryParam(None), + page_size: Optional[int] = QueryParam(None), +) -> Dict[str, Any]: + """List saved queries, page-numbered.""" + entries = [ + _query_to_legacy(e) for e in queries_service._state["queries"].values() if e.get("lifecycle_state") != "TRASHED" + ] + return _paginate(entries, page, page_size) + + +@router.get("/queries/{query_id}", response_model=None) +async def get_query_legacy(query_id: str) -> Dict[str, Any]: + """Get a saved query by ID.""" + return _query_to_legacy(queries_service._get_or_404(query_id)) + + +@router.post("/queries/{query_id}", response_model=None) +async def update_query_legacy(query_id: str, body: Dict[str, Any]) -> Dict[str, Any]: + """Update a saved query. Legacy uses POST for update, not PATCH.""" + stored = queries_service._get_or_404(query_id) + stored.update(_legacy_to_query(body)) + stored["update_time"] = _now_iso() + return _query_to_legacy(stored) + + +@router.delete("/queries/{query_id}") +async def trash_query_legacy(query_id: str) -> dict: + """Move a saved query to the trash. + + Note the asymmetry the legacy API actually has, which is easy to get backwards: + DELETE trashes, and POST to `trash/{id}` *restores*. A trashed query disappears + from both the legacy and the modern list but is still retrievable by id. + """ + stored = queries_service._get_or_404(query_id) + stored["lifecycle_state"] = "TRASHED" + return {} + + +@router.post("/queries/trash/{query_id}") +async def restore_query_legacy(query_id: str) -> dict: + """Restore a saved query from the trash.""" + stored = queries_service._get_or_404(query_id) + stored["lifecycle_state"] = "ACTIVE" + return {} + + +# ------------------------------------------------------------------------ alerts + + +@router.post("/alerts", response_model=None) +async def create_alert_legacy(body: Dict[str, Any]) -> Dict[str, Any]: + """Create an alert through the legacy route.""" + from minilake.models.alerts import AlertBase, CreateAlertRequest + + mapped = _legacy_to_alert(body) + created = await alerts_service.create_alert( + CreateAlertRequest(alert=AlertBase(**mapped), auto_resolve_display_name=True) + ) + return _alert_to_legacy(alerts_service._state["alerts"][created.id]) + + +@router.get("/alerts", response_model=None) +async def list_alerts_legacy() -> List[Dict[str, Any]]: + """List alerts. The legacy route returns a bare array, not an envelope.""" + return [_alert_to_legacy(a) for a in alerts_service._state["alerts"].values()] + + +@router.get("/alerts/{alert_id}", response_model=None) +async def get_alert_legacy(alert_id: str) -> Dict[str, Any]: + """Get an alert by ID.""" + return _alert_to_legacy(alerts_service.get_alert_or_404(alert_id)) + + +@router.put("/alerts/{alert_id}", response_model=None) +async def update_alert_legacy(alert_id: str, body: Dict[str, Any]) -> Dict[str, Any]: + """Update an alert. Legacy uses PUT.""" + stored = alerts_service.get_alert_or_404(alert_id) + stored.update(_legacy_to_alert(body)) + stored["update_time"] = _now_iso() + return _alert_to_legacy(stored) + + +@router.delete("/alerts/{alert_id}") +async def delete_alert_legacy(alert_id: str) -> dict: + """Delete an alert.""" + alerts_service.get_alert_or_404(alert_id) + del alerts_service._state["alerts"][alert_id] + return {} + + +# -------------------------------------------------------------------- dashboards + + +def _dashboard_or_404(dashboard_id: str) -> Dict[str, Any]: + stored = _state["dashboards"].get(dashboard_id) + if stored is None: + raise DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"Dashboard '{dashboard_id}' not found", + status_code=404, + ) + return stored + + +@router.post("/dashboards", response_model=None) +async def create_dashboard(body: Dict[str, Any]) -> Dict[str, Any]: + """Create a legacy SQL dashboard. Metadata only — nothing renders it.""" + dashboard_id = str(uuid.uuid4()) + now = _now_iso() + stored = { + **body, + "id": dashboard_id, + "slug": (body.get("name") or "dashboard").lower().replace(" ", "-"), + "widgets": [], + "created_at": now, + "updated_at": now, + "is_archived": False, + "is_draft": False, + "user_id": 1, + } + _state["dashboards"][dashboard_id] = stored + return stored + + +@router.get("/dashboards", response_model=None) +async def list_dashboards( + page: Optional[int] = QueryParam(None), + page_size: Optional[int] = QueryParam(None), +) -> Dict[str, Any]: + """List dashboards, page-numbered.""" + active = [d for d in _state["dashboards"].values() if not d.get("is_archived")] + return _paginate(active, page, page_size) + + +@router.get("/dashboards/{dashboard_id}", response_model=None) +async def get_dashboard(dashboard_id: str) -> Dict[str, Any]: + """Get a dashboard, including the widgets placed on it.""" + stored = _dashboard_or_404(dashboard_id) + return { + **stored, + "widgets": [w for w in _state["widgets"].values() if w.get("dashboard_id") == dashboard_id], + } + + +@router.post("/dashboards/{dashboard_id}", response_model=None) +async def update_dashboard(dashboard_id: str, body: Dict[str, Any]) -> Dict[str, Any]: + """Update a dashboard.""" + stored = _dashboard_or_404(dashboard_id) + stored.update(body) + stored["updated_at"] = _now_iso() + return stored + + +@router.delete("/dashboards/{dashboard_id}") +async def trash_dashboard(dashboard_id: str) -> dict: + """Move a dashboard to the trash. Its widgets go with it.""" + stored = _dashboard_or_404(dashboard_id) + stored["is_archived"] = True + return {} + + +@router.post("/dashboards/trash/{dashboard_id}") +async def restore_dashboard(dashboard_id: str) -> dict: + """Restore a dashboard from the trash.""" + stored = _dashboard_or_404(dashboard_id) + stored["is_archived"] = False + return {} + + +# ----------------------------------------------------------------------- widgets + + +@router.post("/widgets", response_model=None) +async def create_widget(body: Dict[str, Any]) -> Dict[str, Any]: + """Place a widget on a dashboard.""" + dashboard_id = body.get("dashboard_id") + if dashboard_id: + _dashboard_or_404(dashboard_id) + widget_id = str(uuid.uuid4()) + stored = {**body, "id": widget_id} + _state["widgets"][widget_id] = stored + return stored + + +@router.post("/widgets/{widget_id}", response_model=None) +async def update_widget(widget_id: str, body: Dict[str, Any]) -> Dict[str, Any]: + """Update a widget.""" + stored = _state["widgets"].get(widget_id) + if stored is None: + raise DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"Widget '{widget_id}' not found", + status_code=404, + ) + stored.update(body) + return stored + + +@router.delete("/widgets/{widget_id}") +async def delete_widget(widget_id: str) -> dict: + """Remove a widget.""" + if widget_id not in _state["widgets"]: + raise DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"Widget '{widget_id}' not found", + status_code=404, + ) + del _state["widgets"][widget_id] + return {} + + +# ---------------------------------------------------------------- visualizations + + +@router.post("/visualizations", response_model=None) +async def create_visualization(body: Dict[str, Any]) -> Dict[str, Any]: + """Attach a visualization to a query.""" + visualization_id = str(uuid.uuid4()) + stored = {**body, "id": visualization_id, "created_at": _now_iso()} + _state["visualizations"][visualization_id] = stored + return stored + + +@router.post("/visualizations/{visualization_id}", response_model=None) +async def update_visualization(visualization_id: str, body: Dict[str, Any]) -> Dict[str, Any]: + """Update a visualization.""" + stored = _state["visualizations"].get(visualization_id) + if stored is None: + raise DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"Visualization '{visualization_id}' not found", + status_code=404, + ) + stored.update(body) + return stored + + +@router.delete("/visualizations/{visualization_id}") +async def delete_visualization(visualization_id: str) -> dict: + """Delete a visualization.""" + if visualization_id not in _state["visualizations"]: + raise DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"Visualization '{visualization_id}' not found", + status_code=404, + ) + del _state["visualizations"][visualization_id] + return {} + + +# ------------------------------------------------------------------ data sources + + +@router.get("/data_sources", response_model=None) +async def list_data_sources() -> List[Dict[str, Any]]: + """List data sources. + + In the legacy model a "data source" is the handle a query uses to name its + warehouse, so this projects the real warehouses rather than inventing a list — + a legacy client picks an id here and uses it as `data_source_id`. + """ + from minilake.services import sql_warehouses + + return [ + { + "id": warehouse_id, + "name": record.get("name"), + "warehouse_id": warehouse_id, + "type": "databricks_internal", + "syntax": "sql", + "pause_reason": None, + "paused": 0, + } + for warehouse_id, record in sql_warehouses._state["warehouses"].items() + ] + + +# ============================================================================ +# State Management +# ============================================================================ + + +def get_state() -> Dict[str, Any]: + """Get state for snapshotting. + + Queries and alerts are owned by their modern services and snapshotted there; + only the objects with no modern home are ours to persist. + """ + return _state.copy() + + +def restore_state(data: Dict[str, Any]) -> None: + """Restore state from snapshot.""" + global _state + _state.update(data) + + +async def reset() -> None: + """Reset legacy dashboard/widget/visualization state.""" + global _state + _state = {"dashboards": {}, "widgets": {}, "visualizations": {}} diff --git a/src/minilake/services/saved_queries.py b/src/minilake/services/saved_queries.py index d0a165b..ebf7446 100644 --- a/src/minilake/services/saved_queries.py +++ b/src/minilake/services/saved_queries.py @@ -149,8 +149,13 @@ async def list_queries( page_size: Optional[int] = QueryParam(None), page_token: Optional[str] = QueryParam(None), ) -> ListQueryObjectsResponse: - """List saved queries, newest first.""" - entries: List[Dict[str, Any]] = list(_state["queries"].values()) + """List saved queries, newest first. + + A query the legacy API moved to the trash is hidden here too. There is one store + behind both surfaces, so a trashed query showing up in one list and not the other + would be two answers to the same question. + """ + entries: List[Dict[str, Any]] = [q for q in _state["queries"].values() if q.get("lifecycle_state") != "TRASHED"] entries.reverse() limit = page_size if page_size is not None else 100 diff --git a/src/minilake/services/scim.py b/src/minilake/services/scim.py index 2828a97..a16ad02 100644 --- a/src/minilake/services/scim.py +++ b/src/minilake/services/scim.py @@ -76,6 +76,29 @@ def _seed_current_user() -> None: _seed_current_user() +# SCIM lets a client narrow a response with `attributes` (return only these) or +# `excludedAttributes` (return everything but these). The Databricks Terraform provider +# reads a group with `?attributes=displayName,externalId,entitlements` and then maps the +# response into state field by field; handing it the full object instead makes it try to +# set a field it has no address for, and it fails with an opaque +# `Invalid address to set: []string{""}`. Honouring the parameter is what makes +# `databricks_group` work at all. +# +# `id` and `schemas` are always returned, as the spec requires. +_ALWAYS_RETURNED = {"id", "schemas"} + + +def _project(record: Dict[str, Any], attributes: Optional[str], excluded: Optional[str]) -> Dict[str, Any]: + """Apply SCIM `attributes` / `excludedAttributes` to one resource.""" + if attributes: + wanted = {a.strip() for a in attributes.split(",") if a.strip()} | _ALWAYS_RETURNED + return {k: v for k, v in record.items() if k in wanted} + if excluded: + unwanted = {a.strip() for a in excluded.split(",") if a.strip()} - _ALWAYS_RETURNED + return {k: v for k, v in record.items() if k not in unwanted} + return record + + def _config(resource: str) -> Tuple[Any, str, str, str]: return _RESOURCES[resource] @@ -106,12 +129,37 @@ def _unique_check(resource: str, value: Optional[str], exclude_id: Optional[str] ) +# Multi-valued SCIM attributes. An entry in one of these is meaningless without a +# `value`, and the real API drops the empty ones rather than storing them. +_MULTI_VALUED = ("entitlements", "roles", "groups", "members", "emails") + + +def _prune_empty(payload: Dict[str, Any]) -> Dict[str, Any]: + """Drop valueless entries from multi-valued attributes. + + The Databricks Terraform provider posts `"entitlements": [{}]` when a group has + none. Echoing that back breaks the provider on its own input — it maps each entry + into state and an entry with no value has no address, which surfaces as + `Invalid address to set: []string{""}`. Real Databricks drops the entry, so we do. + """ + for attribute in _MULTI_VALUED: + entries = payload.get(attribute) + if not isinstance(entries, list): + continue + kept = [e for e in entries if not isinstance(e, dict) or any(v is not None for v in e.values())] + if kept: + payload[attribute] = kept + else: + payload.pop(attribute, None) + return payload + + def _dump(model: Any, resource: str) -> Dict[str, Any]: """Serialise an incoming model to its wire shape, dropping unset fields.""" _model, schema, _unique, _label = _config(resource) payload = model.model_dump(by_alias=True, exclude_none=True) payload.setdefault("schemas", [schema]) - return payload + return _prune_empty(payload) # --------------------------------------------------------------------- filtering @@ -151,6 +199,8 @@ def _list( start_index: Optional[int], count: Optional[int], sort_by: Optional[str], + attributes: Optional[str] = None, + excluded: Optional[str] = None, ) -> ListResponse: entries = [s for s in _state[resource].values() if _matches_filter(s, scim_filter)] @@ -167,7 +217,7 @@ def _list( totalResults=len(entries), startIndex=start, itemsPerPage=len(page), - Resources=page, + Resources=[_project(r, attributes, excluded) for r in page], ) @@ -241,7 +291,7 @@ def _apply_patch(stored: Dict[str, Any], req: PatchRequest, resource: str) -> Di stored[path] = value _unique_check(resource, stored.get(_config(resource)[2]), exclude_id=stored.get("id")) - return stored + return _prune_empty(stored) def _as_list(value: Any) -> List[Any]: @@ -265,15 +315,21 @@ async def list_users( startIndex: Optional[int] = QueryParam(None), count: Optional[int] = QueryParam(None), sortBy: Optional[str] = QueryParam(None), + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), ) -> Dict[str, Any]: - """List users.""" - return _list("Users", filter, startIndex, count, sortBy).model_dump(by_alias=True) + """List, honouring SCIM filtering and attribute projection.""" + return _list("Users", filter, startIndex, count, sortBy, attributes, excludedAttributes).model_dump(by_alias=True) @router.get("/Users/{user_id}", response_model=None) -async def get_user(user_id: str) -> Dict[str, Any]: - """Get a user by ID.""" - return _get_or_404("Users", user_id) +async def get_user( + user_id: str, + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), +) -> Dict[str, Any]: + """Get by ID, honouring SCIM attribute projection.""" + return _project(_get_or_404("Users", user_id), attributes, excludedAttributes) @router.put("/Users/{user_id}", response_model=None) @@ -309,15 +365,21 @@ async def list_groups( startIndex: Optional[int] = QueryParam(None), count: Optional[int] = QueryParam(None), sortBy: Optional[str] = QueryParam(None), + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), ) -> Dict[str, Any]: - """List groups.""" - return _list("Groups", filter, startIndex, count, sortBy).model_dump(by_alias=True) + """List, honouring SCIM filtering and attribute projection.""" + return _list("Groups", filter, startIndex, count, sortBy, attributes, excludedAttributes).model_dump(by_alias=True) @router.get("/Groups/{group_id}", response_model=None) -async def get_group(group_id: str) -> Dict[str, Any]: - """Get a group by ID.""" - return _get_or_404("Groups", group_id) +async def get_group( + group_id: str, + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), +) -> Dict[str, Any]: + """Get by ID, honouring SCIM attribute projection.""" + return _project(_get_or_404("Groups", group_id), attributes, excludedAttributes) @router.put("/Groups/{group_id}", response_model=None) @@ -360,15 +422,23 @@ async def list_service_principals( startIndex: Optional[int] = QueryParam(None), count: Optional[int] = QueryParam(None), sortBy: Optional[str] = QueryParam(None), + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), ) -> Dict[str, Any]: - """List service principals.""" - return _list("ServicePrincipals", filter, startIndex, count, sortBy).model_dump(by_alias=True) + """List, honouring SCIM filtering and attribute projection.""" + return _list("ServicePrincipals", filter, startIndex, count, sortBy, attributes, excludedAttributes).model_dump( + by_alias=True + ) @router.get("/ServicePrincipals/{sp_id}", response_model=None) -async def get_service_principal(sp_id: str) -> Dict[str, Any]: - """Get a service principal by ID.""" - return _get_or_404("ServicePrincipals", sp_id) +async def get_service_principal( + sp_id: str, + attributes: Optional[str] = QueryParam(None), + excludedAttributes: Optional[str] = QueryParam(None), +) -> Dict[str, Any]: + """Get by ID, honouring SCIM attribute projection.""" + return _project(_get_or_404("ServicePrincipals", sp_id), attributes, excludedAttributes) @router.put("/ServicePrincipals/{sp_id}", response_model=None) diff --git a/src/minilake/services/sql_warehouses.py b/src/minilake/services/sql_warehouses.py index 28759ac..e37dbe4 100644 --- a/src/minilake/services/sql_warehouses.py +++ b/src/minilake/services/sql_warehouses.py @@ -8,6 +8,7 @@ from fastapi import APIRouter from minilake.app import get_duckdb_pool +from minilake.config import settings from minilake.errors import DatabricksError from minilake.models.sql import ( CreateWarehouseRequest, @@ -15,6 +16,7 @@ GetWarehouseResponse, ListWarehousesResponse, ) +from minilake.services import identity logger = logging.getLogger(__name__) @@ -32,6 +34,9 @@ async def create_warehouse(req: CreateWarehouseRequest) -> CreateWarehouseRespon warehouse_id = str(uuid.uuid4())[:8] now_ms = int(time.time() * 1000) + # Defaults match the real API's, because a client that omits a field reads back + # what Databricks would have defaulted it to — anything else is drift on the next + # plan. None of these values changes how a statement executes here. warehouse = { "id": warehouse_id, "name": req.name, @@ -40,6 +45,24 @@ async def create_warehouse(req: CreateWarehouseRequest) -> CreateWarehouseRespon "comment": req.comment, "created_at": now_ms, "updated_at": now_ms, + "auto_stop_mins": req.auto_stop_mins if req.auto_stop_mins is not None else 120, + "min_num_clusters": req.min_num_clusters if req.min_num_clusters is not None else 1, + "max_num_clusters": req.max_num_clusters if req.max_num_clusters is not None else 1, + "num_clusters": 1, + "enable_photon": req.enable_photon if req.enable_photon is not None else True, + "enable_serverless_compute": ( + req.enable_serverless_compute if req.enable_serverless_compute is not None else False + ), + "spot_instance_policy": req.spot_instance_policy or "COST_OPTIMIZED", + "warehouse_type": req.warehouse_type or "PRO", + "creator_name": identity.USER_NAME, + "odbc_params": { + "hostname": "localhost", + "host": "localhost", + "path": f"/sql/1.0/warehouses/{warehouse_id}", + "port": settings.port, + "protocol": "https" if settings.tls_enabled else "http", + }, } _state["warehouses"][warehouse_id] = warehouse diff --git a/src/minilake/services/workspace_admin.py b/src/minilake/services/workspace_admin.py new file mode 100644 index 0000000..c9ea386 --- /dev/null +++ b/src/minilake/services/workspace_admin.py @@ -0,0 +1,530 @@ +"""The small workspace-admin APIs: git credentials, IP access lists, global init +scripts, notification destinations, instance profiles and workspace conf. + +None of these is interesting on its own. Together they are the difference between +`terraform apply` completing against minilake and stopping at the first resource it +cannot create — a realistic workspace config touches most of them before it reaches a +catalog or a job, and a single 501 fails the whole plan. + +So: real CRUD, faithful round-trips, and no enforcement anywhere. No IP is ever +blocked, no init script ever runs, no notification is ever sent, and an instance +profile grants nothing. They are records, kept so the tools that expect them to exist +can carry on to the parts of minilake that do something. + +Two places where the shape matters more than it looks: + +- a git credential's `personal_access_token` is stored but never returned, matching + the real API — a client that reads one back and finds the token would be justified + in writing it somewhere; +- `list` for global init scripts omits the script body, and for notification + destinations omits `config`, because both can carry secrets. Returning the full + object from `list` would be the easy thing and the wrong one. +""" + +import base64 +import binascii +import logging +import time +import uuid +from typing import Any, Dict, Optional + +from fastapi import APIRouter +from fastapi import Query as QueryParam + +from minilake.errors import DatabricksError +from minilake.models.workspace_admin import ( + AddInstanceProfileRequest, + CreateCredentialRequest, + CreateGlobalInitScriptRequest, + CreateGlobalInitScriptResponse, + CreateIpAccessListRequest, + CredentialInfo, + EditInstanceProfileRequest, + GetIpAccessListsResponse, + GlobalInitScriptDetails, + InstanceProfile, + IpAccessListInfo, + IpAccessListResponse, + ListCredentialsResponse, + ListGlobalInitScriptsResponse, + ListInstanceProfilesResponse, + ListNotificationDestinationsResponse, + ListNotificationDestinationsResult, + NotificationDestination, + NotificationDestinationRequest, + RemoveInstanceProfileRequest, + UpdateCredentialRequest, + UpdateGlobalInitScriptRequest, + UpdateIpAccessListRequest, +) + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/2.0", tags=["workspace_admin"]) + + +def _new_state() -> Dict[str, Any]: + return { + "credentials": {}, # credential_id (int) -> record + "ip_access_lists": {}, # list_id -> record + "init_scripts": {}, # script_id -> record + "notification_destinations": {}, # id -> record + "instance_profiles": {}, # arn -> record + "workspace_conf": {}, # key -> value (always strings, as the real API returns) + "next_credential_id": 1, + } + + +_state: Dict[str, Any] = _new_state() + + +def _now_ms() -> int: + return int(time.time() * 1000) + + +def _not_found(what: str, which: str) -> DatabricksError: + return DatabricksError( + error_code="RESOURCE_DOES_NOT_EXIST", + message=f"{what} '{which}' not found", + status_code=404, + ) + + +# ------------------------------------------------------------------ git credentials + + +@router.post("/git-credentials", response_model=CredentialInfo) +async def create_credential(req: CreateCredentialRequest) -> CredentialInfo: + """Register a git credential.""" + if not req.git_provider: + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message="git_provider is required", + status_code=400, + ) + + credential_id = _state["next_credential_id"] + _state["next_credential_id"] += 1 + + record = { + **req.model_dump(exclude_none=True), + "credential_id": credential_id, + } + # Stored so an update can preserve it, never returned. + _state["credentials"][credential_id] = record + + logger.info(f"Created git credential {credential_id} ({req.git_provider})") + return _credential_info(record) + + +def _credential_info(record: Dict[str, Any]) -> CredentialInfo: + return CredentialInfo(**{k: v for k, v in record.items() if k != "personal_access_token"}) + + +@router.get("/git-credentials", response_model=ListCredentialsResponse) +async def list_credentials() -> ListCredentialsResponse: + """List git credentials.""" + return ListCredentialsResponse(credentials=[_credential_info(r) for r in _state["credentials"].values()]) + + +@router.get("/git-credentials/{credential_id}", response_model=CredentialInfo) +async def get_credential(credential_id: int) -> CredentialInfo: + """Get a git credential by ID.""" + record = _state["credentials"].get(credential_id) + if record is None: + raise _not_found("Git credential", str(credential_id)) + return _credential_info(record) + + +@router.patch("/git-credentials/{credential_id}") +async def update_credential(credential_id: int, req: UpdateCredentialRequest) -> dict: + """Update a git credential.""" + record = _state["credentials"].get(credential_id) + if record is None: + raise _not_found("Git credential", str(credential_id)) + record.update(req.model_dump(exclude_none=True)) + return {} + + +@router.delete("/git-credentials/{credential_id}") +async def delete_credential(credential_id: int) -> dict: + """Delete a git credential.""" + if credential_id not in _state["credentials"]: + raise _not_found("Git credential", str(credential_id)) + del _state["credentials"][credential_id] + return {} + + +# ------------------------------------------------------------------ IP access lists + +_LIST_TYPES = {"ALLOW", "BLOCK"} + + +def _validate_list_type(list_type: Optional[str]) -> Optional[str]: + if list_type is None: + return None + value = list_type.upper() + if value not in _LIST_TYPES: + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message=f"list_type must be one of: {', '.join(sorted(_LIST_TYPES))}", + status_code=400, + ) + return value + + +def _ip_list_info(record: Dict[str, Any]) -> IpAccessListInfo: + addresses = record.get("ip_addresses") or [] + return IpAccessListInfo(**{**record, "address_count": len(addresses)}) + + +@router.post("/ip-access-lists", response_model=IpAccessListResponse) +async def create_ip_access_list(req: CreateIpAccessListRequest) -> IpAccessListResponse: + """Create an IP access list. Nothing here ever blocks an address.""" + list_id = uuid.uuid4().hex[:16] + now = _now_ms() + record = { + "list_id": list_id, + "label": req.label, + "list_type": _validate_list_type(req.list_type), + "ip_addresses": req.ip_addresses or [], + "enabled": True, + "created_at": now, + "updated_at": now, + } + _state["ip_access_lists"][list_id] = record + logger.info(f"Created IP access list {list_id} ({req.label})") + return IpAccessListResponse(ip_access_list=_ip_list_info(record)) + + +@router.get("/ip-access-lists", response_model=GetIpAccessListsResponse) +async def list_ip_access_lists() -> GetIpAccessListsResponse: + """List IP access lists.""" + return GetIpAccessListsResponse(ip_access_lists=[_ip_list_info(r) for r in _state["ip_access_lists"].values()]) + + +@router.get("/ip-access-lists/{list_id}", response_model=IpAccessListResponse) +async def get_ip_access_list(list_id: str) -> IpAccessListResponse: + """Get an IP access list by ID.""" + record = _state["ip_access_lists"].get(list_id) + if record is None: + raise _not_found("IP access list", list_id) + return IpAccessListResponse(ip_access_list=_ip_list_info(record)) + + +@router.put("/ip-access-lists/{list_id}") +async def replace_ip_access_list(list_id: str, req: UpdateIpAccessListRequest) -> dict: + """Replace an IP access list.""" + record = _state["ip_access_lists"].get(list_id) + if record is None: + raise _not_found("IP access list", list_id) + record.update( + { + "label": req.label, + "list_type": _validate_list_type(req.list_type), + "ip_addresses": req.ip_addresses or [], + "enabled": req.enabled if req.enabled is not None else True, + "updated_at": _now_ms(), + } + ) + return {} + + +@router.patch("/ip-access-lists/{list_id}") +async def update_ip_access_list(list_id: str, req: UpdateIpAccessListRequest) -> dict: + """Partially update an IP access list.""" + record = _state["ip_access_lists"].get(list_id) + if record is None: + raise _not_found("IP access list", list_id) + updates = req.model_dump(exclude_none=True) + if "list_type" in updates: + updates["list_type"] = _validate_list_type(updates["list_type"]) + record.update({**updates, "updated_at": _now_ms()}) + return {} + + +@router.delete("/ip-access-lists/{list_id}") +async def delete_ip_access_list(list_id: str) -> dict: + """Delete an IP access list.""" + if list_id not in _state["ip_access_lists"]: + raise _not_found("IP access list", list_id) + del _state["ip_access_lists"][list_id] + return {} + + +# ------------------------------------------------------------- global init scripts + + +def _validate_script(script: Optional[str]) -> None: + """The script body is base64 in the real API. Reject a raw one rather than storing + something no cluster could ever decode.""" + if script is None: + return + try: + base64.b64decode(script, validate=True) + except (binascii.Error, ValueError): + raise DatabricksError( + error_code="INVALID_PARAMETER_VALUE", + message="script must be base64-encoded", + status_code=400, + ) + + +@router.post("/global-init-scripts", response_model=CreateGlobalInitScriptResponse) +async def create_init_script( + req: CreateGlobalInitScriptRequest, +) -> CreateGlobalInitScriptResponse: + """Register a global init script. It is never executed — clusters here are a state + machine with no compute to initialise.""" + _validate_script(req.script) + + script_id = uuid.uuid4().hex[:32].upper() + now = _now_ms() + _state["init_scripts"][script_id] = { + "script_id": script_id, + "name": req.name, + "script": req.script, + "position": req.position if req.position is not None else len(_state["init_scripts"]), + "enabled": req.enabled if req.enabled is not None else False, + "created_at": now, + "created_by": "minilake-user", + "updated_at": now, + "updated_by": "minilake-user", + } + logger.info(f"Created global init script {script_id} ({req.name})") + return CreateGlobalInitScriptResponse(script_id=script_id) + + +@router.get( + "/global-init-scripts", + response_model=ListGlobalInitScriptsResponse, + # Without this the omitted body still ships as `"script": null`, which is a + # different promise from "list does not return the body". + response_model_exclude_none=True, +) +async def list_init_scripts() -> ListGlobalInitScriptsResponse: + """List global init scripts, in execution order. The body is omitted here.""" + scripts = sorted(_state["init_scripts"].values(), key=lambda r: r.get("position") or 0) + return ListGlobalInitScriptsResponse( + scripts=[GlobalInitScriptDetails(**{k: v for k, v in r.items() if k != "script"}) for r in scripts] + ) + + +@router.get("/global-init-scripts/{script_id}", response_model=GlobalInitScriptDetails) +async def get_init_script(script_id: str) -> GlobalInitScriptDetails: + """Get a global init script, including its body.""" + record = _state["init_scripts"].get(script_id) + if record is None: + raise _not_found("Global init script", script_id) + return GlobalInitScriptDetails(**record) + + +@router.patch("/global-init-scripts/{script_id}") +async def update_init_script(script_id: str, req: UpdateGlobalInitScriptRequest) -> dict: + """Update a global init script.""" + record = _state["init_scripts"].get(script_id) + if record is None: + raise _not_found("Global init script", script_id) + _validate_script(req.script) + record.update({**req.model_dump(exclude_none=True), "updated_at": _now_ms()}) + return {} + + +@router.delete("/global-init-scripts/{script_id}") +async def delete_init_script(script_id: str) -> dict: + """Delete a global init script.""" + if script_id not in _state["init_scripts"]: + raise _not_found("Global init script", script_id) + del _state["init_scripts"][script_id] + return {} + + +# ------------------------------------------------------ notification destinations + + +def _destination_type(config: Optional[Dict[str, Any]]) -> Optional[str]: + """Infer the destination type from whichever config block is populated, which is + how the real API reports it — the client never sends the type directly.""" + for key, kind in ( + ("email", "EMAIL"), + ("slack", "SLACK"), + ("pagerduty", "PAGERDUTY"), + ("microsoft_teams", "MICROSOFT_TEAMS"), + ("generic_webhook", "GENERIC_WEBHOOK"), + ): + if (config or {}).get(key) is not None: + return kind + return None + + +@router.post("/notification-destinations", response_model=NotificationDestination) +async def create_notification_destination( + req: NotificationDestinationRequest, +) -> NotificationDestination: + """Create a notification destination. Nothing is ever sent to it.""" + destination_id = uuid.uuid4().hex[:16] + record = { + "id": destination_id, + "display_name": req.display_name, + "config": req.config, + "destination_type": _destination_type(req.config), + } + _state["notification_destinations"][destination_id] = record + logger.info(f"Created notification destination {destination_id} ({req.display_name})") + return NotificationDestination(**record) + + +@router.get("/notification-destinations", response_model=ListNotificationDestinationsResponse) +async def list_notification_destinations() -> ListNotificationDestinationsResponse: + """List notification destinations. `config` is omitted — it can carry secrets.""" + return ListNotificationDestinationsResponse( + results=[ + ListNotificationDestinationsResult( + id=r["id"], + display_name=r.get("display_name"), + destination_type=r.get("destination_type"), + ) + for r in _state["notification_destinations"].values() + ] + ) + + +@router.get("/notification-destinations/{destination_id}", response_model=NotificationDestination) +async def get_notification_destination(destination_id: str) -> NotificationDestination: + """Get a notification destination by ID.""" + record = _state["notification_destinations"].get(destination_id) + if record is None: + raise _not_found("Notification destination", destination_id) + return NotificationDestination(**record) + + +@router.patch("/notification-destinations/{destination_id}", response_model=NotificationDestination) +async def update_notification_destination( + destination_id: str, req: NotificationDestinationRequest +) -> NotificationDestination: + """Update a notification destination.""" + record = _state["notification_destinations"].get(destination_id) + if record is None: + raise _not_found("Notification destination", destination_id) + record.update(req.model_dump(exclude_none=True)) + if req.config is not None: + record["destination_type"] = _destination_type(req.config) + return NotificationDestination(**record) + + +@router.delete("/notification-destinations/{destination_id}") +async def delete_notification_destination(destination_id: str) -> dict: + """Delete a notification destination.""" + if destination_id not in _state["notification_destinations"]: + raise _not_found("Notification destination", destination_id) + del _state["notification_destinations"][destination_id] + return {} + + +# ---------------------------------------------------------------- instance profiles + + +@router.post("/instance-profiles/add") +async def add_instance_profile(req: AddInstanceProfileRequest) -> dict: + """Register an instance profile. It grants nothing — there is no AWS behind this.""" + arn = req.instance_profile_arn + if arn in _state["instance_profiles"]: + raise DatabricksError( + error_code="RESOURCE_ALREADY_EXISTS", + message=f"Instance profile '{arn}' is already registered", + status_code=400, + ) + _state["instance_profiles"][arn] = req.model_dump(exclude_none=True, exclude={"skip_validation"}) + return {} + + +@router.get("/instance-profiles/list", response_model=ListInstanceProfilesResponse) +async def list_instance_profiles() -> ListInstanceProfilesResponse: + """List registered instance profiles.""" + return ListInstanceProfilesResponse( + instance_profiles=[InstanceProfile(**r) for r in _state["instance_profiles"].values()] + ) + + +@router.post("/instance-profiles/edit") +async def edit_instance_profile(req: EditInstanceProfileRequest) -> dict: + """Edit a registered instance profile.""" + arn = req.instance_profile_arn + if arn not in _state["instance_profiles"]: + raise _not_found("Instance profile", arn) + _state["instance_profiles"][arn].update(req.model_dump(exclude_none=True)) + return {} + + +@router.post("/instance-profiles/remove") +async def remove_instance_profile(req: RemoveInstanceProfileRequest) -> dict: + """Deregister an instance profile.""" + if req.instance_profile_arn not in _state["instance_profiles"]: + raise _not_found("Instance profile", req.instance_profile_arn) + del _state["instance_profiles"][req.instance_profile_arn] + return {} + + +# ----------------------------------------------------------------- workspace conf + + +@router.get("/workspace-conf") +async def get_workspace_conf(keys: Optional[str] = QueryParam(None)) -> Dict[str, str]: + """Read workspace configuration keys. + + A flat string->string map, and the response is the map itself rather than a wrapper + — `databricks_workspace_conf` in Terraform reads it that way. An unset key comes + back as the empty string, not omitted, which is what lets Terraform see a key it + set and later cleared. + """ + if not keys: + return dict(_state["workspace_conf"]) + wanted = [k.strip() for k in keys.split(",") if k.strip()] + return {k: _state["workspace_conf"].get(k, "") for k in wanted} + + +@router.patch("/workspace-conf") +async def set_workspace_conf(body: Dict[str, Any]) -> dict: + """Set workspace configuration keys. + + Values are coerced to strings because the real API only ever stores and returns + strings — a client that PATCHes `true` and reads back `"true"` is seeing correct + behaviour, and one that reads back `true` here would break against Databricks. + """ + for key, value in body.items(): + _state["workspace_conf"][key] = _as_conf_string(value) + return {} + + +def _as_conf_string(value: Any) -> str: + if isinstance(value, bool): + return "true" if value else "false" + return "" if value is None else str(value) + + +# ============================================================================ +# State Management +# ============================================================================ + + +def get_state() -> Dict[str, Any]: + """Get state for snapshotting.""" + return _state.copy() + + +def restore_state(data: Dict[str, Any]) -> None: + """Restore state from snapshot. + + Git credential ids are ints, and a JSON round-trip turns dict keys into strings. + Rebuild them, or a restored credential is unreachable by the id it reports. + """ + global _state + _state.update(data) + credentials = _state.get("credentials") or {} + _state["credentials"] = {int(k): v for k, v in credentials.items()} + + +async def reset() -> None: + """Reset workspace-admin state.""" + global _state + _state = _new_state() diff --git a/tests/terraform/main.tf b/tests/terraform/main.tf new file mode 100644 index 0000000..f5c12cb --- /dev/null +++ b/tests/terraform/main.tf @@ -0,0 +1,99 @@ +# A deliberately ordinary workspace: the resources a real Terraform config touches +# before it reaches anything interesting. Nothing here is exotic — that is the point. +# +# The provider reads DATABRICKS_HOST and DATABRICKS_TOKEN from the environment, which +# the test sets, so this file needs no templating. + +terraform { + required_providers { + databricks = { + source = "databricks/databricks" + } + } +} + +provider "databricks" {} + +resource "databricks_catalog" "sandbox" { + name = "tf_sandbox" + comment = "Managed by Terraform" + force_destroy = true +} + +resource "databricks_schema" "things" { + catalog_name = databricks_catalog.sandbox.name + name = "things" + force_destroy = true +} + +resource "databricks_sql_endpoint" "compute" { + name = "tf-warehouse" + cluster_size = "Small" +} + +resource "databricks_group" "engineers" { + display_name = "tf-engineers" +} + +resource "databricks_user" "alice" { + user_name = "alice@tf.local" + display_name = "Alice" +} + +resource "databricks_group_member" "alice_in_engineers" { + group_id = databricks_group.engineers.id + member_id = databricks_user.alice.id +} + +resource "databricks_service_principal" "ci" { + display_name = "tf-ci-bot" +} + +resource "databricks_token" "pat" { + comment = "tf-managed" + lifetime_seconds = 3600 +} + +resource "databricks_secret_scope" "app" { + name = "tf-app" +} + +resource "databricks_secret" "api_key" { + key = "api_key" + string_value = "s3cr3t" + scope = databricks_secret_scope.app.name +} + +resource "databricks_secret_acl" "engineers_read" { + principal = databricks_group.engineers.display_name + permission = "READ" + scope = databricks_secret_scope.app.name +} + +resource "databricks_grants" "sandbox" { + catalog = databricks_catalog.sandbox.name + grant { + principal = databricks_group.engineers.display_name + privileges = ["USE_CATALOG", "SELECT"] + } +} + +resource "databricks_cluster_policy" "small" { + name = "tf-small" + definition = jsonencode({ + node_type_id = { type = "fixed", value = "local" } + }) +} + +resource "databricks_instance_pool" "warm" { + instance_pool_name = "tf-pool" + node_type_id = "local" + min_idle_instances = 0 + idle_instance_autotermination_minutes = 10 +} + +resource "databricks_git_credential" "github" { + git_provider = "gitHub" + git_username = "tf-user" + personal_access_token = "ghp_not_a_real_token" +} diff --git a/tests/terraform/test_terraform_conformance.py b/tests/terraform/test_terraform_conformance.py new file mode 100644 index 0000000..b8f5c0a --- /dev/null +++ b/tests/terraform/test_terraform_conformance.py @@ -0,0 +1,161 @@ +"""End-to-end conformance: does the real Databricks Terraform provider work? + +`docs/terraform.md` promises that `terraform apply` works against minilake. Nothing +verified that until this file, and the gap mattered: the first run of this test found +three defects that every SDK-driven test in the suite had missed, because they were in +behaviour only the provider exercises — + +- the provider posts `"entitlements": [{}]` for a group with none, and minilake echoed + the empty entry back, which broke the provider on its own input; +- SQL warehouses did not report `auto_stop_mins`, `enable_photon`, `max_num_clusters` + or `odbc_params`, so every `terraform plan` showed a permanent in-place update; +- SCIM ignored the `attributes` projection the provider asks for. + +The assertions are deliberately coarse — apply succeeds, a second plan is empty, +destroy succeeds — because that is what a user actually cares about, and anything +finer would just restate the config. The empty plan is the sharp one: it is what +proves minilake reports back what it was told, which is the whole contract Terraform +depends on. +""" + +import json +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +CONFIG = Path(__file__).parent / "main.tf" + +# `terraform init` resolves providers from the registry unless it is pointed at a local +# mirror. The test image bakes one (see Dockerfile.test); without it `init` falls back to +# the network, which works locally and is why this is a fallback rather than a skip. +PROVIDER_MIRROR = os.environ.get("MINILAKE_TF_PROVIDER_MIRROR") + +pytestmark = [pytest.mark.serial, pytest.mark.workflow] + + +def _terraform() -> str: + binary = shutil.which("terraform") + if not binary: + pytest.skip("terraform is not installed; see Dockerfile.test") + return binary + + +def _run(binary: str, args: list[str], cwd: Path, env: dict) -> subprocess.CompletedProcess: + """Run one terraform command, surfacing its output on failure.""" + result = subprocess.run( + [binary, *args, "-no-color"], + cwd=cwd, + env=env, + capture_output=True, + text=True, + timeout=600, + ) + if result.returncode not in (0, 2): # 2 is `plan -detailed-exitcode` "has changes" + raise AssertionError( + f"terraform {' '.join(args)} failed ({result.returncode})\n" + f"--- stdout ---\n{result.stdout}\n--- stderr ---\n{result.stderr}" + ) + return result + + +@pytest.fixture +def workspace(tmp_path: Path, minilake_server: str) -> tuple[str, Path, dict]: + """An initialised Terraform working directory pointed at minilake.""" + binary = _terraform() + + work = tmp_path / "tf" + work.mkdir() + shutil.copy(CONFIG, work / "main.tf") + + env = { + **os.environ, + "DATABRICKS_HOST": minilake_server, + "DATABRICKS_TOKEN": "terraform-conformance", + # Keep the provider from looking for a CLI profile or cloud metadata. + "DATABRICKS_CONFIG_FILE": os.devnull, + "TF_IN_AUTOMATION": "1", + "TF_INPUT": "0", + } + + init = ["init"] + if PROVIDER_MIRROR and Path(PROVIDER_MIRROR).is_dir(): + init.append(f"-plugin-dir={PROVIDER_MIRROR}") + # -plugin-dir and a plugin cache pointing at the same tree make terraform try + # to install the provider into the directory it is reading it from. + env.pop("TF_PLUGIN_CACHE_DIR", None) + _run(binary, init, work, env) + + yield binary, work, env + + # Always try to tear down, so a failed assertion does not leave the next test a + # workspace full of half-created resources. + _run(binary, ["destroy", "-auto-approve"], work, env) + + +def test_terraform_apply_is_idempotent_and_destroys(workspace): + """apply -> plan (empty) -> destroy, against a realistic config. + + The empty second plan is the real assertion. A resource minilake accepts but + reports back differently shows up here as permanent drift, which is worse than a + 501: it looks like it works until someone runs plan twice. + """ + binary, work, env = workspace + + applied = _run(binary, ["apply", "-auto-approve"], work, env) + assert "Apply complete!" in applied.stdout + + planned = _run(binary, ["plan", "-detailed-exitcode"], work, env) + assert planned.returncode == 0, ( + "terraform plan reported drift immediately after apply — minilake is not " + f"reporting back what it was given:\n{planned.stdout}" + ) + + destroyed = _run(binary, ["destroy", "-auto-approve"], work, env) + assert "Destroy complete!" in destroyed.stdout + + +def test_terraform_state_matches_minilake(workspace, workspace_client): + """What Terraform recorded and what minilake holds must be the same workspace. + + A provider can report success while writing state that does not match the server — + this reads both sides and compares them, which `plan` alone would not catch if + minilake echoed the request body without storing it. + """ + binary, work, env = workspace + _run(binary, ["apply", "-auto-approve"], work, env) + + state = json.loads(_run(binary, ["show", "-json"], work, env).stdout) + resources = {r["address"]: r["values"] for r in state["values"]["root_module"]["resources"]} + + # Unity Catalog + assert resources["databricks_catalog.sandbox"]["name"] == "tf_sandbox" + assert workspace_client.catalogs.get(name="tf_sandbox").name == "tf_sandbox" + assert workspace_client.schemas.get(full_name="tf_sandbox.things").name == "things" + + # SCIM — the group, the user, and the membership between them + group_id = resources["databricks_group.engineers"]["id"] + group = workspace_client.groups.get(id=group_id) + assert group.display_name == "tf-engineers" + member_ids = {m.value for m in (group.members or [])} + assert resources["databricks_user.alice"]["id"] in member_ids + + # Grants, including the privileges Terraform declared + grants = workspace_client.grants.get(securable_type="CATALOG", full_name="tf_sandbox") + granted = {a.principal: {p.value for p in a.privileges} for a in grants.privilege_assignments} + assert granted["tf-engineers"] == {"USE_CATALOG", "SELECT"} + + # Secret scope, its secret, and the ACL on it + scopes = {s.name for s in workspace_client.secrets.list_scopes()} + assert "tf-app" in scopes + acls = {a.principal: a.permission.value for a in workspace_client.secrets.list_acls(scope="tf-app")} + assert acls["tf-engineers"] == "READ" + + # Compute-adjacent resources that only had to resolve, not run + assert resources["databricks_cluster_policy.small"]["name"] == "tf-small" + assert resources["databricks_instance_pool.warm"]["instance_pool_name"] == "tf-pool" + + # The git credential's token must not come back — the provider would store it. + assert not resources["databricks_git_credential.github"].get("personal_access_token_wo") diff --git a/tests/test_preview_sql.py b/tests/test_preview_sql.py new file mode 100644 index 0000000..279f8fd --- /dev/null +++ b/tests/test_preview_sql.py @@ -0,0 +1,181 @@ +"""Legacy `/api/2.0/preview/sql/*` tests. + +Driven through `w.queries_legacy`, `w.alerts_legacy`, `w.dashboards` and +`w.data_sources`. + +The point of these endpoints is that they are *adapters*, not a second store. So the +assertions that matter most are the cross-surface ones: an object created through the +legacy route must be visible and editable through the modern one, and vice versa. A +second implementation would pass every single-surface test in this file and still be +wrong. + +Two details caught here that are easy to get backwards: + +- `DELETE` moves to trash and `POST .../trash/{id}` *restores*. Implemented the other + way round, a client asking to restore would delete instead. +- The list endpoints are page-numbered and the SDK walks them until a page comes back + empty, so a handler that ignores `page` never terminates. `test_legacy_query_list_ + paginates` is what stops that regressing into a hung test suite. +""" + +import pytest +from databricks.sdk import WorkspaceClient +from databricks.sdk.errors import DatabricksError +from databricks.sdk.service.sql import AlertOptions, CreateQueryRequestQuery + + +@pytest.fixture +def warehouse(workspace_client: WorkspaceClient) -> str: + return workspace_client.warehouses.create(name="legacy_wh", cluster_size="Small").id + + +@pytest.fixture +def legacy_query(workspace_client: WorkspaceClient, warehouse: str): + return workspace_client.queries_legacy.create(name="legacy q", query="SELECT 1 AS n", data_source_id=warehouse) + + +# ---------------------------------------------------------------- one shared store + + +@pytest.mark.crud +def test_legacy_query_is_visible_to_the_modern_api(workspace_client: WorkspaceClient, legacy_query): + """Created through the legacy route, read through the modern one.""" + modern = workspace_client.queries.get(id=legacy_query.id) + assert modern.display_name == "legacy q" + assert modern.query_text == "SELECT 1 AS n" + + +@pytest.mark.crud +def test_modern_query_is_visible_to_the_legacy_api(workspace_client: WorkspaceClient, warehouse: str): + """And the other direction.""" + workspace_client.queries.create( + query=CreateQueryRequestQuery(display_name="modern q", query_text="SELECT 2", warehouse_id=warehouse) + ) + assert "modern q" in {q.name for q in workspace_client.queries_legacy.list()} + + +@pytest.mark.crud +def test_legacy_update_is_seen_by_the_modern_api(workspace_client: WorkspaceClient, legacy_query): + workspace_client.queries_legacy.update(query_id=legacy_query.id, name="renamed", query="SELECT 3") + modern = workspace_client.queries.get(id=legacy_query.id) + assert modern.display_name == "renamed" + assert modern.query_text == "SELECT 3" + + +# ------------------------------------------------------------------------- trash + + +@pytest.mark.crud +def test_query_trash_and_restore(workspace_client: WorkspaceClient, legacy_query): + """DELETE trashes; POST to trash/{id} restores. Getting this backwards would make + a restore destroy the thing it was meant to bring back.""" + workspace_client.queries_legacy.delete(query_id=legacy_query.id) + + assert legacy_query.id not in {q.id for q in workspace_client.queries_legacy.list()} + assert legacy_query.id not in {q.id for q in workspace_client.queries.list()} + # Trashed, not gone. + assert workspace_client.queries.get(id=legacy_query.id).display_name == "legacy q" + + workspace_client.queries_legacy.restore(query_id=legacy_query.id) + assert legacy_query.id in {q.id for q in workspace_client.queries_legacy.list()} + + +# -------------------------------------------------------------------- pagination + + +@pytest.mark.crud +def test_legacy_query_list_paginates(workspace_client: WorkspaceClient, warehouse: str): + """The SDK increments `page` until a response is empty. A handler that returns + everything on every page never terminates — this test would hang, not fail.""" + for index in range(5): + workspace_client.queries_legacy.create(name=f"q{index}", query="SELECT 1", data_source_id=warehouse) + + assert len({q.name for q in workspace_client.queries_legacy.list()}) == 5 + + first_page = workspace_client.api_client.do( + "GET", "/api/2.0/preview/sql/queries", query={"page": 1, "page_size": 2} + ) + assert len(first_page["results"]) == 2 + assert first_page["count"] == 5 + + third_page = workspace_client.api_client.do( + "GET", "/api/2.0/preview/sql/queries", query={"page": 3, "page_size": 2} + ) + assert len(third_page["results"]) == 1 + + +# ------------------------------------------------------------------------ alerts + + +@pytest.mark.crud +def test_legacy_alert_translates_the_operator(workspace_client: WorkspaceClient, legacy_query): + """Legacy sends `>`; the modern store and the evaluator expect GREATER_THAN. An + untranslated symbol leaves an alert that silently never fires.""" + created = workspace_client.alerts_legacy.create( + name="legacy alert", + query_id=legacy_query.id, + options=AlertOptions(column="n", op=">", value=5), + ) + + modern = workspace_client.alerts.get(id=created.id) + assert modern.display_name == "legacy alert" + assert modern.condition.op.value == "GREATER_THAN" + assert modern.condition.operand.column.name == "n" + assert modern.condition.threshold.value.double_value == 5 + + +@pytest.mark.crud +def test_legacy_alert_reads_back_the_symbol(workspace_client: WorkspaceClient, legacy_query): + """And the translation is symmetric — the legacy reader gets its symbol back.""" + created = workspace_client.alerts_legacy.create( + name="symmetric", + query_id=legacy_query.id, + options=AlertOptions(column="n", op=">=", value=1), + ) + assert workspace_client.alerts_legacy.get(alert_id=created.id).options.op == ">=" + + +@pytest.mark.crud +def test_legacy_alert_delete(workspace_client: WorkspaceClient, legacy_query): + created = workspace_client.alerts_legacy.create( + name="doomed", query_id=legacy_query.id, options=AlertOptions(column="n", op=">", value=1) + ) + workspace_client.alerts_legacy.delete(alert_id=created.id) + with pytest.raises(DatabricksError): + workspace_client.alerts.get(id=created.id) + + +# -------------------------------------------------------------------- dashboards + + +@pytest.fixture +def dashboard(workspace_client: WorkspaceClient): + """Created through the raw client: the SDK's DashboardsAPI has no `create`.""" + return workspace_client.api_client.do("POST", "/api/2.0/preview/sql/dashboards", body={"name": "board"}) + + +@pytest.mark.crud +def test_dashboard_list_and_get(workspace_client: WorkspaceClient, dashboard): + assert "board" in {d.name for d in workspace_client.dashboards.list()} + assert workspace_client.dashboards.get(dashboard_id=dashboard["id"]).name == "board" + + +@pytest.mark.crud +def test_dashboard_trash_and_restore(workspace_client: WorkspaceClient, dashboard): + workspace_client.dashboards.delete(dashboard_id=dashboard["id"]) + assert "board" not in {d.name for d in workspace_client.dashboards.list()} + + workspace_client.dashboards.restore(dashboard_id=dashboard["id"]) + assert "board" in {d.name for d in workspace_client.dashboards.list()} + + +# ------------------------------------------------------------------ data sources + + +@pytest.mark.crud +def test_data_sources_project_real_warehouses(workspace_client: WorkspaceClient, warehouse: str): + """A legacy client picks an id here and uses it as `data_source_id`, so the list + has to be the real warehouses rather than an invented one.""" + sources = {ds.id: ds.name for ds in workspace_client.data_sources.list()} + assert warehouse in sources + assert sources[warehouse] == "legacy_wh" diff --git a/tests/test_workspace_admin.py b/tests/test_workspace_admin.py new file mode 100644 index 0000000..c62270c --- /dev/null +++ b/tests/test_workspace_admin.py @@ -0,0 +1,238 @@ +"""Tests for the small workspace-admin APIs Terraform reaches for. + +Git credentials, IP access lists, global init scripts, notification destinations, +instance profiles and workspace conf. None of these enforces anything — the value is +that they round-trip, because a `terraform apply` stops at the first resource it cannot +create, and a resource that reads back differently from what was written shows up as +permanent drift. + +Two behaviours here are load-bearing rather than cosmetic, and both have their own +test: a git credential's token must never come back, and `list` must omit the fields +that can carry secrets. +""" + +import base64 + +import pytest +from databricks.sdk import WorkspaceClient +from databricks.sdk.errors import DatabricksError +from databricks.sdk.service.settings import Config, EmailConfig, ListType + +# ------------------------------------------------------------------ git credentials + + +@pytest.mark.crud +def test_create_and_get_git_credential(workspace_client: WorkspaceClient): + created = workspace_client.git_credentials.create( + git_provider="gitHub", git_username="me", personal_access_token="ghp_secret" + ) + assert created.credential_id + assert created.git_provider == "gitHub" + + fetched = workspace_client.git_credentials.get(credential_id=created.credential_id) + assert fetched.git_username == "me" + + +@pytest.mark.crud +def test_git_credential_never_returns_the_token(workspace_client: WorkspaceClient): + """The real API does not echo the token back, and neither may this — a client that + read one here would be justified in persisting it somewhere.""" + created = workspace_client.git_credentials.create( + git_provider="gitHub", git_username="me", personal_access_token="ghp_secret" + ) + + raw = workspace_client.api_client.do("GET", f"/api/2.0/git-credentials/{created.credential_id}") + assert "personal_access_token" not in raw + + listed = workspace_client.api_client.do("GET", "/api/2.0/git-credentials") + assert all("personal_access_token" not in c for c in listed.get("credentials", [])) + + +@pytest.mark.crud +def test_update_and_delete_git_credential(workspace_client: WorkspaceClient): + created = workspace_client.git_credentials.create(git_provider="gitHub", git_username="me") + workspace_client.git_credentials.update( + credential_id=created.credential_id, git_provider="gitHub", git_username="renamed" + ) + assert workspace_client.git_credentials.get(credential_id=created.credential_id).git_username == "renamed" + + workspace_client.git_credentials.delete(credential_id=created.credential_id) + with pytest.raises(DatabricksError): + workspace_client.git_credentials.get(credential_id=created.credential_id) + + +# ------------------------------------------------------------------ IP access lists + + +@pytest.mark.crud +def test_create_and_get_ip_access_list(workspace_client: WorkspaceClient): + created = workspace_client.ip_access_lists.create( + label="office", list_type=ListType.ALLOW, ip_addresses=["1.2.3.4", "5.6.7.8"] + ) + info = created.ip_access_list + assert info.list_id + assert info.address_count == 2, "address_count is derived, not stored" + assert info.enabled is True + + fetched = workspace_client.ip_access_lists.get(ip_access_list_id=info.list_id).ip_access_list + assert fetched.label == "office" + assert fetched.list_type == ListType.ALLOW + + +@pytest.mark.crud +def test_replace_and_delete_ip_access_list(workspace_client: WorkspaceClient): + created = workspace_client.ip_access_lists.create(label="temp", list_type=ListType.BLOCK, ip_addresses=["9.9.9.9"]) + list_id = created.ip_access_list.list_id + + workspace_client.ip_access_lists.replace( + ip_access_list_id=list_id, + label="replaced", + list_type=ListType.ALLOW, + ip_addresses=["1.1.1.1"], + enabled=False, + ) + fetched = workspace_client.ip_access_lists.get(ip_access_list_id=list_id).ip_access_list + assert fetched.label == "replaced" + assert fetched.enabled is False + assert fetched.address_count == 1 + + workspace_client.ip_access_lists.delete(ip_access_list_id=list_id) + assert list_id not in {x.list_id for x in workspace_client.ip_access_lists.list()} + + +@pytest.mark.error +def test_invalid_list_type_rejected(workspace_client: WorkspaceClient): + with pytest.raises(DatabricksError) as exc: + workspace_client.api_client.do( + "POST", + "/api/2.0/ip-access-lists", + body={"label": "bad", "list_type": "MAYBE", "ip_addresses": []}, + ) + assert "list_type" in str(exc.value) + + +# ------------------------------------------------------------- global init scripts + + +@pytest.mark.crud +def test_create_and_get_init_script(workspace_client: WorkspaceClient): + body = base64.b64encode(b"echo hello").decode() + created = workspace_client.global_init_scripts.create(name="setup", script=body) + assert created.script_id + + fetched = workspace_client.global_init_scripts.get(script_id=created.script_id) + assert fetched.name == "setup" + assert fetched.script == body, "get returns the body" + assert fetched.enabled is False, "scripts are created disabled, as in the real API" + + +@pytest.mark.crud +def test_list_init_scripts_omits_the_body(workspace_client: WorkspaceClient): + """The body can carry secrets, so `list` must not include it.""" + workspace_client.global_init_scripts.create(name="setup", script=base64.b64encode(b"export TOKEN=hunter2").decode()) + raw = workspace_client.api_client.do("GET", "/api/2.0/global-init-scripts") + assert all("script" not in s for s in raw.get("scripts", [])) + + +@pytest.mark.crud +def test_init_scripts_list_in_position_order(workspace_client: WorkspaceClient): + for name, position in (("third", 2), ("first", 0), ("second", 1)): + workspace_client.global_init_scripts.create( + name=name, script=base64.b64encode(b"true").decode(), position=position + ) + names = [s.name for s in workspace_client.global_init_scripts.list()] + assert names == ["first", "second", "third"] + + +@pytest.mark.error +def test_non_base64_script_rejected(workspace_client: WorkspaceClient): + """A raw script would be stored as something no cluster could decode.""" + with pytest.raises(DatabricksError) as exc: + workspace_client.global_init_scripts.create(name="raw", script="echo not-base64!!") + assert "base64" in str(exc.value).lower() + + +# ------------------------------------------------------ notification destinations + + +@pytest.mark.crud +def test_create_notification_destination_infers_type(workspace_client: WorkspaceClient): + """The client never sends the type; it is inferred from the populated config block.""" + created = workspace_client.notification_destinations.create( + display_name="oncall", config=Config(email=EmailConfig(addresses=["a@b.c"])) + ) + assert created.id + assert created.destination_type.value == "EMAIL" + + fetched = workspace_client.notification_destinations.get(id=created.id) + assert fetched.display_name == "oncall" + + +@pytest.mark.crud +def test_list_notification_destinations_omits_config(workspace_client: WorkspaceClient): + """Config can carry webhook URLs and tokens, so `list` omits it.""" + workspace_client.notification_destinations.create( + display_name="oncall", config=Config(email=EmailConfig(addresses=["a@b.c"])) + ) + raw = workspace_client.api_client.do("GET", "/api/2.0/notification-destinations") + assert all("config" not in d for d in raw.get("results", [])) + + +@pytest.mark.crud +def test_update_and_delete_notification_destination(workspace_client: WorkspaceClient): + created = workspace_client.notification_destinations.create( + display_name="before", config=Config(email=EmailConfig(addresses=["a@b.c"])) + ) + workspace_client.notification_destinations.update(id=created.id, display_name="after") + assert workspace_client.notification_destinations.get(id=created.id).display_name == "after" + + workspace_client.notification_destinations.delete(id=created.id) + with pytest.raises(DatabricksError): + workspace_client.notification_destinations.get(id=created.id) + + +# ---------------------------------------------------------------- instance profiles + + +@pytest.mark.crud +def test_add_list_and_remove_instance_profile(workspace_client: WorkspaceClient): + arn = "arn:aws:iam::123456789012:instance-profile/minilake" + workspace_client.instance_profiles.add(instance_profile_arn=arn) + + assert arn in {p.instance_profile_arn for p in workspace_client.instance_profiles.list()} + + workspace_client.instance_profiles.remove(instance_profile_arn=arn) + assert arn not in {p.instance_profile_arn for p in workspace_client.instance_profiles.list()} + + +@pytest.mark.error +def test_duplicate_instance_profile_rejected(workspace_client: WorkspaceClient): + arn = "arn:aws:iam::123456789012:instance-profile/dupe" + workspace_client.instance_profiles.add(instance_profile_arn=arn) + with pytest.raises(DatabricksError) as exc: + workspace_client.instance_profiles.add(instance_profile_arn=arn) + assert "already registered" in str(exc.value).lower() + + +# ----------------------------------------------------------------- workspace conf + + +@pytest.mark.crud +def test_workspace_conf_round_trip(workspace_client: WorkspaceClient): + workspace_client.workspace_conf.set_status({"enableIpAccessLists": "true"}) + assert workspace_client.workspace_conf.get_status(keys="enableIpAccessLists") == {"enableIpAccessLists": "true"} + + +@pytest.mark.crud +def test_workspace_conf_values_are_strings(workspace_client: WorkspaceClient): + """The real API only ever stores strings; a client reading back a bool here would + break against Databricks.""" + workspace_client.api_client.do("PATCH", "/api/2.0/workspace-conf", body={"maxTokenLifetimeDays": 90}) + value = workspace_client.workspace_conf.get_status(keys="maxTokenLifetimeDays") + assert value == {"maxTokenLifetimeDays": "90"} + + +@pytest.mark.crud +def test_unset_workspace_conf_key_is_empty_string(workspace_client: WorkspaceClient): + """Omitting the key would hide from Terraform that a value it set is now gone.""" + assert workspace_client.workspace_conf.get_status(keys="neverSet") == {"neverSet": ""} diff --git a/tests/unity_catalog/test_grants.py b/tests/unity_catalog/test_grants.py new file mode 100644 index 0000000..321fbcc --- /dev/null +++ b/tests/unity_catalog/test_grants.py @@ -0,0 +1,163 @@ +"""Unity Catalog grant tests. + +Driven through `w.grants.*`. Grants are recorded and never enforced here, so the +behaviour worth testing is what a client can *observe*: that a delta round-trips, that +dropping the last privilege drops the principal, and above all that inheritance works — +`get_effective` is a separate endpoint from `get` precisely because it walks up the +hierarchy, and a version that just echoed the direct grants would look right while +being useless. +""" + +import pytest +from databricks.sdk import WorkspaceClient +from databricks.sdk.errors import DatabricksError +from databricks.sdk.service.catalog import PermissionsChange, Privilege, SecurableType + + +def _privileges(response) -> dict: + return {a.principal: {p.value for p in a.privileges} for a in response.privilege_assignments} + + +@pytest.mark.crud +def test_grant_and_read_back(workspace_client: WorkspaceClient, catalog): + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal="data-eng", add=[Privilege.USE_CATALOG, Privilege.SELECT])], + ) + + granted = _privileges(workspace_client.grants.get(securable_type=SecurableType.CATALOG, full_name=catalog.name)) + assert granted == {"data-eng": {"USE_CATALOG", "SELECT"}} + + +@pytest.mark.crud +def test_removing_last_privilege_drops_the_principal(workspace_client: WorkspaceClient, catalog): + """A principal holding nothing is not listed with an empty set — it is not listed.""" + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal="temp", add=[Privilege.USE_CATALOG])], + ) + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal="temp", remove=[Privilege.USE_CATALOG])], + ) + + granted = _privileges(workspace_client.grants.get(securable_type=SecurableType.CATALOG, full_name=catalog.name)) + assert "temp" not in granted + + +@pytest.mark.crud +def test_add_and_remove_in_one_call(workspace_client: WorkspaceClient, catalog): + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal="mixed", add=[Privilege.USE_CATALOG, Privilege.SELECT])], + ) + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal="mixed", add=[Privilege.MODIFY], remove=[Privilege.SELECT])], + ) + + granted = _privileges(workspace_client.grants.get(securable_type=SecurableType.CATALOG, full_name=catalog.name)) + assert granted["mixed"] == {"USE_CATALOG", "MODIFY"} + + +@pytest.mark.crud +def test_filter_by_principal(workspace_client: WorkspaceClient, catalog): + for principal in ("one", "two"): + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(principal=principal, add=[Privilege.USE_CATALOG])], + ) + + only = workspace_client.grants.get(securable_type=SecurableType.CATALOG, full_name=catalog.name, principal="one") + assert set(_privileges(only)) == {"one"} + + +# -------------------------------------------------------------------- inheritance + + +@pytest.mark.crud +def test_effective_permissions_inherit_from_catalog(workspace_client: WorkspaceClient, catalog_and_schema): + """A grant on the catalog reaches the schema, tagged with where it came from.""" + cat, schema = catalog_and_schema + + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=cat.name, + changes=[PermissionsChange(principal="data-eng", add=[Privilege.SELECT])], + ) + workspace_client.grants.update( + securable_type=SecurableType.SCHEMA, + full_name=schema.full_name, + changes=[PermissionsChange(principal="analysts", add=[Privilege.USE_SCHEMA])], + ) + + # The direct read shows only what was granted on the schema itself. + direct = _privileges(workspace_client.grants.get(securable_type=SecurableType.SCHEMA, full_name=schema.full_name)) + assert set(direct) == {"analysts"} + + effective = workspace_client.grants.get_effective(securable_type=SecurableType.SCHEMA, full_name=schema.full_name) + by_principal = {a.principal: a.privileges for a in effective.privilege_assignments} + assert set(by_principal) == {"analysts", "data-eng"} + + inherited = by_principal["data-eng"][0] + assert inherited.privilege.value == "SELECT" + assert inherited.inherited_from_name == cat.name + + # A grant made directly on the securable is not marked as inherited. + assert by_principal["analysts"][0].inherited_from_name is None + + +@pytest.mark.crud +def test_effective_permissions_reach_a_table(workspace_client: WorkspaceClient, catalog_schema_and_table): + """Two levels up: a catalog grant is effective on a table inside it.""" + cat, schema, table = catalog_schema_and_table + + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=cat.name, + changes=[PermissionsChange(principal="readers", add=[Privilege.SELECT])], + ) + + effective = workspace_client.grants.get_effective(securable_type=SecurableType.TABLE, full_name=table.full_name) + by_principal = {a.principal: a.privileges for a in effective.privilege_assignments} + assert [p.privilege.value for p in by_principal["readers"]] == ["SELECT"] + assert by_principal["readers"][0].inherited_from_name == cat.name + + +# ------------------------------------------------------------------------- errors + + +@pytest.mark.error +def test_mismatched_securable_name_rejected(workspace_client: WorkspaceClient, catalog): + """A TABLE addressed by a one-part name would sit in the store matching nothing.""" + with pytest.raises(DatabricksError) as exc: + workspace_client.grants.update( + securable_type=SecurableType.TABLE, + full_name=catalog.name, + changes=[PermissionsChange(principal="x", add=[Privilege.SELECT])], + ) + assert "3-part name" in str(exc.value) + + +@pytest.mark.error +def test_change_without_principal_rejected(workspace_client: WorkspaceClient, catalog): + with pytest.raises(DatabricksError) as exc: + workspace_client.grants.update( + securable_type=SecurableType.CATALOG, + full_name=catalog.name, + changes=[PermissionsChange(add=[Privilege.SELECT])], + ) + assert "principal" in str(exc.value).lower() + + +@pytest.mark.crud +def test_ungranted_securable_reads_empty(workspace_client: WorkspaceClient, catalog): + """No grants is an empty list, not a 404.""" + response = workspace_client.grants.get(securable_type=SecurableType.CATALOG, full_name=catalog.name) + assert response.privilege_assignments in (None, [])