From caf7e3aef47e8dc3199a5e82f51ade97554f6f36 Mon Sep 17 00:00:00 2001 From: Daniel Young Date: Tue, 17 Nov 2026 08:42:17 -0500 Subject: [PATCH] [access] Declare users, roles and grants (0.9.0) 0.8 gave the migration role a fixed set of grants, including the right to manage users and roles, and had no way to say what any other user or role should hold. 0.9 declares users, roles and grants in access.yaml, per environment. access validate, show, plan, apply and check compare a server with the file and make it match, logged in as the admin, so a new project's migration role holds only what migrations need. bootstrap runs on the same engine. Without an access.yaml it still gives 0.8's grants, but attempts every grant and names each one that fails. apply grants before it revokes, and revokes only if every earlier change succeeded. Where users and roles are replicated, as on ClickHouse Cloud, the access commands read every replica. create_dictionary now works with a reader password that starts with ":", and up's failure report hides every secret ch-migrate has read. The CHANGELOG's upgrade notes cover what changes for 0.8 projects: exit 2 for errors before any change, ClickHouse 25.8 or later for bootstrap and the access commands, and init writing access.yaml. Solves: DRY-1620 declarative access for 0.9.0 Tests: unit 1167 on Python 3.10-3.14; Docker integration 189 passed, 4 skipped; cluster 43; ClickHouse 25.8 and ClickHouse Cloud suites (the last three before the final comment and docs cleanup) --- .gitignore | 5 + CHANGELOG.md | 55 +- README.md | 223 ++- ch_migrate/__init__.py | 2 +- ch_migrate/access/__init__.py | 10 + ch_migrate/access/applier.py | 471 ++++++ ch_migrate/access/blocks.py | 158 ++ ch_migrate/access/bootstrap.py | 398 +++++ ch_migrate/access/bundle.py | 70 + ch_migrate/access/check.py | 89 ++ ch_migrate/access/cli.py | 309 ++++ ch_migrate/access/document.py | 125 ++ ch_migrate/access/grants.py | 165 +++ ch_migrate/access/legacy.py | 46 + ch_migrate/access/legacy_mode.yaml | 23 + ch_migrate/access/live.py | 445 ++++++ ch_migrate/access/loader.py | 203 +++ ch_migrate/access/model.py | 117 ++ ch_migrate/access/planner.py | 408 ++++++ ch_migrate/access/privileges.py | 113 ++ ch_migrate/access/privileges_26_3.json | 236 +++ ch_migrate/access/profiles.py | 33 + ch_migrate/access/profiles/core.yaml | 23 + ch_migrate/access/profiles/legacy.yaml | 34 + ch_migrate/access/reading.py | 191 +++ ch_migrate/access/render.py | 115 ++ ch_migrate/access/report.py | 122 ++ ch_migrate/access/rights.py | 280 ++++ ch_migrate/access/server.py | 196 +++ ch_migrate/access/settings.py | 187 +++ ch_migrate/access/show.py | 218 +++ ch_migrate/access/sql/apply.sql | 70 + ch_migrate/access/sql/bundle.sql | 24 + ch_migrate/access/sql/check.sql | 7 + ch_migrate/access/sql/live.sql | 105 ++ ch_migrate/access/sql/render.sql | 43 + ch_migrate/access/templates.py | 27 + ch_migrate/access/writes.py | 260 ++++ ch_migrate/alembic_env.py | 9 +- ch_migrate/bootstrap.py | 431 ++---- ch_migrate/cli.py | 109 +- ch_migrate/helpers.py | 81 +- ch_migrate/migration_runner.py | 15 +- ch_migrate/project_init.py | 101 ++ ch_migrate/secrets.py | 114 +- ch_migrate/skills/ch-migrate/SKILL.md | 73 +- ch_migrate/templates/bootstrap/init_users.sql | 65 - .../templates/project/access.yaml.template | 36 + docs/QUICKSTART.md | 439 ++---- docs/design/2026-10-02-ch-migrate-1.0.md | 10 +- docs/design/2026-10-02-dialect-spike.md | 9 +- docs/design/2026-10-02-rebuild-spike.md | 6 +- docs/design/2026-10-02-waiting.md | 70 +- docs/design/2026-11-11-access-spike.md | 507 +++++++ docs/design/2026-11-11-declarative-access.md | 657 +++++++++ ....md => 2026-03-05_architectural_review.md} | 7 +- examples/basic/README.md | 9 + examples/basic/access.yaml | 42 + examples/basic/config.yaml | 1 - scripts/bundle_privileges.py | 97 ++ scripts/clean_wheel_access.sh | 191 +++ tests/access/conftest.py | 70 + tests/access/fake_access_server.py | 225 +++ tests/access/test_access_file.py | 538 +++++++ tests/access/test_access_live.py | 329 +++++ tests/access/test_access_planner.py | 467 ++++++ tests/access/test_access_profiles.py | 115 ++ tests/access/test_access_rights.py | 212 +++ tests/access/test_access_show.py | 177 +++ tests/access/test_access_sql.py | 115 ++ tests/access/test_access_writes.py | 230 +++ tests/access/test_apply_command.py | 712 +++++++++ tests/access/test_bootstrap_command.py | 343 +++++ tests/access/test_check_command.py | 99 ++ tests/access/test_duplicate_keys.py | 182 +++ tests/access/test_grant_parser.py | 215 +++ tests/access/test_init_access_yaml.py | 52 + tests/access/test_node_read.py | 107 ++ tests/access/test_plan_command.py | 354 +++++ tests/access/test_privilege_list.py | 50 + tests/access/test_project_settings.py | 158 ++ tests/access/test_secret_masking.py | 60 + tests/access/test_validate_command.py | 184 +++ .../access/build_bootstrap_sql_0_8.json | 134 ++ .../access/legacy_bootstrap_26_3.json | 140 ++ tests/integration/access_fixtures.py | 267 ++++ tests/integration/conftest.py | 222 ++- tests/integration/dialect_spike_probe.py | 2 +- tests/integration/grant_rights.py | 232 +++ tests/integration/test_access_apply.py | 1285 +++++++++++++++++ tests/integration/test_access_bootstrap.py | 410 ++++++ .../test_access_characterization.py | 108 ++ tests/integration/test_access_dictionary.py | 104 ++ tests/integration/test_access_parity.py | 175 +++ .../test_access_password_transport.py | 54 + tests/integration/test_access_plan.py | 790 ++++++++++ .../integration/test_access_privilege_list.py | 30 + tests/integration/test_access_spike.py | 1190 +++++++++++++++ tests/integration/test_access_validate_sql.py | 44 + tests/integration/test_cloud.py | 2 +- tests/integration/test_mutation_waiting.py | 4 +- tests/test_bootstrap.py | 237 ++- tests/test_helpers.py | 76 + tests/test_waiting_display.py | 20 + 104 files changed, 18188 insertions(+), 1017 deletions(-) create mode 100644 ch_migrate/access/__init__.py create mode 100644 ch_migrate/access/applier.py create mode 100644 ch_migrate/access/blocks.py create mode 100644 ch_migrate/access/bootstrap.py create mode 100644 ch_migrate/access/bundle.py create mode 100644 ch_migrate/access/check.py create mode 100644 ch_migrate/access/cli.py create mode 100644 ch_migrate/access/document.py create mode 100644 ch_migrate/access/grants.py create mode 100644 ch_migrate/access/legacy.py create mode 100644 ch_migrate/access/legacy_mode.yaml create mode 100644 ch_migrate/access/live.py create mode 100644 ch_migrate/access/loader.py create mode 100644 ch_migrate/access/model.py create mode 100644 ch_migrate/access/planner.py create mode 100644 ch_migrate/access/privileges.py create mode 100644 ch_migrate/access/privileges_26_3.json create mode 100644 ch_migrate/access/profiles.py create mode 100644 ch_migrate/access/profiles/core.yaml create mode 100644 ch_migrate/access/profiles/legacy.yaml create mode 100644 ch_migrate/access/reading.py create mode 100644 ch_migrate/access/render.py create mode 100644 ch_migrate/access/report.py create mode 100644 ch_migrate/access/rights.py create mode 100644 ch_migrate/access/server.py create mode 100644 ch_migrate/access/settings.py create mode 100644 ch_migrate/access/show.py create mode 100644 ch_migrate/access/sql/apply.sql create mode 100644 ch_migrate/access/sql/bundle.sql create mode 100644 ch_migrate/access/sql/check.sql create mode 100644 ch_migrate/access/sql/live.sql create mode 100644 ch_migrate/access/sql/render.sql create mode 100644 ch_migrate/access/templates.py create mode 100644 ch_migrate/access/writes.py create mode 100644 ch_migrate/project_init.py delete mode 100644 ch_migrate/templates/bootstrap/init_users.sql create mode 100644 ch_migrate/templates/project/access.yaml.template create mode 100644 docs/design/2026-11-11-access-spike.md create mode 100644 docs/design/2026-11-11-declarative-access.md rename docs/plans/{2026-03-05_architectural_review_DRY-13.md => 2026-03-05_architectural_review.md} (96%) create mode 100644 examples/basic/access.yaml create mode 100644 scripts/bundle_privileges.py create mode 100755 scripts/clean_wheel_access.sh create mode 100644 tests/access/conftest.py create mode 100644 tests/access/fake_access_server.py create mode 100644 tests/access/test_access_file.py create mode 100644 tests/access/test_access_live.py create mode 100644 tests/access/test_access_planner.py create mode 100644 tests/access/test_access_profiles.py create mode 100644 tests/access/test_access_rights.py create mode 100644 tests/access/test_access_show.py create mode 100644 tests/access/test_access_sql.py create mode 100644 tests/access/test_access_writes.py create mode 100644 tests/access/test_apply_command.py create mode 100644 tests/access/test_bootstrap_command.py create mode 100644 tests/access/test_check_command.py create mode 100644 tests/access/test_duplicate_keys.py create mode 100644 tests/access/test_grant_parser.py create mode 100644 tests/access/test_init_access_yaml.py create mode 100644 tests/access/test_node_read.py create mode 100644 tests/access/test_plan_command.py create mode 100644 tests/access/test_privilege_list.py create mode 100644 tests/access/test_project_settings.py create mode 100644 tests/access/test_secret_masking.py create mode 100644 tests/access/test_validate_command.py create mode 100644 tests/fixtures/access/build_bootstrap_sql_0_8.json create mode 100644 tests/fixtures/access/legacy_bootstrap_26_3.json create mode 100644 tests/integration/access_fixtures.py create mode 100644 tests/integration/grant_rights.py create mode 100644 tests/integration/test_access_apply.py create mode 100644 tests/integration/test_access_bootstrap.py create mode 100644 tests/integration/test_access_characterization.py create mode 100644 tests/integration/test_access_dictionary.py create mode 100644 tests/integration/test_access_parity.py create mode 100644 tests/integration/test_access_password_transport.py create mode 100644 tests/integration/test_access_plan.py create mode 100644 tests/integration/test_access_privilege_list.py create mode 100644 tests/integration/test_access_spike.py create mode 100644 tests/integration/test_access_validate_sql.py diff --git a/.gitignore b/.gitignore index 923ee9d..d63c319 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,11 @@ tmp/ temp/ examples/ +# Except the basic example, which is tracked. Git can't re-include a directory under an +# excluded one, so the top-level examples/ comes back first and only its contents are ignored. +!/examples/ +/examples/* +!/examples/basic/ # Documentation examples are reviewed source, not local sample projects. !docs/examples/ lambda-exporter/ diff --git a/CHANGELOG.md b/CHANGELOG.md index d13af63..86461c7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,60 @@ Changes are recorded in [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) format. -## [Unreleased] +## [0.9.0] + +0.9 declares users, roles and grants in `access.yaml`. `ch-migrate access plan` shows how a server differs from it, and `access apply` makes the server match, logged in as the admin. A new project's migration role holds only what migrations need, with no right to manage users or roles. A normal `pip install -U` reaches 0.9 from 0.8, so read this before upgrading: + +1. **A project without `access.yaml` keeps 0.8's grants, but `bootstrap` reports differently.** + - It creates the migration role and user before any grant, attempts every grant and names each one that fails. **With an admin that can't give every grant, the role and user now exist and hold every grant the admin could give, and `bootstrap` exits 1 naming each failed grant.** 0.8 stopped at the first refused grant, `CREATE FUNCTION`, before it created the migration user. + - A best-effort `CURRENT GRANTS` that lands short is now a warning instead of passing silently. + - It ends by checking the migration role's grants, logged in as the migration user. **If it can't log in as that user, for example because the user's password differs from its secret, it exits 1.** To make them match, run `ALTER USER IDENTIFIED BY ''` as the admin; `access apply --reset-passwords` resets only the users `access.yaml` declares. 0.8 never logged in as the migration user. + - **It needs ClickHouse 25.8 or later,** with or without an `access.yaml`, and exits 2 before any change on an older server. 0.8's `bootstrap` already failed on 24.8. +2. **An error before any change now exits 2 instead of 1,** such as a missing secret, a `config.yaml` problem or a server that can't be reached. Update CI jobs that test for exit 1. +3. **`init` writes `access.yaml`.** Running `init` again in an existing project adds one, and the next `bootstrap` then gives the `core` profile instead of 0.8's grants. Delete the file to keep 0.8's behavior. +4. **Legacy `bootstrap` still runs on one node.** Without an `access.yaml` it never uses `ON CLUSTER`, even with `cluster` set, and sends best-effort grants as `CURRENT GRANTS`, as 0.8 does. On a self-hosted cluster that keeps users and roles on each node's own disk, bootstrap each node. +5. **To adopt `access.yaml` in an existing project,** set `migration_role.profile: legacy` if your migrations create users or roles or grant to other users, start each existing user or role from `ch-migrate access show ENV NAME`, written to another file and copied in, and review the first `access plan` before `access apply`. `apply` revokes, from each user and role the file declares, every grant the file leaves out. With an `access.yaml`, `create_dictionary` no longer grants to `dict_reader`, even under `profile: legacy`: declare the reader and its `SELECT` there. +6. **No `upgrade-env` this time.** + +To stay on 0.8, pin `ch-migrate-cli==0.8.0`. + +### Added + +- `access.yaml` declares users, roles, the roles each one holds (with default roles) and grants (with grant option), with a block per environment and `absent: true` to drop a user or role. An `access.yaml` that is empty, or only comments, is an error, not legacy mode: delete it to keep 0.8's grants. Grants use ClickHouse's own words. `{db}`, `{project}`, `{env}` and `{migration_role}` are placeholders, and `{secret: NAME}` reads a password from SSM or from `CH__`. +- `ch-migrate access validate ENV [--sql]` checks `access.yaml` and the built-in profiles offline, with no server and no secrets. `--sql` prints the SQL for a DBA to review and run, with each password as an unquoted placeholder. A privilege name the bundled ClickHouse 26.3 list doesn't know is a warning, and so is a `READ` or `WRITE` on a source without the other direction. +- `ch-migrate access show ENV [NAME...]` prints what the server holds, in `access.yaml` form: the starting point for adopting existing users and roles. +- `ch-migrate access plan ENV` lists each create, grant, revoke and drop without changing anything. It exits 0 in sync, 1 with changes pending and 2 on an error. `READ` and `WRITE` on one source compare as one grant, because ClickHouse keeps them apart only with `access_control_improvements.enable_read_write_grants` on, which is off by default. +- `ch-migrate access apply ENV [--reset-passwords]` makes the server match, logged in as the admin. It grants before it revokes, and reads every secret before its first change. It narrows a grant's scope with one `GRANT ... WITH REPLACE OPTION`, which keeps what is held inside a declared best-effort grant's scope; a replace that can't keep that exactly, such as `SELECT ON system.*` held less `system.users`, isn't sent: it's skipped and named, the user or role keeps its access, and `apply` exits 1. Revokes, replaces and default-role changes run only if every earlier change succeeded; otherwise they're skipped and named, so old access survives and a role the user keeps stays active at login. A user whose create or password reset fails gets nothing more from that run. A role's replace runs before that of any user or role that holds it, whatever the order in `access.yaml`. Users and roles the file doesn't declare are never touched. +- `ch-migrate access check ENV` checks, logged in as the migration user, that it holds the migration role's grants, for servers where ch-migrate has no admin login. +- Two built-in profiles for the migration role: `core`, what migrations need on the project's database, with no grant option and no user or role management; and `legacy`, 0.8's grants exactly. `migration_role.grants` in `access.yaml` adds to either. `bootstrap` and `apply` only ever add to the migration role. +- `migration_role` in `config.yaml` names a migration role that another project directory shares. +- Where users and roles are replicated, as on ClickHouse Cloud, `access show`, `plan`, `apply` and `bootstrap` read every replica at once, through `clusterAllReplicas` on `cluster` from `config.yaml`, or else on the one cluster that holds the node and another host. A row missing on every replica is absent at once, with no wait. Replicas that disagree are read again until they agree; if they still disagree at the deadline, one line names them, and what the node connected to holds counts. Where every replica can't be read, for example because the admin lacks `READ ON REMOTE` or only one node is listed, a missing row on the connected node is read again before it counts as absent. The fallback reason prints once, only when the command actually waits. +- `access_read_timeout` in `config.yaml`: a deadline, in seconds from the first read, for the access commands and `bootstrap` to keep reading where a replica is behind. Read time counts toward it as well as the waits; one last read may start at the deadline, and each of its requests is bounded by the driver's request timeout. It must be a finite number, 0 or more; `.inf` or `.nan` exits 2 before any change. The default is 30. +- Where the server grants `CLUSTER` to every login, as ClickHouse Cloud does, the best-effort `CLUSTER ON *.*` counts as held: `plan`, `apply`, `check` and `bootstrap` don't warn about it, and `apply` doesn't try it on every run. +- Users and roles are created in the first user directory that can take one, and that is the storage the access commands read: ClickHouse Cloud lists its read-only `jwt` directory first. +- `show`, `plan`, `apply` and `check`, and `bootstrap`, with or without an `access.yaml`, need ClickHouse 25.8 or later, and exit 2 on an older server, naming its version. 0.8's `bootstrap` already failed on 24.8. +- On a self-hosted cluster that keeps users and roles on each node's own disk, with `cluster` set, `apply`, and `bootstrap` with an `access.yaml`, run every statement `ON CLUSTER`, with the cluster's name backquoted so a name such as `c-1` works, and send each best-effort privilege as its own `GRANT ... ON CLUSTER`. There `access plan`, `access apply`, and `bootstrap` with an `access.yaml`, read only the node they connect to, and print a line naming it before any change. An `ON CLUSTER` change that failed on another node goes unseen by the next run against this one, so after a failed `ON CLUSTER` apply, run `access plan` against each node. Reading every node is a planned follow-up. + +### Changed + +- `bootstrap` runs on the access engine. With an `access.yaml`, it gives the migration role its profile and `migration_role.grants`, and `access apply` makes the rest. Without one, it gives 0.8's grants, as the upgrade notes describe. +- `bootstrap --dry-run` reads no secret and prints each password as a `` placeholder, which fails to parse if run unedited. With an `access.yaml` it prints every statement, without `ON CLUSTER`, because offline it can't tell what the server already holds. +- `init` writes `access.yaml`, with the `core` profile and commented examples. +- `create_dictionary` grants nothing in a project with an `access.yaml`: declare the dictionary's reader and its `SELECT` there, and run `access apply` before `up`. Without one, it grants `SELECT` on the source table to `dict_reader` first, as before. + +### Deprecated + +- `build_bootstrap_sql`. It returns the same statements as 0.8, rendered from the built-in `legacy` profile, with the roles and users created first. + +### Removed + +- `ch_migrate/templates/bootstrap/init_users.sql`, which no code read. + +### Fixed + +- `up`'s failure report, `--verbose` traceback included, hides every secret ch-migrate has read, raw, URL-encoded and as SQLAlchemy escapes it. `create_dictionary` writes the reader's password into the statement, and SQLAlchemy's message quotes the statement. +- `create_dictionary` works with a reader password that starts with `:`. SQLAlchemy read it as a bind parameter, so the migration failed and its error named part of the password. +- `create_dictionary` reads the reader's password from the environment's `dict_reader_password` secret, its `ssm:` path in `config.yaml` or `CH__DICT_READER_PASSWORD`, when `DICT_READER_PASSWORD` isn't set. It read only `DICT_READER_PASSWORD`, which neither `config.yaml` nor the `.env.local` template sets. ## [0.8.0] diff --git a/README.md b/README.md index 964177f..6ecbf7a 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,33 @@ This README describes the source checkout, which may be ahead of PyPI. To try an ## Upgrade from 0.x +**From 0.8:** 0.9 needs no `upgrade-env`. It adds `access.yaml` and the `access` commands +(see [Access: users, roles and grants](#access-users-roles-and-grants)). A project without +an `access.yaml` keeps 0.8's grants: `bootstrap` gives the migration role the same grants +as before, on the node it connects to. What changes in `bootstrap`: + +- It creates the migration role and user before any grant, attempts every grant and names + each one that fails. With an admin that can't give every grant, the role and user now + exist and hold what the admin could give, and `bootstrap` exits 1. 0.8 stopped at the + first refused grant, before it created the migration user. +- A best-effort `GRANT CURRENT GRANTS(...)` that lands short, such as + `SELECT ON system.*` from an admin that holds only part of it, is now a warning instead + of passing silently. +- It ends by logging in as the migration user to check the role's grants. If it can't log + in, for example because the user's password differs from its secret, it exits 1. To make + them match, run `ALTER USER IDENTIFIED BY ''` as the admin: + `access apply --reset-passwords` resets only the users `access.yaml` declares. +- It needs ClickHouse 25.8 or later, with or without an `access.yaml`, and exits 2 before + any change on an older server. 0.8's `bootstrap` already failed on 24.8. +- An error before any change, such as a missing secret or an unreachable server, exits 2 + instead of 1. Update CI jobs that test for exit 1. + +`init` now writes an `access.yaml`. Running `init` again in an existing project adds one, +and the next `bootstrap` then gives the core profile instead of 0.8's grants. Delete the +file to keep 0.8's behavior, or adopt it as described under +[Access](#access-users-roles-and-grants). A loose requirement such as `ch-migrate-cli` +upgrades to 0.9; pin `ch-migrate-cli==0.8.0` to stay on 0.8. + **From 0.7:** 0.8 needs no `upgrade-env`, and nothing changes unless you pass `--json` (see [Drift detection in CI](#drift-detection-in-ci)). A loose requirement such as `ch-migrate-cli` upgrades to 0.8; pin `ch-migrate-cli==0.7.0` to stay on 0.7. @@ -70,6 +97,8 @@ cd my-clickhouse-project ch-migrate init --name my_project ``` +`init` writes `config.yaml`, `access.yaml` and the `migrations/` directory. + ### 2. Configure the server Replace `config.yaml` with: @@ -107,6 +136,8 @@ ch-migrate bootstrap dev ch-migrate new dev add_status --table logs ``` +`bootstrap` logs in as the admin and creates the database, the migration role and the migration user. The role gets the `core` profile that `access.yaml` names: what migrations need on the project's database, and no right to manage users or roles. `bootstrap` needs ClickHouse 25.8 or later. + The last command creates a revision plus two files under `migrations/sql/history/tables/logs/`. Their names include a timestamp and revision ID. Replace the contents of the generated `.up.sql` with: ```sql @@ -134,6 +165,17 @@ ch-migrate down dev After `up`, the `logs` table has `id` and `status` columns and status reports one applied revision. After `down`, the example table is gone. +### 5. Declare users and roles + +Users and roles other than the migration identity go in `access.yaml`; its comments show the format. After adding some, preview the changes, then make them as the admin: + +```bash +ch-migrate access plan dev +ch-migrate access apply dev +``` + +See [Access: users, roles and grants](#access-users-roles-and-grants). + ## Concepts ### Project layout @@ -141,6 +183,7 @@ After `up`, the `logs` table has `id` and `status` columns and status reports on ```text project/ ├── config.yaml +├── access.yaml # Users, roles and grants ├── .env.local # Secrets, ignored by git ├── alembic.ini └── migrations/ @@ -468,7 +511,7 @@ DROP TABLE IF EXISTS {db}.users_shadow; `EXCHANGE TABLES` requires a supporting database engine. Neither the copy nor the exchange is automatically idempotent. -The dictionary helper retains automatic SELECT grants for a configured dictionary reader: +`create_dictionary` creates a dictionary from its SQL file, filling in `{db}` and `{password}`, the password of the user the dictionary reads its source as: ```python from ch_migrate import create_dictionary @@ -477,6 +520,123 @@ def upgrade(): create_dictionary("history/dictionaries/dict_users/001_create.sql") ``` +```sql +CREATE DICTIONARY IF NOT EXISTS {db}.dict_users (id UInt64, name String) PRIMARY KEY id +SOURCE(CLICKHOUSE(DB '{db}' TABLE 'users' USER 'dict_reader' PASSWORD '{password}')) +LAYOUT(FLAT()) LIFETIME(300) +``` + +The password comes from `DICT_READER_PASSWORD` if it is set, and otherwise from the environment's `dict_reader_password` secret: its `ssm:` path in `config.yaml`, or `CH__DICT_READER_PASSWORD`. If the statement fails, `up` hides the password in what it prints, `--verbose` included. + +- **Without `access.yaml`,** the helper first grants `SELECT` on the source table to a user named `dict_reader`, as 0.8 does. +- **With `access.yaml`,** it grants nothing. Declare the reader and its `SELECT` there, with the same secret, and run `access apply` before `up` so the reader can read the source once the dictionary exists: + +```yaml +users: + dict_reader: + password: {secret: dict_reader_password} + grants: + - SELECT ON {db}.users +``` + +### Access: users, roles and grants + +`access.yaml`, next to `config.yaml`, declares the users and roles a project needs, the roles each one holds and their grants. `ch-migrate access plan ENV` shows how a server differs from it, and `access apply ENV` makes the server match. `init` writes one that declares only the migration role's profile, with commented examples. + +ch-migrate deals with three identities: + +| Identity | Managed by | Declared in | +|---|---|---| +| The admin, `admin_user` | You. ch-migrate never changes it. | `config.yaml` only. `access.yaml` can't declare it. | +| The migration role and user | `bootstrap` and `access apply`, which only add to them | A built-in profile, plus `migration_role.grants` | +| Every other user and role | `access apply`, which makes each one match the file | `access.yaml` | + +```yaml +migration_role: + profile: core # core (the default) or legacy: 0.8's grants + grants: # beyond the profile + - CREATE FUNCTION, DROP FUNCTION ON *.* + +roles: + analyst: + grants: + - SELECT, SHOW TABLES ON {db}.* + loader: + grants: + - INSERT, SELECT ON {db}.events + reporting: + roles: [analyst] # a role can hold roles + +users: + dashboards: + password: {secret: dashboards_password} + roles: [reporting] + etl: + password: {secret: etl_password} + roles: [loader] + default_roles: [loader] + grants: + - SELECT ON {db}.regions + +environments: + production: + users: + etl: {absent: true} +``` + +- **Grants** use ClickHouse's own words: ` ON [WITH GRANT OPTION]`. A target is `*.*`, `db.*` or `db.table`. `READ` and `WRITE` take a source as their target, as in `READ ON REMOTE`; the old spelling, `REMOTE ON *.*`, is an error that names the new one. An entry can also be `{grant: "...", best_effort: true}` (see below). Column grants and prefix targets such as `db.t*` aren't supported. +- **Placeholders** `{db}`, `{project}`, `{env}` and `{migration_role}` are filled in for each environment. +- **Roles held.** `roles:` on a user or a role grants it those roles. `default_roles:` picks which of a user's roles are default roles; without it, all of them are. A role the file names but doesn't declare must already exist on the server, or `plan` exits 2. +- **Passwords.** `password: {secret: NAME}` reads the secret the way the migration password is read (see [Secrets](#secrets)). A password is set only when its user is created, or again with `access apply --reset-passwords`, and ch-migrate never reads one back. It goes to the server as a bound parameter in the request body, never in the statement or the URL, and an error ch-migrate prints hides every secret it has read. A declared user with no `password` is never created: it must already exist, or `apply` exits 2 before any change. +- **Environments.** `environments.` merges over the rest of the file: mappings merge and lists replace. +- **`absent: true`** drops a user or role; in an environment block, in that environment only. Renames aren't supported: declare the old name absent and add the new one. +- **Validation.** `access validate ENV` checks the file offline, with no server and no secrets. Unknown keys are errors, and each error names the file, the key path and the reason. A privilege name the bundled ClickHouse 26.3 list doesn't know is a warning; `plan` checks names against the live server. + +**What `apply` changes.** For each user and role the file declares, `apply` makes its grants and roles match the file exactly. It grants first and revokes after. Revokes, replaces (below) and default-role changes wait for every earlier change to succeed: creates, password resets, role memberships, grants, replaces and default roles. If one failed, for any user or role, they're all skipped and each is named in a `skipped:` warning, so old access survives, and `apply` exits 1. For example, a user moving from role `A` to role `B` keeps `A` when granting it `B` fails, when a grant to `B` itself fails, and when the user holds both and a grant to `B` meant to replace one of `A`'s fails. Holding back the default-role change means a role the user keeps stays active at login. A role's replace runs before the replace of any user or role that holds it, whatever the order in `access.yaml`, so a holder's replace waits for it. Users and roles the file doesn't declare are never touched, and one is dropped only when it's declared `absent: true`. Run one `apply` at a time for an environment: two at once can interleave their statements, as two `bootstrap` runs could in 0.8. `plan` lists every revoke and drop before `apply` runs it. + +Narrowing a grant's scope, such as `db.*` to `db.events`, can't grant first, because ClickHouse folds the narrower grant into the broader one. Instead, `apply` sends one `GRANT ... WITH REPLACE OPTION` of that user's or role's whole declared set, which keeps the roles it holds. A declared best-effort grant goes into the replace only as far as it's held now, since the admin may not hold the rest, and the replace keeps what is held inside that grant's scope: with a best-effort `SELECT ON system.*` declared, a held `SELECT ON system.tables` survives. That needs the admin to hold, with grant option, every right the grantee holds now; if it doesn't, nothing changes and `apply` says why. One statement can't keep a revoke inside a best-effort grant's scope, such as `SELECT ON system.*` held less `system.users`, nor a revoke of only the grant option there when the declared grant carries one. Then the replace isn't sent: it's skipped and named in a `skipped:` warning, the user or role keeps the access it has, and `apply` exits 1. As after a failure, its revokes and default-role change are skipped too, and so are the revokes, replaces and default-role changes of each user or role that holds it. + +**Adopting existing users and roles.** Declaring a user or role that already exists adopts it. `access show ENV NAME...` prints what the server holds for those names in `access.yaml` form, as a starting point; write it to another file and copy from there. An `access.yaml` that is empty, or only comments, is an error: delete it to keep legacy mode. `plan` marks each declared user or role that exists and has changes pending with `~`, then lists the changes; ch-migrate keeps no state, so adoption and drift look the same. Review the first `plan` before the first `apply`: it revokes every grant the file leaves out. + +**The migration role** holds a built-in profile: + +- **`core`**, the default, holds what migrations need on the project's database, with no grant option and no user or role management: + - on `{db}.*`: `CREATE TABLE`, `DROP TABLE`, `UNDROP TABLE`, `ALTER`, `CREATE VIEW`, `DROP VIEW`, `CREATE DICTIONARY`, `DROP DICTIONARY`, `SELECT`, `INSERT`, `DELETE`, `TRUNCATE`, `OPTIMIZE`, `SHOW TABLES`, `SHOW COLUMNS` and `SHOW DICTIONARIES`; + - `SELECT` on `system.databases`, `system.tables`, `system.mutations` and `system.dictionaries`; + - best-effort: `SELECT` on `system.parts` and `system.replicas`, `SYSTEM SYNC REPLICA` and `SYSTEM SYNC DATABASE REPLICA` on `{db}.*`, and `CLUSTER`, `READ ON REMOTE` and `CREATE TEMPORARY TABLE ON *.*`. +- **`legacy`** is 0.8's migration role exactly: core's database rights with grant option, plus `CREATE FUNCTION` and `DROP FUNCTION`, user, role and row-policy management, and `SELECT` on `system.*` as far as the admin can give it. Set `migration_role.profile: legacy` when the project's migrations create users or roles, or grant to other users. + +`migration_role.grants` adds grants beyond the profile. `bootstrap` and `apply` only ever add to the migration role. `plan` marks each grant the role holds beyond what's declared with `!`, which leaves the exit code alone; revoke those by hand. Because nothing is revoked from it, two project directories can share one migration role (see `migration_role` under [Configuration](#configuration)) without revoking each other's grants, and a project that adopts `access.yaml` keeps the 0.8 grants its migrations rely on. The migration role and user can't be declared under `roles:` or `users:`. + +**Best-effort grants** land as far as the admin can give them, as `GRANT CURRENT GRANTS(...)`: where the admin holds part of a privilege, that part lands, where a plain `GRANT` would land nothing. A best-effort grant that is missing or only partly held is a warning in `plan`, `apply`, `check` and `bootstrap`, and never changes an exit code; only a missing required grant makes `plan` or `check` exit 1. `apply` tries the missing ones again on every run, so `plan` can report in sync while it warns. Where the server grants `CLUSTER` to every login, as ClickHouse Cloud does, `CLUSTER ON *.*` is already held: no command warns about it, and `apply` doesn't try it. On a self-hosted cluster, `up` needs four of core's best-effort grants: `CLUSTER`, `READ ON REMOTE`, `SYSTEM SYNC REPLICA` and, while a mutation on a replicated table is pending, `SELECT ON system.replicas`. + +**Without `access.yaml`** a project is in legacy mode, as every project was in 0.8. `bootstrap` gives the migration role the `legacy` profile, and `mcp_user_name` and `dict_reader_name` in `config.yaml` create the read-only and dictionary roles and users that 0.8 creates. As in 0.8, each is made only when its password (`mcp_password`, `dict_reader_password`) is set; a name without one is skipped with a warning. `access plan` and `apply` compare only the migration role and user, and `apply` only adds missing `legacy` grants. + +**Migrations and `access.yaml`.** In a core project, a migration can't create users or roles, or grant to another user: core has neither the rights nor grant option. Declare those users, roles and grants in `access.yaml`. When a migration and `access.yaml` both touch a declared user or role, `access.yaml` wins at the next `apply`: a grant a migration gives to a user or role that `access.yaml` declares is revoked then, unless `access.yaml` declares it too. With an `access.yaml`, `create_dictionary` grants nothing: declare the dictionary's reader and its `SELECT` in `access.yaml` (see [Exchange and dictionary patterns](#exchange-and-dictionary-patterns)). Set up a fresh environment with `bootstrap`, `up`, then `access apply`. A project whose migrations create dictionaries for a declared reader runs `access apply` before `up` instead, so the reader holds its `SELECT` when a dictionary first loads; ClickHouse accepts grants on tables that don't exist yet. Deploy with `up`, then `access apply`, and run `access plan` in CI to see any drift a migration introduced. ClickHouse accepts grants on databases and tables that don't exist yet, so `apply` can also run before `up`. + +**`READ` and `WRITE` on a source.** ClickHouse keeps `READ` and `WRITE` on a source such as `S3` apart only with `access_control_improvements.enable_read_write_grants` on. That setting is off by default, and SQL can't see it; with it off, `READ ON S3` holds both directions. So `plan` and `apply` compare `READ` and `WRITE` on one source as one grant: declaring either covers both, and neither direction is revoked because the other is declared. `validate` warns about a grant that names one direction alone. A `WRITE` added by hand where `READ` is declared goes unnoticed. + +**Clusters.** On a self-hosted cluster, users and roles live either in replicated storage (Keeper) or on each node's own disk. ch-migrate reads which from `system.user_directories`: the first directory there that can take a create. `users.xml`, LDAP and ClickHouse Cloud's `jwt` only read, so they're passed over. + +- **On each node's own disk, with `cluster` set in `config.yaml`,** `access apply`, and `bootstrap` with an `access.yaml`, run every create, grant, revoke and drop `ON CLUSTER`, sent with `wait_end_of_query=1` so that a host that fails is reported. The cluster's name is backquoted, so a name such as `c-1` works. ClickHouse refuses `CURRENT GRANTS` with `ON CLUSTER`, so each best-effort privilege goes as its own plain `GRANT ... ON CLUSTER`: a full admin lands each one on every node, and each one the admin can't give is a warning. The admin needs `CLUSTER ON *.*` to run `ON CLUSTER` at all. +- **Only one node is read.** On each node's own disk, with `cluster` set, `access plan`, `access apply` and `bootstrap` with an `access.yaml` read only the node they connect to, and before any change they print a line naming it: the server's `hostName()`, or `host:port` from `config.yaml` when that can't be read. If an `ON CLUSTER` change lands on one node and fails on another, `apply` exits 1 and names the error, but the next `plan` or `apply` against the first node sees nothing to do, so a `plan` that exits 0 there says nothing about the other nodes. After a failed `ON CLUSTER` apply, point `host` in `config.yaml` at each node in turn and run `access plan` against it. Reading every node is a planned follow-up. +- **In replicated storage, and on ClickHouse Cloud,** nothing runs `ON CLUSTER`; with replicated storage it would fail with `ACCESS_ENTITY_ALREADY_EXISTS`. A replica can be behind, so `plan`, `apply`, `show` and `bootstrap` read every replica at once, through `clusterAllReplicas`: the cluster named by `cluster` in `config.yaml`, or else the one cluster that holds the node and another host (clusters that list the same hosts, as Cloud's `default` and `all_groups.default` do, count as one). A row missing on every replica is absent at once. Replicas that disagree are read again until they agree, for up to `access_read_timeout` seconds; if they still disagree then, one line names them, and what the node connected to holds counts. Where every replica can't be read, because no cluster is found, the admin lacks `READ ON REMOTE` or a replica can't be reached, a missing row on the node connected to is read again for up to `access_read_timeout` seconds before it counts as absent. A lone replicated node keeps this wait because peers sharing its users may exist outside its listed clusters. The fallback reason prints once, only if the command actually waits. +- **`bootstrap` without an `access.yaml`** never uses `ON CLUSTER`, even with `cluster` set, and sends best-effort grants as `CURRENT GRANTS`, as 0.8 does. Where users and roles are on each node's own disk, run it once per node. +- **`access validate --sql`** prints best-effort grants as `CURRENT GRANTS`, with no `ON CLUSTER`. Where users and roles are on each node's own disk, a DBA runs that SQL on each node. +- **`bootstrap --dry-run`** with an `access.yaml` prints every statement for the database and the migration role and user, without `ON CLUSTER`: offline, it can't tell whether `ON CLUSTER` applies, and its header says so. The real run sends only what's missing. + +**What the admin needs.** `access show`, `plan`, `apply` and `check`, and `bootstrap`, need ClickHouse 25.8 or later; on an older server they exit 2 and name its version. `bootstrap`, `access show`, `plan` and `apply` log in as `admin_user`, which needs: + +- `SELECT` on `system.users`, `system.roles`, `system.grants`, `system.role_grants` and `system.user_directories`, to read what the server holds; +- where users and roles are replicated, as on ClickHouse Cloud, `READ ON REMOTE` to read every replica at once, and `SELECT ON system.clusters` when `cluster` isn't set. Without them, a read waits for what it doesn't find; +- `CREATE DATABASE ON {db}.*`, even when the database exists, and `CREATE ROLE` and `CREATE USER` on `*.*`; +- `ROLE ADMIN ON *.*`, because creating a role doesn't give its creator the right to grant it. `ROLE ADMIN` also lets the admin grant any role to anyone, so even the smallest admin that can run `bootstrap` holds that power; +- each grant it gives, with grant option. The `SHOW` grants come with the admin's other rights on the database; +- `ALTER USER` to set default roles and reset passwords, and `DROP USER` and `DROP ROLE` to drop what `access.yaml` declares `absent: true`; +- `CLUSTER ON *.*` to run `ON CLUSTER`. + +An admin with the read grants, the three creates, `ROLE ADMIN` and core's required grants with grant option lands every required grant of a core `bootstrap`, and each best-effort grant it can't give is a warning. `access check` needs no admin: it logs in as the migration user, for servers where ch-migrate has no admin login. + ## Drift detection in CI After applying and verifying migrations in an environment, capture its expected @@ -541,16 +701,45 @@ Output lines start with `→` for a step, `✓` for a result, `!` for a warning ### `init` -`ch-migrate init [PATH] [-n NAME]` initializes the current directory by default. `-n/--name` sets the project name; otherwise it uses the directory name. +`ch-migrate init [PATH] [-n NAME]` initializes the current directory by default. `-n/--name` sets the project name; otherwise it uses the directory name. It writes `config.yaml`, an `access.yaml` whose migration role holds the `core` profile, `alembic.ini`, `.env.local.example` and the `migrations/` directory, and leaves any of those files that already exists alone. Example: `ch-migrate init analytics --name analytics` ### `bootstrap` -`ch-migrate bootstrap ENV [--dry-run] [-v]` creates the database, roles, and configured users. `--dry-run` prints SQL without executing it; `-v/--verbose` prints statements during execution. Requires admin and migration credentials. +`ch-migrate bootstrap ENV [--dry-run] [-v]` creates the database and the migration role and user, then checks the role's grants, logged in as the migration user. With an `access.yaml`, the role gets its profile and `migration_role.grants`, and `access apply` makes the rest. It needs ClickHouse 25.8 or later. On a cluster that keeps users and roles on each node's own disk, with `cluster` set, it runs `ON CLUSTER` as `access apply` does, reads only the node it connects to, and prints a line naming that node. Without an `access.yaml`, `bootstrap` gives the grants 0.8 gave, plus the optional MCP and dict reader users, on the node it connects to and never `ON CLUSTER`, so such a cluster is bootstrapped once per node, as in 0.8. On a self-hosted cluster where users and roles are stored in Keeper, `bootstrap` never uses `ON CLUSTER`, with or without an `access.yaml`, so it creates the database only on the node it connects to, as 0.8 did; create it on the other nodes, or use a `Replicated` database. It creates the role and user first, attempts every grant and names each one that fails. `--dry-run` prints the SQL without connecting or reading a secret, with each password as a `` placeholder. With an `access.yaml` it prints every statement, without `ON CLUSTER`, since offline it can't tell what the server already holds or where users are stored; the real run sends only what's missing. `-v/--verbose` prints statements during execution. Requires admin and migration credentials. It exits 0 when done, 1 when something failed or, with an `access.yaml`, a change is still pending once replicas have had `access_read_timeout` to agree (each one named, as `access apply` names them), and 2 on an error before any change. Example: `ch-migrate bootstrap dev --dry-run` +### `access` + +`ch-migrate access validate ENV [--sql]` checks `access.yaml`, which declares users, roles and grants, and the built-in profiles, offline: it needs no server and no secrets. It exits 0 when the file is valid and 2 when it isn't, listing every error with its file, key path and reason. Warnings, such as a privilege name the bundled ClickHouse 26.3 list doesn't know, leave the exit code at 0. Without `access.yaml`, it checks legacy mode: the grants 0.8's `bootstrap` gave. `--sql` also prints the SQL a DBA can review and run. Each password is an unquoted placeholder, ``, so the SQL fails to parse until each one is replaced with its secret as a quoted string. A declared user with no password isn't created there; the header names it as a user that must already exist. Best-effort grants are printed as `GRANT CURRENT GRANTS(...)`, with no `ON CLUSTER`, so on a self-hosted cluster that keeps users and roles on each node's own disk, the DBA runs the SQL on each node. + +Example: `ch-migrate access validate dev --sql` + +`ch-migrate access show ENV [NAME...]` logs in as `admin_user` and prints what the server holds, in `access.yaml` form, for the users and roles `access.yaml` declares or for the names given. It is where adopting existing users and roles starts: write it to another file, such as `ch-migrate access show dev NAME > access.show.yaml`, and copy what you keep into `access.yaml`. Redirected straight into `access.yaml`, the shell empties that file before `show` runs, and `show` then stops with an error. It writes nothing, reads only the admin's secret and never shows a password. It exits 0, or 2 on an error. + +`ch-migrate access plan ENV` logs in as `admin_user` and prints how the server differs from `access.yaml`, one line per change, without changing anything: + +- `+` create or grant; +- `-` revoke or drop; +- `~` a declared user or role that already exists and has changes pending; +- `!` a grant the migration role holds beyond its profile. Nothing is revoked from the migration role. + +It exits 0 in sync, 1 with changes pending and 2 on an error. `!` lines and warnings about best-effort grants leave the exit code alone. Narrowing a grant's scope, such as `db.*` to `db.events`, shows as one `replace` of that user's or role's declared set, and the line names what the replace takes away. `READ` and `WRITE` on one source, such as `READ ON S3`, compare as one grant: ClickHouse keeps them apart only with `access_control_improvements.enable_read_write_grants` on, which is off by default, so `validate` warns about a grant that names one direction alone. In legacy mode, with no `access.yaml`, only the migration role and user are compared. On a self-hosted cluster that keeps users and roles on each node's own disk, with `cluster` set, `plan` reads only the node it connects to and names it first: after a failed `ON CLUSTER` apply, run `plan` against each node (see Clusters under [Access: users, roles and grants](#access-users-roles-and-grants)). + +Example: `ch-migrate access plan dev` + +`ch-migrate access apply ENV [--reset-passwords]` logs in as `admin_user` and makes the changes `plan` lists, in order: creates, memberships, grants, replaces, default roles, revokes, then drops. A role's replace runs before the replace of any user or role that holds it, whatever the order in `access.yaml`. It continues past a failed statement, then plans again and reports what still differs. Revokes, replaces and default-role changes run only if every earlier change succeeded; otherwise they're skipped and named, so old access survives and a role the user keeps stays active at login. A user whose create or password reset fails gets nothing more from that run, since someone else may have made it, with a password that isn't the declared one. Drops run only if nothing failed and every replace was sent. Otherwise each drop is skipped and named, since a revoke held back may leave a user or role relying on a role about to be dropped. Narrowing a scope is one `GRANT ... WITH REPLACE OPTION` of the declared set, which keeps what is held inside a declared best-effort grant's scope. A replace that can't keep exactly what is held of a declared best-effort grant, such as `SELECT ON system.*` held less `system.users`, isn't sent: it's skipped and named, the user or role keeps its access, the changes waiting on it are skipped as after a failure, and `apply` exits 1. The migration role is only ever added to. Best-effort grants land as far as the admin can give them, and the rest is a warning. On a self-hosted cluster that keeps users and roles on each node's own disk, with `cluster` set, every statement runs `ON CLUSTER`, and each best-effort privilege is its own `GRANT ON CLUSTER`; `apply` reads only the node it connects to and names it before any change, so a change that failed on another node goes unseen by the next run against this one. A password is set when its user is created, and again with `--reset-passwords`, which also resets a user the same run creates, right after its create. Before any change, `apply` reads every secret it will set, and it exits 2 if `access.yaml` declares `admin_user` or the login it runs as, would revoke from, replace or drop a role that login holds, or declares a new user with no password. Interrupted after a write, it says so and exits 130, as `up` does. It exits 0 when the server then matches, 1 when it doesn't, because a change failed or was skipped (each one named) or something still differs, and 2 on an error before any change. + +Example: `ch-migrate access apply dev` + +`ch-migrate access check ENV` is for servers where ch-migrate has no admin login. It logs in as the migration user and runs one `CHECK GRANT` for each grant of the migration role's profile and `migration_role.grants`, as the flags each grant means on its target. `CHECK GRANT` can't see a grant option, so only privileges are checked. It writes nothing and reads only the migration user's secret. It exits 0 when every required grant is held, 1 when one is missing (each one named) and 2 on an error. A missing best-effort grant is a warning. + +Example: `ch-migrate access check dev` + +`show`, `plan`, `apply` and `check` need ClickHouse 25.8 or later. The admin needs `SELECT` on `system.users`, `system.roles`, `system.grants`, `system.role_grants` and `system.user_directories`, and where users and roles are replicated, `READ ON REMOTE`. `apply` also needs `ALTER USER` to set default roles and reset passwords, `DROP USER` and `DROP ROLE` to drop what `access.yaml` declares `absent: true`, and `CLUSTER ON *.*` where it runs `ON CLUSTER`. The full list, including the `ROLE ADMIN` that lets the admin grant any role to anyone, is under [Access: users, roles and grants](#access-users-roles-and-grants). Where users and roles are replicated, a replica can be behind, so every replica is read at once, and replicas that disagree are read again for up to `access_read_timeout` seconds (default 30, set per environment in `config.yaml`). Where every replica can't be read, a line says why, and a missing row is read again for that long before it counts as absent. + ### `new` `ch-migrate new ENV NAME [--table T | --view V | --dict D] [--irreversible REASON | --python | --exchange]` creates SQL-first migrations by default. Object-option aliases are `-t`, `-v`, and `-d`. `--python` keeps the Python template. `--exchange` requires `--table`. The three authoring-mode options are mutually exclusive, and conflicts fail before a revision is written. @@ -681,6 +870,8 @@ defaults: secure: true admin_user: default # cluster: my_cluster + # migration_role: shared_migration_role + # access_read_timeout: 30 # dict_reader_name: dict_reader # mcp_user_name: mcp_reader @@ -693,8 +884,16 @@ environments: ssm: admin_password: /analytics/dev/admin_password migration_password: /analytics/credentials#password + dashboards_password: /analytics/dev/dashboards_password ``` +These keys can be set in `defaults` or in an environment: + +- `migration_role` names the migration role. Without it, the role is `_migration_role`. Two project directories that set the same `migration_role`, each with its own database, share that role: each directory's `bootstrap` adds the profile's grants on its own database and revokes nothing, and each keeps its own version table. The role has no rights on a database whose directory hasn't been bootstrapped, so a stray migration there fails with `ACCESS_DENIED`. +- `access_read_timeout` is a deadline, in seconds from the first read, for the `access` commands and `bootstrap` to keep reading again where users and roles are replicated: until every replica agrees, or, where every replica can't be read, before a missing row counts as absent. The time the reads take counts toward it, as well as the waits between them, so slow reads can't stretch it; one last read may start at the deadline, and each of its requests is bounded by the driver's request timeout. It must be a finite number, 0 or more, and 0 reads once; anything else, such as `.inf` or `.nan`, makes those commands exit 2 before any change. The default is 30. +- `cluster` also decides whether access statements run `ON CLUSTER`; see [Access](#access-users-roles-and-grants). They backquote its name, so a name such as `c-1` works there. It must be a string. +- `mcp_user_name` and `dict_reader_name` apply only without an `access.yaml`. With one, `bootstrap` creates neither user: declare a read-only user in `access.yaml` instead, and see [Access](#access-users-roles-and-grants) about the dictionary reader. + ### Secrets Choose `.env.local` (or exported environment variables) or per-environment SSM paths. When an SSM path is configured, it is used for that secret. A `#key` suffix extracts a JSON key from the parameter. SSM access requires AWS credentials and permission to read the specified parameters; `aws_region` is optional. @@ -703,8 +902,11 @@ Choose `.env.local` (or exported environment variables) or per-environment SSM p |---|---| | `CH__MIGRATION_PASSWORD` | Required migration password | | `CH__ADMIN_PASSWORD` | Admin password for bootstrap | -| `CH__DICT_READER_PASSWORD` | Password when a dictionary reader is configured | +| `CH__DICT_READER_PASSWORD` | The dictionary reader's password, for `create_dictionary` and `dict_reader_name` | | `CH__MCP_PASSWORD` | Password when a read-only MCP user is configured | +| `CH__` | Password of a user `access.yaml` declares with `password: {secret: NAME}`, such as `CH_DEV_DASHBOARDS_PASSWORD` for `{secret: dashboards_password}` | + +A declared user's secret is read the same way: from the SSM path at `environments..ssm.` in `config.yaml` when one is set, and otherwise from `CH__`. Only `access apply` reads these secrets, and only for the passwords it sets: those of users it creates, or every declared user's with `--reset-passwords`. It reads them all before its first change, and a missing one exits 2 with nothing changed. `access validate`, `show` and `plan` never read them. The legacy `CH__PASSWORD` remains supported. Never commit credentials or pass them in migration SQL that will be logged. @@ -746,7 +948,18 @@ Review findings rather than treating a successful command as a guarantee that a ### Bootstrap roles and Cloud notes -Bootstrap creates `{project}_migration_role` for schema/data operations and introspection, including explicit `system.grants`, `system.databases`, `system.tables`, and `system.mutations` access. It grants available cluster, remote-read, and synchronization rights through `CURRENT GRANTS`. Optional users add `{project}_readonly_role` (SELECT/SHOW) and `{project}_dict_role` (dictionary sources). Bootstrap uses explicit grants rather than `GRANT ALL` for Cloud compatibility. +`bootstrap` creates the database, the migration role and the migration user, and grants the role to the user. The role is `_migration_role`, or `migration_role` from `config.yaml`. What else it does depends on whether the project has an `access.yaml`: + +| | With `access.yaml` | Without (legacy mode) | +|---|---|---| +| Migration role's grants | The profile it names, `core` by default, plus `migration_role.grants` | 0.8's grants: the `legacy` profile | +| Other roles and users | None. `access apply` makes what `access.yaml` declares. | `_readonly_role` (`SELECT`, `SHOW TABLES`) and its user, with `mcp_user_name`; `_dict_role` and its user, with `dict_reader_name` | +| Server version | 25.8 or later | 25.8 or later | +| `ON CLUSTER` | Where users and roles are on each node's own disk and `cluster` is set | Never: bootstrap each node | + +Either way it grants explicit privileges, never `GRANT ALL`, and attempts every grant. Best-effort grants land as far as the admin can give them, and the rest are warnings. It ends by logging in as the migration user and checking the role's required grants. It is safe to run again, and it never revokes. + +On ClickHouse Cloud the admin may not hold every best-effort grant, such as all of `SELECT ON system.*` in the `legacy` profile; each one it can't give is a warning. The `core` profile grants `SELECT` on each system table ch-migrate reads, one by one, rather than on `system.*`. Cloud grants `CLUSTER` to every login, so `CLUSTER ON *.*` is already held and nothing warns about it. Access statements don't run `ON CLUSTER` on Cloud. Its users and roles are replicated, so each read takes every replica at once, through the `default` cluster, with no wait for a row that no replica holds; the admin needs `READ ON REMOTE` for that. Use standard table engine names such as `MergeTree` and `ReplacingMergeTree`; ClickHouse Cloud supplies its shared variants. Cloud usually uses HTTPS port `8443`; local HTTP usually uses `8123`. diff --git a/ch_migrate/__init__.py b/ch_migrate/__init__.py index 4e1e8bd..2943254 100644 --- a/ch_migrate/__init__.py +++ b/ch_migrate/__init__.py @@ -5,7 +5,7 @@ from ch_migrate import read_sql, get_db, get_env_config, create_dictionary """ -__version__ = "0.8.0" +__version__ = "0.9.0" from typing import Any diff --git a/ch_migrate/access/__init__.py b/ch_migrate/access/__init__.py new file mode 100644 index 0000000..140551e --- /dev/null +++ b/ch_migrate/access/__init__.py @@ -0,0 +1,10 @@ +"""Declarative access: users, roles and grants in access.yaml. + +- Input: model, document, reading, blocks, grants, loader, settings and profiles. +- Comparison: privileges, rights and planner. +- Live I/O: server, live, show, check and report. +- Execution: applier, writes, bootstrap and legacy. +- Entry points and SQL: cli, render and templates; bundle maintains privilege metadata. + +The behavior contract is docs/design/2026-11-11-declarative-access.md. +""" diff --git a/ch_migrate/access/applier.py b/ch_migrate/access/applier.py new file mode 100644 index 0000000..905d8df --- /dev/null +++ b/ch_migrate/access/applier.py @@ -0,0 +1,471 @@ +"""Prepare, apply and replan access changes (design 2.5). + +Preparation resolves every refusal and secret before any write. Execution retains old +access when replacements or role dependencies fail; an unsent replace also blocks drops. +Dependency-first replaces, default-role gating and statement accounting are enforced by +Outcome and _steps. Replanning uses the same reader and waits for partial writes to settle. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Any, Callable, Mapping + +from ch_migrate.access.live import REPLICATED_STORAGE, LiveState, Reader +from ch_migrate.access.model import AccessSpec, Role, User +from ch_migrate.access.planner import ( + ACTION_ORDER, + Change, + Entity, + Plan, + build_plan, + declared_entities, + wanted, +) +from ch_migrate.access.server import ( + AccessError, + hide_secrets, + read_secret, + server_errors, + server_message, +) +from ch_migrate.access.settings import ProjectSettings +from ch_migrate.access.templates import statement +from ch_migrate.access.writes import Unkept, Write, Writing, writes_for + +# What must have landed, for any user or role, before any revoke, replace or default-role +# change (2.5). +_BEFORE_REVOKES = frozenset( + { + "create_role", + "create_user", + "reset_password", + "grant_role", + "grant", + "replace", + "set_default_roles", + } +) +# What can take access away, so it waits for those: the revokes, a replace, and default +# roles, which can leave a role the user keeps inactive at login. +_GATED = frozenset( + { + "revoke", + "revoke_grant_option", + "revoke_role", + "revoke_admin_option", + "replace", + "set_default_roles", + } +) +_DROPS = frozenset({"drop_user", "drop_role"}) +# The changes that set a user's password. When one fails, the user may be someone else's, with +# their password, so it gets nothing more from this run. +_SETS_PASSWORD = {"create_user": "create", "reset_password": "password reset"} +# The changes to a role that take access from whoever holds it. +_TAKES_ACCESS = frozenset( + {"revoke", "revoke_grant_option", "revoke_role", "revoke_admin_option", "replace", "drop_role"} +) + + +class Refusal(AccessError): + """`apply` won't start, for each of these reasons. Nothing has changed.""" + + def __init__(self, *messages: str): + super().__init__(" ".join(messages)) + self.messages = messages + + +@dataclass(frozen=True) +class Request: + """What `access apply` was asked to do.""" + + settings: ProjectSettings + spec: AccessSpec + reset_passwords: bool = False + + +@dataclass(frozen=True) +class Work: + """What `apply` will do, in order, and what its statements are written from.""" + + plan: Plan + steps: tuple[Change, ...] # the plan's lines, password resets and best-effort tries + writing: Writing + reader: Reader # how the server is read, before and after the writes + + +@dataclass(frozen=True) +class Step: + """How one change went: made, failed with the server's reason, or skipped and why.""" + + change: Change + failure: str | None = None + skipped: str | None = None + unkept: bool = False # a replace not sent: it couldn't keep what is held + + @property + def wrote(self) -> bool: + """Whether a statement was sent for it.""" + return self.change.marker in "+-" and self.skipped is None + + +@dataclass +class Outcome: + """Every step `run` took, in order.""" + + steps: list[Step] = field(default_factory=list) + # The roles each declared user or role holds as access.yaml says, through declared roles. + holding: Mapping[Entity, frozenset[str]] = field(default_factory=dict) + + @property + def counted(self) -> int: + """The changes made: every `+` and `-` line but the best-effort tries.""" + return sum(1 for change in self.made if change.action != "best_effort") + + @property + def wrote(self) -> bool: + return any(step.wrote for step in self.steps) + + def skip_reason(self, change: Change) -> str | None: + """Why a change must not run, or None (2.5). + + A user whose create or password reset failed gets nothing more. + A revoke, replace, default-role change or drop waits for every earlier change: one + that failed holds it back, and so does a replace that couldn't be sent. The reason + names its own user or role, or a role it holds, when that is where it went wrong. + Otherwise it names the change anywhere else, since a sibling role its holders rely on + may be the one that failed. + """ + if change.action in _DROPS: + return self._drop_reason() + login = self._failed_login(change.entity) + if login: + return f"its {login} failed, so this run gives it nothing more" + if change.action not in _GATED: + return None + failed = { + step.change.entity for step in self.failures if step.change.action in _BEFORE_REVOKES + } + unkept = {step.change.entity for step in self.steps if step.unkept} + return ( + self._because(change.entity, failed, "failed") + or self._because(change.entity, unkept, "couldn't be sent") + or _elsewhere(failed, unkept) + ) + + def exit_code(self, after: Plan) -> int: + """0 when the server now matches, else 1: a change failed, or something still differs.""" + return 1 if self.failures or after.pending or after.errors else 0 + + @property + def made(self) -> frozenset[Change]: + return frozenset(step.change for step in self.steps if step.wrote and not step.failure) + + @property + def failures(self) -> list[Step]: + """The changes that failed. A best-effort try that fails is only a warning.""" + return [step for step in self.steps if step.failure and step.change.action != "best_effort"] + + @property + def skipped(self) -> list[Step]: + return [step for step in self.steps if step.skipped] + + def _failed_login(self, entity: Entity) -> str | None: + """Which change that sets `entity`'s password failed, "create" or "password reset".""" + for step in self.failures: + if step.change.entity == entity and step.change.action in _SETS_PASSWORD: + return _SETS_PASSWORD[step.change.action] + return None + + def _drop_reason(self) -> str | None: + """Why no drop runs yet: a change failed, or a replace couldn't be sent. + + Either can leave a revoke skipped, so a role about to be dropped may be the access a + user or role keeps. + """ + if self.failures: + return "an earlier change failed" + unkept = ", ".join(str(step.change.entity) for step in self.steps if step.unkept) + return f"the replace of {unkept} couldn't be sent" if unkept else None + + def _because(self, entity: Entity, gating: set[Entity], verb: str) -> str | None: + """Why `entity` waits, if `gating` names it or a role it holds as access.yaml says.""" + if entity in gating: + return f"a change to {entity} {verb}, so it keeps the access it has" + held = self.holding.get(entity, frozenset()) + roles = sorted(other.name for other in gating if other.kind == "role") + roles = [role for role in roles if role in held] + if roles: + return f"{_changes_to(roles)}, which it holds, {verb}, so it keeps the access it has" + return None + + +def prepare(reader: Reader, request: Request) -> Work: + """Read, plan and check everything that can stop `apply`, before any write. + + Raises `Refusal`, or `AccessError` for a secret or the server, and nothing has changed. + """ + _refuse_identities(reader.client, request) + spec = request.spec + live = reader.settled(wanted(spec), lambda state: build_plan(spec, state).missing_rows) + plan = build_plan(spec, live) + if plan.errors: + raise Refusal(*plan.errors) + _refuse_taking_from_the_login(reader.client, plan) + created = tuple(change.entity.name for change in plan.changes if change.action == "create_user") + resets = _resets(request, live, created) + passwords = _passwords(request, created, resets) + writing = Writing(spec, live, _cluster(request.settings, live), passwords) + return Work(plan, _steps(plan, resets, _held_roles(spec)), writing, reader) + + +def run(client: Any, work: Work, report: Callable[[Step], None]) -> Outcome: + """Make each change in order, reporting each step as it ends; go on past a failure.""" + outcome = Outcome(holding=_held_roles(work.writing.spec)) + for change in work.steps: + skipped = outcome.skip_reason(change) + steps = [Step(change, skipped=skipped)] if skipped else _make(client, work.writing, change) + for step in steps: + outcome.steps.append(step) + report(step) + return outcome + + +def replan(work: Work, outcome: Outcome) -> Plan: + """Plan again, after reading until what `apply` made shows, or the time limit is up. + + Where every replica is read at once, a read is behind only while the replicas disagree + (`LiveState.behind`). Where only the node connected to is read, a read is behind while a + user or role that `apply` changed has a change pending, other than one `apply` failed at + or skipped, which no read will show. The change pending needn't be one `apply` made: a + replica that shows only the first statement of a replace leaves a grant option pending + instead. + """ + spec = work.writing.spec + changed = {change.entity for change in outcome.made if change.action != "best_effort"} + unmade = {step.change for step in outcome.steps if step.failure or step.skipped} + live = work.reader.settled( + wanted(spec), + lambda state: any( + change.entity in changed and change not in unmade + for change in build_plan(spec, state).pending + ), + ) + return build_plan(spec, live) + + +def _refuse_identities(client: Any, request: Request) -> None: + """`apply` never changes the admin's access, or that of the login it runs as (2.1, 2.5). + + The loader already refuses an access.yaml that declares `admin_user`. The server says + who `apply` is really logged in as, and that login can't be declared either. + """ + settings = request.settings + if settings.migration_user == settings.admin_user: + raise Refusal( + f"The migration user {settings.migration_user} is config.yaml's admin_user, " + "whose access ch-migrate never changes. Give the migration user a login of its own." + ) + with server_errors(): + [row] = client.query(statement("apply", "current_user")).named_results() + login = str(row["name"]) + if login in {user.name for user in request.spec.users}: + raise Refusal( + f"`apply` is logged in as {login}, which access.yaml declares. " + "ch-migrate never changes the login it runs as." + ) + + +def _refuse_taking_from_the_login(client: Any, plan: Plan) -> None: + """`apply` never takes access from a role the login it runs as holds (2.1). + + A revoke, replace or drop there could leave the admin without a right a later statement + needs. The admin may hold a declared role, as it must hold one WITH ADMIN OPTION to grant + it without ROLE ADMIN; only taking access from it is refused. + """ + with server_errors(): + rows = client.query(statement("apply", "current_roles")).named_results() + held = {str(row["name"]) for row in rows} + taken = sorted( + { + change.entity.name + for change in plan.changes + if change.entity.kind == "role" + and change.entity.name in held + and change.action in _TAKES_ACCESS + } + ) + if taken: + raise Refusal( + f"access.yaml would revoke from, replace or drop {_roles_named(taken)}, which the " + "login `apply` runs as holds. ch-migrate never takes access from the login it runs " + "as: change access.yaml, or apply as an admin that doesn't hold it." + ) + + +def _resets(request: Request, live: LiveState, created: tuple[str, ...]) -> tuple[str, ...]: + """With --reset-passwords: each declared user with a password, existing or created now. + + One this run creates is reset too, right after its create: if someone else makes the user + between this run's read and its `CREATE USER IF NOT EXISTS`, the create keeps their + password, and only the reset replaces it. + """ + if not request.reset_passwords: + return () + created_names = set(created) + return tuple( + user.name + for user in _users(request.spec) + if user.password is not None + and (user.name in created_names or live.find("user", user.name) is not None) + ) + + +def _passwords( + request: Request, created: tuple[str, ...], resets: tuple[str, ...] +) -> dict[str, str]: + """Every password `apply` will set, read before its first write (2.5).""" + spec = request.spec + secrets = {user.name: user.password for user in _users(spec) if user.password is not None} + secrets[spec.migration.user] = spec.migration.password + return {name: read_secret(request.settings, secrets[name].name) for name in (*created, *resets)} + + +def _cluster(settings: ProjectSettings, live: LiveState) -> str | None: + """The cluster to run every statement ON, or None where a create reaches every node.""" + cluster = settings.server.cluster + if cluster is None or live.storage == REPLICATED_STORAGE: + return None + if live.storage is None: + raise Refusal( + f"config.yaml sets cluster {cluster} for {settings.environment}, but the admin " + "can't read system.user_directories, or it lists no storage a create can go to, " + "so `apply` can't tell whether users and roles need ON CLUSTER. " + "Grant the admin SELECT ON system.user_directories." + ) + return cluster + + +def _steps( + plan: Plan, resets: tuple[str, ...], holding: Mapping[Entity, frozenset[str]] +) -> tuple[Change, ...]: + """The plan's lines, each password reset and each best-effort try, in apply's order.""" + tries = [ + Change("best_effort", shortfall.entity, grant=shortfall.grant) + for shortfall in plan.shortfalls + if not shortfall.reason + ] + reset = [Change("reset_password", Entity("user", name)) for name in resets] + steps = [*plan.changes, *reset, *tries] + return tuple( + sorted(steps, key=lambda change: (ACTION_ORDER[change.action], _depth(change, holding))) + ) + + +def _depth(change: Change, holding: Mapping[Entity, frozenset[str]]) -> int: + """Where a replace runs among the replaces: the more roles it holds, the later (2.5). + + A user or role holds each role that a role it holds holds, and that role too, so a role's + replace runs before the replace of any declared user or role that holds it. + """ + if change.action != "replace": + return 0 + return len(holding.get(change.entity, frozenset())) + + +def _held_roles(spec: AccessSpec) -> dict[Entity, frozenset[str]]: + """The roles each declared user or role holds as access.yaml says, through declared roles. + + A role access.yaml doesn't declare counts, but what it holds isn't known, so the walk + stops there. + """ + declared = [entity for entity in declared_entities(spec) if not entity.absent] + through = {entity.name: entity.roles for entity in declared if isinstance(entity, Role)} + holding = {} + for entity in declared: + held: set[str] = set() + left = list(entity.roles) + while left: + role = left.pop() + if role not in held: + held.add(role) + left += through.get(role, ()) + kind = "user" if isinstance(entity, User) else "role" + holding[Entity(kind, entity.name)] = frozenset(held) + return holding + + +def _make(client: Any, writing: Writing, change: Change) -> list[Step]: + """Send a change's statements in order; the first that fails ends it. + + A best-effort grant's statements are each a step of their own, and all are sent. A replace + that can't keep what is held sends nothing, and is skipped. + """ + try: + writes = writes_for(change, writing) + except Unkept as unkept: + return [Step(change, skipped=str(unkept), unkept=True)] + if change.action == "best_effort": + return [ + Step(replace(change, grant=write.gives), failure=_send(client, writing, write)) + for write in writes + ] + for write in writes: + failure = _send(client, writing, write) + if failure is not None: + return [Step(change, failure=failure)] + return [Step(change)] + + +def _send(client: Any, writing: Writing, write: Write) -> str | None: + """Send one statement: None when it ran, else the server's reason.""" + from clickhouse_connect.driver.exceptions import ClickHouseError + + # A statement with bound parameters, a password, goes by `raw_query`, which the client sends + # form-encoded in the request body. `command` would put them in the URL. + send = client.raw_query if write.parameters else client.command + try: + send(write.sql, parameters=dict(write.parameters) or None, settings=dict(write.settings)) + except ClickHouseError as error: + return _reason(error, writing) + return None + + +def _reason(error: Exception, writing: Writing) -> str: + """The server's own message, with its error name, and no secret in it.""" + return hide_secrets(server_message(error), writing.passwords.values()) + + +def _changes_to(roles: list[str]) -> str: + """`a change to role a`, or `changes to roles a, b`.""" + if len(roles) == 1: + return f"a change to role {roles[0]}" + return "changes to roles " + ", ".join(roles) + + +def _users(spec: AccessSpec) -> list[User]: + """The declared users that aren't `absent`: none in legacy mode.""" + return [ + declared + for declared in declared_entities(spec) + if isinstance(declared, User) and not declared.absent + ] + + +def _elsewhere(failed: set[Entity], unkept: set[Entity]) -> str | None: + """Why a change waits on a failure, or an unsent replace, of another user or role.""" + if failed: + return f"an earlier change to {_entities(failed)} failed, so it keeps the access it has" + if unkept: + return f"the replace of {_entities(unkept)} couldn't be sent, so it keeps the access it has" + return None + + +def _entities(entities: set[Entity]) -> str: + return ", ".join(sorted(str(entity) for entity in entities)) + + +def _roles_named(names: list[str]) -> str: + """`role a`, or `roles a, b`.""" + return f"role {names[0]}" if len(names) == 1 else f"roles {', '.join(names)}" diff --git a/ch_migrate/access/blocks.py b/ch_migrate/access/blocks.py new file mode 100644 index 0000000..533ac90 --- /dev/null +++ b/ch_migrate/access/blocks.py @@ -0,0 +1,158 @@ +"""Blocks of access.yaml: `migration_role`, `roles` and `users`, read and merged. + +The file's base and each `environments.` block are read on their own, so every problem +names the key path where it was written. An environment block then deep-merges over the base: +mappings merge, lists replace. Each field remembers the path of the block that set it last. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Callable + +from ch_migrate.access.model import Role, User +from ch_migrate.access.reading import Reader, child, describe + +BLOCK_KEYS = ("migration_role", "roles", "users") +MIGRATION_KEYS = ("profile", "grants") +ROLE_KEYS = ("grants", "roles", "absent") +USER_KEYS = ("password", "roles", "default_roles", "grants", "absent") +PROFILE_NAMES = ("core", "legacy") + + +@dataclass +class Entry: + """One declared user or role, or `migration_role`: the fields set, and where.""" + + path: str # the key path of the block that declared it last + fields: dict[str, Any] = field(default_factory=dict) + paths: dict[str, str] = field(default_factory=dict) # each field's key path + + def get(self, key: str, default: Any = None) -> Any: + return self.fields.get(key, default) + + def where(self, key: str) -> str: + """The key path of a field, or where it would go.""" + return self.paths.get(key, child(self.path, key)) + + +@dataclass +class Block: + """The base of the file, or one environment block, or the two merged.""" + + migration: Entry | None = None + roles: dict[str, Entry] = field(default_factory=dict) + users: dict[str, Entry] = field(default_factory=dict) + + +def read_block(reader: Reader, block: dict[str, Any], path: str) -> Block: + """Read the `migration_role`, `roles` and `users` keys of an already-checked mapping.""" + result = Block() + if "migration_role" in block: + section = _Section(child(path, "migration_role"), MIGRATION_KEYS) + result.migration = _entry(reader, block["migration_role"], section) + if "roles" in block: + result.roles = _entries(reader, block["roles"], _Section(child(path, "roles"), ROLE_KEYS)) + if "users" in block: + result.users = _entries(reader, block["users"], _Section(child(path, "users"), USER_KEYS)) + return result + + +def merge(base: Block, override: Block) -> Block: + """Deep-merge an environment block over the base: mappings merge and lists replace.""" + migration = base.migration or override.migration + if base.migration and override.migration: + migration = _merged(base.migration, override.migration) + return Block( + migration, _merged_all(base.roles, override.roles), _merged_all(base.users, override.users) + ) + + +def role(name: str, entry: Entry) -> Role: + return Role( + name, + grants=entry.get("grants", ()), + roles=entry.get("roles", ()), + absent=entry.get("absent", False), + ) + + +def user(name: str, entry: Entry) -> User: + return User( + name, + password=entry.get("password"), + grants=entry.get("grants", ()), + roles=entry.get("roles", ()), + default_roles=entry.get("default_roles"), + absent=entry.get("absent", False), + ) + + +@dataclass(frozen=True) +class _Section: + """Where a declaration sits, and the keys it may hold.""" + + path: str + keys: tuple[str, ...] + + +def _entries(reader: Reader, value: Any, section: _Section) -> dict[str, Entry]: + """Declared users or roles by rendered name; `section.keys` are each one's keys.""" + if value is None: + return {} + if not isinstance(value, dict): + reader.error(section.path, f"expected a mapping of names, found {describe(value)}") + return {} + entries: dict[str, Entry] = {} + for key, body in value.items(): + path = child(section.path, str(key)) + name = reader.name(key, path) + if name is None: + continue + if name in entries: + reader.error(path, f"declares {name} a second time") + continue + entries[name] = _entry(reader, body, _Section(path, section.keys)) + return entries + + +def _entry(reader: Reader, value: Any, section: _Section) -> Entry: + fields = reader.mapping(value, section.path, section.keys) or {} + entry = Entry(section.path) + for key, item in fields.items(): + path = child(section.path, key) + entry.fields[key] = _FIELD_READERS[key](reader, item, path) + entry.paths[key] = path + return entry + + +def _merged_all(base: dict[str, Entry], override: dict[str, Entry]) -> dict[str, Entry]: + merged = dict(base) + for name, entry in override.items(): + merged[name] = _merged(merged[name], entry) if name in merged else entry + return merged + + +def _merged(base: Entry, override: Entry) -> Entry: + return Entry( + override.path, + {**base.fields, **override.fields}, + {**base.paths, **override.paths}, + ) + + +def _profile(reader: Reader, value: Any, path: str) -> str: + if value not in PROFILE_NAMES: + reader.error(path, f"unknown profile {value!r}; the profiles are core and legacy") + return "core" + return str(value) + + +_FIELD_READERS: dict[str, Callable[[Reader, Any, str], Any]] = { + "grants": lambda reader, value, path: reader.grants(value, path), + "roles": lambda reader, value, path: reader.names(value, path), + "default_roles": lambda reader, value, path: reader.names(value, path), + "absent": lambda reader, value, path: reader.flag(value, path), + "password": lambda reader, value, path: reader.secret(value, path), + "profile": _profile, +} diff --git a/ch_migrate/access/bootstrap.py b/ch_migrate/access/bootstrap.py new file mode 100644 index 0000000..1a0d102 --- /dev/null +++ b/ch_migrate/access/bootstrap.py @@ -0,0 +1,398 @@ +"""Bootstrap the database and migration identity, then check as the migration user. + +With access.yaml, use the applier for the additive migration identity only. The remaining +declaration belongs to access apply. Legacy mode retains 0.8's per-node statements and +CURRENT GRANTS, continues past failures, and skips unsupported read-back on old servers. +Refusals and secrets precede every write; later errors return 1 (design 2.5). +""" + +from __future__ import annotations + +from contextlib import closing +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Callable + +from ch_migrate import ui +from ch_migrate.access import applier +from ch_migrate.access.check import Checked, check_migration +from ch_migrate.access.legacy import OPTIONAL_PASSWORDS, legacy_spec +from ch_migrate.access.live import LiveState +from ch_migrate.access.loader import ACCESS_FILE, validate_access +from ch_migrate.access.model import AccessSpec, Grant, Role, User +from ch_migrate.access.planner import Change, Entity, Plan, build_plan, wanted +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.profiles import load_profiles +from ch_migrate.access.render import PasswordText, render_bootstrap_sql +from ch_migrate.access.report import ( + print_change, + reader, + report_check, + report_node, + report_step, +) +from ch_migrate.access.server import ( + AccessError, + Login, + hide_secrets, + open_client, + optional_secret, + read_secret, + require_supported_version, + secret_is_set, +) +from ch_migrate.access.settings import ProjectSettings +from ch_migrate.access.writes import Writing + +# The changes that create a user or role, which a read after the write waits for. +_CREATES = frozenset({"create_role", "create_user"}) + + +@dataclass(frozen=True) +class Bootstrap: + """What `ch-migrate bootstrap ENV` was asked to do.""" + + settings: ProjectSettings + root: Path # the project directory, which holds access.yaml or doesn't + verbose: bool = False # print each statement as it is sent + + +def run(request: Bootstrap) -> int: + """Bootstrap, then check. 0 when it is all in place, else 1, once each failure is named. + + Raises before the first write, with nothing changed. + """ + spec = declaration(request) + settings = request.settings + if spec.legacy: + spec = _without_unset_optional_users(request, spec, _readable) + passwords = _legacy_passwords(settings, spec) + else: + read_secret(settings, spec.migration.password.name) # `check` logs in with it + with closing(open_client(settings, _admin(settings))) as admin: + # Every bootstrap needs 25.8, legacy too: 0.8's already failed on 24.8, and the + # read-back and CHECK GRANT need it. + require_supported_version(str(admin.server_version)) + if spec.legacy: + run = _Run(request, spec, admin) + ui.step(_heading(run)) + return _guarded(lambda: _legacy_writes(run, passwords)) + run = _Run(request, _bootstrapped(spec), admin) + work = _declared_work(run) + ui.step(_heading(run)) + report_node(admin, settings, work.writing.live) + return _guarded(lambda: _declared_writes(run, work)) + + +def dry_run_sql(request: Bootstrap) -> str: + """What `bootstrap` would run, with secret placeholders: no server and no secret.""" + spec = declaration(request) + if spec.legacy: + spec = _without_unset_optional_users(request, spec, secret_is_set) + settings = request.settings + statements = render_bootstrap_sql(_bootstrapped(spec), settings.database) + return "\n".join([*_dry_run_header(settings, spec), *(f"{sql};" for sql in statements)]) + + +def declaration(request: Bootstrap) -> AccessSpec: + """access.yaml for the environment, or legacy mode without one; a `Refusal` if invalid.""" + result = validate_access(request.settings, request.root) + if result.spec is None: + count = len(result.errors) + summary = f"Invalid: {count} error{'' if count == 1 else 's'}." + raise applier.Refusal(*(str(problem) for problem in result.errors), summary) + return result.spec + + +def legacy_bootstrap_sql(settings: ProjectSettings, password: PasswordText) -> str: + """0.8's bootstrap SQL, from the `legacy` profile, for `build_bootstrap_sql`. + + The same statements as 0.8's, with the roles and users created before any grant. + """ + tree = bundled_tree() + profiles, _ = load_profiles(settings.placeholders(), tree) + spec, _ = legacy_spec(settings, profiles["legacy"], tree) + statements = render_bootstrap_sql(spec, settings.database, password) + return "\n".join(f"{sql};" for sql in statements) + + +@dataclass(frozen=True) +class _Run: + """One bootstrap under way: what was asked, what it makes, and the admin's client.""" + + request: Bootstrap + spec: AccessSpec # the migration identity, and in legacy mode its extra roles and users + admin: Any + + @property + def settings(self) -> ProjectSettings: + return self.request.settings + + +@dataclass(frozen=True) +class _Echo: + """The admin's client, printing each statement as it is sent: `bootstrap --verbose`. + + A password is a bound parameter sent in the request body, so it is never part of what is + printed. + """ + + client: Any + + def command(self, sql: str, parameters: Any = None, settings: Any = None) -> Any: + ui.detail(f"{sql};") + return self.client.command(sql, parameters=parameters, settings=settings) + + def raw_query(self, sql: str, parameters: Any = None, settings: Any = None) -> Any: + ui.detail(f"{sql};") + return self.client.raw_query(sql, parameters=parameters, settings=settings) + + +@dataclass(frozen=True) +class _Ending: + """How a bootstrap's writes and check went, for its closing line.""" + + failed: int # changes that failed; a refused best-effort grant is only a warning + checked: Checked | None # None when the check couldn't run + plan_errors: int = 0 # what planning again found that the declaration can't have + pending: int = 0 # changes planning again still found, as `apply` reports them + + +def _without_unset_optional_users( + request: Bootstrap, spec: AccessSpec, is_set: Callable[[ProjectSettings, str], bool] +) -> AccessSpec: + """Legacy mode without each optional user whose password isn't set, as 0.8 skipped it. + + `mcp_user_name` or `dict_reader_name` with no password set made nothing in 0.8; reading the + secret as required stopped 0.9's bootstrap instead. The real run + reads the secret to tell; `--dry-run` reads none, so it asks only whether one is set. + """ + settings = request.settings + unset = { + key: secret + for key, secret in OPTIONAL_PASSWORDS.items() + if getattr(settings, key) and not is_set(settings, secret) + } + for key, secret in unset.items(): + ui.warn( + f"{key} names {getattr(settings, key)}, but {secret} isn't set, so `bootstrap` " + "skips that user and its role, as 0.8 did." + ) + if not unset: + return spec + trimmed = replace( + settings, + mcp_user_name=None if "mcp_user_name" in unset else settings.mcp_user_name, + dict_reader_name=None if "dict_reader_name" in unset else settings.dict_reader_name, + ) + return declaration(replace(request, settings=trimmed)) + + +def _readable(settings: ProjectSettings, name: str) -> bool: + return optional_secret(settings, name) is not None + + +def _legacy_passwords(settings: ProjectSettings, spec: AccessSpec) -> dict[str, str]: + """Every password legacy mode sets, by user, read before the first write.""" + migration = spec.migration + secrets = {migration.user: migration.password} + secrets.update({user.name: user.password for user in spec.users if user.password}) + return {name: read_secret(settings, secret.name) for name, secret in secrets.items()} + + +def _guarded(write: Callable[[], int]) -> int: + """Run the writes and the check; once a write may have run, an error is exit 1, never 2.""" + try: + return write() + except Exception as error: # noqa: BLE001 - after a write, every error is exit 1 + reason = ( + str(error) if isinstance(error, AccessError) else f"{type(error).__name__}: {error}" + ) + ui.error(f"`bootstrap` stopped part-way: {hide_secrets(reason)}") + return 1 + except KeyboardInterrupt: + # Ctrl-C isn't an Exception, but a write may have run all the same. 130, as + # `up` exits. + ui.error("`bootstrap` stopped part-way: interrupted. Run it again: it only adds.") + return 130 + + +def _legacy_writes(run: _Run, passwords: dict[str, str]) -> int: + """Send every statement, then read back and check (Decision 6).""" + settings = run.settings + writing = Writing(run.spec, LiveState(bundled_tree()), None, passwords) # Decision 13 + work = applier.Work( + Plan(), _legacy_steps(run.spec, settings.database), writing, reader(run.admin, settings) + ) + outcome = applier.run(_client(run), work, _report_trouble) + _warn_shortfalls(run, work, outcome) + return _finish(run, _Ending(len(outcome.failures), _check(run))) + + +def _declared_work(run: _Run) -> applier.Work: + """`apply`'s work for the migration identity, with the database first.""" + settings = run.settings + work = applier.prepare(reader(run.admin, settings), applier.Request(settings, run.spec)) + database = Change("create_database", Entity("database", settings.database)) + return replace(work, steps=(database, *work.steps)) + + +def _declared_writes(run: _Run, work: applier.Work) -> int: + outcome = applier.run(_client(run), work, report_step) + after = applier.replan(work, outcome) + for shortfall in after.shortfalls: + ui.warn(str(shortfall)) + for message in after.errors: + ui.error(message) + # A replica still behind at the deadline leaves a change pending even when the check, on + # the node connected to, passes; `apply` reports the same. + if after.pending: + ui.step(f"Still pending for {run.settings.environment}:") + for change in after.pending: + print_change(change) + ending = _Ending(len(outcome.failures), _check(run), len(after.errors), len(after.pending)) + return _finish(run, ending) + + +def _legacy_steps(spec: AccessSpec, database: str) -> tuple[Change, ...]: + """0.8's statements, the database, roles and users first. Legacy mode's read-only and + dictionary roles and users follow the migration identity's own.""" + migration = spec.migration + holders: list[Role | User] = [*spec.roles, *spec.users] + role, user = Entity("role", migration.role), Entity("user", migration.user) + return ( + Change("create_database", Entity("database", database)), + *(Change("create_role", entity) for entity in (role, *map(_entity, spec.roles))), + *(Change("create_user", entity) for entity in (user, *map(_entity, spec.users))), + Change("grant_role", user, roles=(migration.role,)), + *(Change("grant_role", _entity(h), roles=(name,)) for h in holders for name in h.roles), + *(_granting(role, grant) for grant in migration.all_grants), + *(_granting(_entity(h), grant) for h in holders for grant in h.grants), + ) + + +def _warn_shortfalls(run: _Run, work: applier.Work, outcome: applier.Outcome) -> None: + """Read back, as the admin, what landed; each best-effort grant that fell short warns.""" + spec = run.spec + made = [change.entity for change in outcome.made if change.action in _CREATES] + try: + live = work.reader.settled( + wanted(spec), + lambda state: any(state.find(entity.kind, entity.name) is None for entity in made), + ) + except AccessError as error: + ui.warn( + f"Can't read back what landed, as {run.settings.admin_user}: " + f"{hide_secrets(str(error))}" + ) + return + for shortfall in build_plan(spec, live).shortfalls: + ui.warn(str(shortfall)) + + +def _check(run: _Run) -> Checked | None: + """`access check` as the migration user; None, once it is named, for an error.""" + settings, migration = run.settings, run.spec.migration + try: + with closing( + open_client(settings, Login(migration.user, migration.password.name)) + ) as client: + checked = check_migration(client, migration) + except AccessError as error: + ui.error( + f"Can't check the grants of user {migration.user}, logged in as it: " + f"{hide_secrets(str(error))}" + ) + return None + report_check(checked, best_effort=False) + return checked + + +def _finish(run: _Run, ending: _Ending) -> int: + """The last line: complete, or each kind of problem counted. Returns the exit code.""" + problems = _problems(run, ending) + environment = run.settings.environment + if problems: + ui.error(f"Bootstrap of {environment} isn't complete: {'; '.join(problems)}.") + return 1 + ui.success(f"Bootstrap complete for {environment}.") + ui.hint( + f"Next: `ch-migrate new {environment} NAME --table TABLE`, or `ch-migrate up {environment}`." + ) + return 0 + + +def _problems(run: _Run, ending: _Ending) -> list[str]: + """Failed changes, the plan's errors and the check's findings, each counted on its own.""" + problems = [f"{_count(ending.failed, 'change')} failed"] if ending.failed else [] + if ending.plan_errors: + problems.append(f"planning again found {_count(ending.plan_errors, 'error')}") + if ending.pending: + problems.append(f"{_count(ending.pending, 'change')} still pending") + checked = ending.checked + if checked is None: + problems.append("its grants couldn't be checked") + elif checked is not None and checked.missing: + lacking = _count(len(checked.missing), "required grant") + problems.append(f"user {checked.user} lacks {lacking}") + return problems + + +def _heading(run: _Run) -> str: + settings, spec = run.settings, run.spec + where = f"database {settings.database} on {settings.server.host}, as {settings.admin_user}" + if spec.legacy: + return f"Bootstrapping {settings.environment}: {where}, in legacy mode (no {ACCESS_FILE})" + profile = spec.migration.profile.name + return f"Bootstrapping {settings.environment}: {where}, with the {profile} profile" + + +def _dry_run_header(settings: ProjectSettings, spec: AccessSpec) -> list[str]: + if spec.legacy: + source = "legacy mode, as 0.8's `bootstrap`" + else: + source = f"{ACCESS_FILE}: the database and the migration role and user only" + header = [ + f"-- Bootstrap for {settings.environment}, from {source}.", + "-- Replace each with that secret's value as a quoted string, such as", + "-- 'value', before running it. Left in place, it fails to parse.", + ] + cluster = settings.server.cluster + if cluster and not spec.legacy: + header += [ + f"-- With cluster {cluster} set, bootstrap runs each statement ON CLUSTER where users", + "-- and roles are stored on each node's own disk, and each best-effort privilege as", + "-- a grant of its own. Offline, the dry run can't tell, so it shows them without.", + ] + return header + + +def _admin(settings: ProjectSettings) -> Login: + return Login(settings.admin_user, "admin_password") + + +def _bootstrapped(spec: AccessSpec) -> AccessSpec: + """What `bootstrap` makes: with an access.yaml, only the migration identity (2.5).""" + return spec if spec.legacy else replace(spec, roles=(), users=()) + + +def _client(run: _Run) -> Any: + return _Echo(run.admin) if run.request.verbose else run.admin + + +def _report_trouble(step: applier.Step) -> None: + """Legacy mode sends every statement on every run, so it names only what went wrong.""" + if step.failure or step.skipped: + report_step(step) + + +def _entity(holder: Role | User) -> Entity: + return Entity("user" if isinstance(holder, User) else "role", holder.name) + + +def _granting(entity: Entity, grant: Grant) -> Change: + return Change("best_effort" if grant.best_effort else "grant", entity, grant=grant) + + +def _count(count: int, noun: str) -> str: + return f"{count} {noun}" if count == 1 else f"{count} {noun}s" diff --git a/ch_migrate/access/bundle.py b/ch_migrate/access/bundle.py new file mode 100644 index 0000000..54d52f1 --- /dev/null +++ b/ch_migrate/access/bundle.py @@ -0,0 +1,70 @@ +"""Record the bundled privilege list from a server, for `scripts/bundle_privileges.py`. + +`system.privileges` gives the names, aliases, levels and groups. It doesn't mark which +privileges are data sources, and ClickHouse 25.8 and later store an old source spelling such +as `REMOTE ON *.*` as `READ` and `WRITE` on that source. So each global privilege is granted +on `*.*` to a scratch role, and those stored that way are recorded as old spellings. + +This is a maintainer tool: it writes only to the scratch role it is given, and drops it. +`tests/integration/test_access_privilege_list.py` runs it to pin the bundled file. +""" + +from __future__ import annotations + +from typing import Any + +from clickhouse_connect.driver.exceptions import DatabaseError + +from ch_migrate.access.templates import statement + +# The access types an old source spelling is stored as. +_SOURCE_ACCESS = frozenset({"READ", "WRITE"}) + + +def record_privileges(client: Any, scratch_role: str) -> dict[str, Any]: + """The privilege list in the bundled file's shape, read from the server `client` reaches.""" + rows = client.query(statement("bundle", "privileges")).named_results() + privileges = [ + { + "privilege": row["privilege"], + "aliases": list(row["aliases"]), + "level": row["level"], + "parent_group": row["parent_group"], + } + for row in rows + ] + return { + "version": client.server_version, + "privileges": privileges, + "source_spellings": _source_spellings(client, privileges, scratch_role), + } + + +def _source_spellings(client: Any, privileges: list[dict], role: str) -> dict[str, str]: + """Each global privilege the server stores as READ and WRITE, and the source it means.""" + spellings = {} + client.command(statement("bundle", "create_scratch_role", {"role": role})) + try: + for row in privileges: + if row["level"] == "GLOBAL": + source = _stored_source(client, row["privilege"], role) + if source is not None: + spellings[row["privilege"]] = source + finally: + client.command(statement("bundle", "drop_scratch_role", {"role": role})) + return spellings + + +def _stored_source(client: Any, privilege: str, role: str) -> str | None: + """The source ` ON *.*` is stored as ("" for every source), or None.""" + client.command(statement("bundle", "clear_scratch_role", {"role": role})) + values = {"privilege": privilege, "role": role} + try: + client.command(statement("bundle", "grant_on_everything", values)) + except DatabaseError: + return None # a privilege the admin can't pass on is no source spelling it can check + result = client.query(statement("bundle", "scratch_grants"), parameters={"role": role}) + stored = {(access, source) for access, source in result.result_rows} + if not stored or {access for access, _ in stored} - _SOURCE_ACCESS: + return None + return str(min(source for _, source in stored)) diff --git a/ch_migrate/access/check.py b/ch_migrate/access/check.py new file mode 100644 index 0000000..efffcea --- /dev/null +++ b/ch_migrate/access/check.py @@ -0,0 +1,89 @@ +"""`access check`: whether the migration user holds the migration role's grants (2.5). + +It runs as the migration user, for servers where ch-migrate has no admin login, and sends +one `CHECK GRANT` for each grant of the migration role: its profile plus +`migration_role.grants`. `bootstrap` ends with the same check. The SQL is in `sql/check.sql`. + +- **Each grant is checked as the flags it means on its target** (2.7), from the server's own + `system.privileges`, which any login can read. `CHECK GRANT` on a group checks every flag + in it, even those its target can't hold: `ACCESS MANAGEMENT ON db.*` answers 0 right after + that very grant, because the group's user and role rights apply only on `*.*`. A group that + is only partly held still answers 0, so it counts as missing. +- **No grant option.** `CHECK GRANT` takes none, so only the privileges are checked. +- A required grant that isn't held is missing, and the check fails. A best-effort one is a + warning. +""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import Any + +from ch_migrate.access.live import read_tree +from ch_migrate.access.model import Grant, MigrationIdentity +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.access.rights import grant_problems, rights_of +from ch_migrate.access.server import server_errors +from ch_migrate.access.templates import statement +from ch_migrate.access.writes import grant_clause + + +@dataclass(frozen=True) +class Verdict: + """One grant as checked, without grant option, and whether the user holds it.""" + + grant: Grant + held: bool + # Why the server can't check it, such as a privilege it doesn't know. + problem: str = "" + + def __str__(self) -> str: + return f"{self.grant}: {self.problem}" if self.problem else str(self.grant) + + +@dataclass(frozen=True) +class Checked: + """Every grant of the migration role, checked as the migration user.""" + + user: str + role: str + verdicts: tuple[Verdict, ...] + + @property + def exit_code(self) -> int: + """0 when every required grant is held, else 1 (2.5).""" + return 1 if self.missing else 0 + + @property + def missing(self) -> tuple[Verdict, ...]: + """The required grants the user doesn't hold.""" + return tuple(v for v in self.verdicts if not v.held and not v.grant.best_effort) + + @property + def shortfalls(self) -> tuple[Verdict, ...]: + """The best-effort grants the user doesn't hold: warnings only (2.4).""" + return tuple(v for v in self.verdicts if not v.held and v.grant.best_effort) + + @property + def required(self) -> int: + return sum(1 for verdict in self.verdicts if not verdict.grant.best_effort) + + +def check_migration(client: Any, migration: MigrationIdentity) -> Checked: + """Check each grant of the migration role, logged in as the migration user.""" + with server_errors(): + tree = read_tree(client) + verdicts = tuple(_verdict(client, tree, grant) for grant in migration.all_grants) + return Checked(migration.user, migration.role, verdicts) + + +def _verdict(client: Any, tree: PrivilegeTree, grant: Grant) -> Verdict: + checked = replace(grant, grant_option=False) + problems = grant_problems(tree, checked) + if problems: + return Verdict(checked, held=False, problem="; ".join(problems)) + flags = tuple(sorted({right.flag for right in rights_of(tree, checked)})) + sql = statement( + "check", "check_grant", {"grants": grant_clause(replace(checked, privileges=flags))} + ) + return Verdict(checked, held=int(client.command(sql)) == 1) diff --git a/ch_migrate/access/cli.py b/ch_migrate/access/cli.py new file mode 100644 index 0000000..83a3859 --- /dev/null +++ b/ch_migrate/access/cli.py @@ -0,0 +1,309 @@ +"""The access commands and their CLI error boundaries (design 2.5). + +Validate is offline; show and plan use the admin; check uses the migration login. +Apply exits 2 only before any write. Once a write may have run, failures exit 1. +Command help defines outputs and exit codes; live.Reader owns replica settlement. +""" + +from __future__ import annotations + +from contextlib import closing +from pathlib import Path +from typing import Any, Callable, NoReturn + +import click + +from ch_migrate import ui +from ch_migrate.access import applier +from ch_migrate.access.check import check_migration +from ch_migrate.access.loader import ACCESS_FILE, Validation, validate_access +from ch_migrate.access.model import AccessSpec +from ch_migrate.access.planner import Plan, build_plan, wanted +from ch_migrate.access.render import render_sql, users_that_must_exist +from ch_migrate.access.report import ( + print_change, + reader, + report_check, + report_node, + report_step, +) +from ch_migrate.access.server import AccessError, connect_admin, connect_migration, hide_secrets +from ch_migrate.access.settings import ProjectSettings, SettingsError, load_settings +from ch_migrate.access.show import Showing, show_access + +# Exit 2: an invalid file or config.yaml, or an error in a live command (2.5). +INVALID = 2 + + +@click.group() +def access() -> None: + """Declare users, roles and grants in access.yaml.""" + + +@access.command() +@click.argument("environment") +@click.option( + "--sql", "show_sql", is_flag=True, help="Also print the SQL a DBA can review and run." +) +def validate(environment: str, show_sql: bool) -> None: + """Check access.yaml and the built-in profiles for ENVIRONMENT, offline. + + Needs no server and no secrets. Without access.yaml, checks legacy mode: the grants + `bootstrap` gave in 0.8. Exits 0 when valid and 2 when not, listing every error. + """ + settings = _settings_or_exit(environment) + result = validate_access(settings, Path.cwd()) + for warning in result.warnings: + ui.warn(str(warning)) + if result.spec is None: + _report_errors(result) + if show_sql: + click.echo(_sql_text(result.spec)) + _report_valid(result.spec, settings, stderr=show_sql) + + +@access.command() +@click.argument("environment") +@click.argument("names", nargs=-1) +def show(environment: str, names: tuple[str, ...]) -> None: + """Print what the server holds, in access.yaml form, for ENVIRONMENT. + + Covers the users and roles access.yaml declares, or the NAMES given. It is where + adopting existing users and roles starts: write it to another file and copy what you + keep into access.yaml. Redirected into access.yaml itself, the shell empties the file + first. Logs in as the admin, writes nothing and + never shows a password. Exits 0, or 2 on an error. + """ + _exit_2_on_failure(lambda: _show(environment, names)) + + +@access.command() +@click.argument("environment") +def plan(environment: str) -> None: + """Show how the server differs from access.yaml for ENVIRONMENT, changing nothing. + + One line per change: `+` create or grant, `-` revoke or drop, `~` adopt a user or role + that already exists, `!` a grant the migration role holds beyond its profile. Logs in as + the admin and reads no other secret. Exits 0 in sync, 1 with changes pending, 2 on an + error. `!` lines and best-effort warnings leave the exit code alone. + """ + _exit_2_on_failure(lambda: _plan(environment)) + + +@access.command() +@click.argument("environment") +@click.option( + "--reset-passwords", + is_flag=True, + help="Set every declared user's password again, from its secret.", +) +def apply(environment: str, reset_passwords: bool) -> None: + """Make the server match access.yaml for ENVIRONMENT. + + Logs in as the admin and makes what `plan` lists, in order: creates, memberships, + grants, default roles, revokes, then drops. A user's or role's revokes run only once + everything granted to it has landed, and drops only if nothing failed. Best-effort + grants land as far as the admin can give them, and the rest is a warning. A password is + set when its user is created, or again with --reset-passwords. Exits 0 when the server + matches, 1 when a change failed (each one named), and 2 on an error before any change. + """ + _exit_2_on_failure(lambda: _apply(environment, reset_passwords)) + + +@access.command() +@click.argument("environment") +def check(environment: str) -> None: + """Check that the migration user holds the migration role's grants for ENVIRONMENT. + + For servers where ch-migrate has no admin login: it logs in as the migration user and + sends one CHECK GRANT for each grant of the role's profile and `migration_role.grants`, + without grant option, which CHECK GRANT can't check. Exits 0 when every required grant + is held, 1 when one is missing (each one named), and 2 on an error. A missing + best-effort grant is a warning. Needs ClickHouse 25.8 or later. + """ + _exit_2_on_failure(lambda: _check(environment)) + + +def _exit_2_on_failure(command: Callable[[], None]) -> None: + """Run a live command so that an error that stops it prints and exits 2, never 1.""" + try: + command() + return + except (click.exceptions.Exit, click.exceptions.Abort): + raise + except click.ClickException as error: + error.show() + except AccessError as error: + ui.error(hide_secrets(str(error))) + except Exception as error: + ui.error(hide_secrets(f"{type(error).__name__}: {error}")) + raise click.exceptions.Exit(INVALID) + + +def _show(environment: str, names: tuple[str, ...]) -> None: + settings, spec = _declaration(environment) + showing = Showing(settings, spec, names) + showing.check() + with closing(connect_admin(settings)) as client: + live = reader(client, settings).settled(showing.wanted, showing.unsettled) + shown = show_access(showing, live) + for warning in shown.warnings: + ui.warn(warning) + click.echo(shown.text, nl=False) + + +def _plan(environment: str) -> None: + settings, spec = _declaration(environment) + with closing(connect_admin(settings)) as client: + live = reader(client, settings).settled( + wanted(spec), lambda state: build_plan(spec, state).missing_rows + ) + report_node(client, settings, live) + result = build_plan(spec, live) + _report_plan(result, spec) + raise click.exceptions.Exit(result.exit_code) + + +def _apply(environment: str, reset_passwords: bool) -> None: + settings, spec = _declaration(environment) + with closing(connect_admin(settings)) as client: + request = applier.Request(settings, spec, reset_passwords) + try: + work = applier.prepare(reader(client, settings), request) + except applier.Refusal as refusal: + for message in refusal.messages: + ui.error(message) + raise click.exceptions.Exit(INVALID) from None + report_node(client, settings, work.writing.live) + code = _applied(client, work) + raise click.exceptions.Exit(code) + + +def _check(environment: str) -> None: + settings, spec = _declaration(environment) + with closing(connect_migration(settings)) as client: + checked = check_migration(client, spec.migration) + report_check(checked, best_effort=True) + raise click.exceptions.Exit(checked.exit_code) + + +def _applied(client: Any, work: applier.Work) -> int: + """Make the changes, plan again and report. Once a write may have run, nothing exits 2.""" + try: + outcome = applier.run(client, work, report_step) + after = applier.replan(work, outcome) if outcome.wrote else work.plan + except Exception as error: # noqa: BLE001 - after a write, every error is exit 1 + reason = ( + str(error) if isinstance(error, AccessError) else f"{type(error).__name__}: {error}" + ) + ui.error(f"`apply` stopped part-way: {hide_secrets(reason)}") + ui.hint("`ch-migrate access plan` shows what still differs.", stderr=True) + return 1 + except KeyboardInterrupt: + # Ctrl-C isn't an Exception, but a write may have run all the same. 130, as + # `up` exits. + ui.error("`apply` stopped part-way: interrupted.") + ui.hint("`ch-migrate access plan` shows what still differs.", stderr=True) + return 130 + _report_applied(work, outcome, after) + return outcome.exit_code(after) + + +def _declaration(environment: str) -> tuple[ProjectSettings, AccessSpec]: + """config.yaml's settings and the valid declaration, or exit 2 listing every error.""" + settings = _settings_or_exit(environment) + result = validate_access(settings, Path.cwd()) + if result.spec is None: + _report_errors(result) + return settings, result.spec + + +def _settings_or_exit(environment: str) -> ProjectSettings: + try: + return load_settings(environment, Path.cwd() / "config.yaml") + except SettingsError as error: + ui.error(str(error)) + raise click.exceptions.Exit(INVALID) from None + + +def _report_errors(result: Validation) -> NoReturn: + for problem in result.errors: + ui.error(str(problem)) + count = len(result.errors) + ui.error(f"Invalid: {count} error{'' if count == 1 else 's'}.") + raise click.exceptions.Exit(INVALID) + + +def _sql_text(spec: AccessSpec) -> str: + source = "legacy mode, as 0.8's `bootstrap`" if spec.legacy else ACCESS_FILE + header = [ + f"-- Access for {spec.environment}, from {source}.", + "-- Replace each with that secret's value as a quoted string, such as", + "-- 'value', before running it. Left in place, it fails to parse.", + ] + existing = ", ".join(users_that_must_exist(spec)) + if existing: + header.append( + f"-- Users with no password aren't created here and must already exist: {existing}." + ) + return "\n".join([*header, *(f"{sql};" for sql in render_sql(spec))]) + + +def _report_valid(spec: AccessSpec, settings: ProjectSettings, *, stderr: bool) -> None: + migration = f"the migration role {settings.migration_role} holds the {spec.migration.profile.name} profile" + if spec.legacy: + ui.success(f"No {ACCESS_FILE}: legacy mode, where {migration}.", stderr=stderr) + return + declared = f"{_count(spec.roles, 'role')} and {_count(spec.users, 'user')} declared" + ui.success( + f"{ACCESS_FILE} is valid for {spec.environment}: {declared}; {migration}.", stderr=stderr + ) + + +def _report_plan(result: Plan, spec: AccessSpec) -> None: + """The plan's lines on stdout; shortfalls and errors on stderr.""" + if result.errors: + for message in result.errors: + ui.error(message) + return + for change in result.changes: + print_change(change) + for shortfall in result.shortfalls: + ui.warn(str(shortfall)) + count = len(result.pending) + if count: + ui.step(f"{_changes(count)} pending for {spec.environment} ({_source(spec)}).") + else: + ui.success(f"In sync for {spec.environment} ({_source(spec)}): nothing to change.") + + +def _report_applied(work: applier.Work, outcome: applier.Outcome, after: Plan) -> None: + """Best-effort warnings, then in sync, or what still differs and what failed.""" + spec = work.writing.spec + for shortfall in after.shortfalls: + ui.warn(str(shortfall)) + for message in after.errors: + ui.error(message) + where = f"{spec.environment} ({_source(spec)})" + applied = f"{_changes(outcome.counted)} applied" + if not outcome.exit_code(after): + ui.success(f"In sync for {where}: {applied}.") + return + if after.pending: + ui.step(f"Still pending for {where}:") + for change in after.pending: + print_change(change) + failed, skipped = len(outcome.failures), len(outcome.skipped) + ui.error(f"Not in sync for {where}: {applied}, {failed} failed, {skipped} skipped.") + + +def _count(entities: tuple[object, ...], noun: str) -> str: + return f"{len(entities)} {noun}" if len(entities) == 1 else f"{len(entities)} {noun}s" + + +def _source(spec: AccessSpec) -> str: + return "legacy mode, the migration role and user only" if spec.legacy else ACCESS_FILE + + +def _changes(count: int) -> str: + return "1 change" if count == 1 else f"{count} changes" diff --git a/ch_migrate/access/document.py b/ch_migrate/access/document.py new file mode 100644 index 0000000..ba788c5 --- /dev/null +++ b/ch_migrate/access/document.py @@ -0,0 +1,125 @@ +"""Parse access.yaml as `yaml.safe_load` does, and find every key written twice in a mapping. + +YAML keeps the last of two equal keys in one mapping and drops the first without a word, so +two `analyst:` entries would collapse into the second. Two keys are equal when YAML builds +equal values from them, as in the mapping `safe_load` returns: `1` and `1.0`, or `yes` and +`true`, are one key. A merge key (`<<`) repeats nothing, since merging is what it asks for. +""" + +from __future__ import annotations + +from collections.abc import Hashable +from dataclasses import dataclass, field +from typing import Any + +import yaml +from yaml.constructor import SafeConstructor + +from ch_migrate.access.reading import child + +_MERGE_TAG = "tag:yaml.org,2002:merge" +_VALUE_TAG = "tag:yaml.org,2002:value" +_UNKEYED = object() # a key the check leaves alone; building the document reports it + + +@dataclass(frozen=True) +class DuplicateKey: + """A key written again in the same mapping: its key path, and where each one is.""" + + path: str + key: str + first: yaml.Mark + again: yaml.Mark + + @property + def message(self) -> str: + """`duplicate key analyst on lines 2 and 5; ...`, with 1-based lines.""" + if self.first.line == self.again.line: + columns = f"columns {self.first.column + 1} and {self.again.column + 1}" + where = f"line {self.first.line + 1}, {columns}" + else: + where = f"lines {self.first.line + 1} and {self.again.line + 1}" + return f"duplicate key {self.key} on {where}; YAML would silently keep only the last" + + +@dataclass(frozen=True) +class Document: + """One parsed YAML document, and every key it repeats, in the order they appear.""" + + data: Any + duplicates: tuple[DuplicateKey, ...] = () + + +def parse_document(text: str) -> Document: + """Parse one YAML document exactly as `yaml.safe_load` does, listing repeated keys. + + Raises `yaml.YAMLError` where `safe_load` would, with the same message. + """ + loader = yaml.SafeLoader(text) + try: + node = loader.get_single_node() + if node is None: + return Document(None) + duplicates = _Walk().run(node) + return Document(loader.construct_document(node), duplicates) + finally: + loader.dispose() + + +@dataclass +class _Walk: + """Visits every node once, aliases included, collecting repeated keys with their paths.""" + + keys: SafeConstructor = field(default_factory=SafeConstructor) + seen: set[int] = field(default_factory=set) + found: list[DuplicateKey] = field(default_factory=list) + + def run(self, node: yaml.Node) -> tuple[DuplicateKey, ...]: + self.visit(node, "") + return tuple(self.found) + + def visit(self, node: yaml.Node, path: str) -> None: + if id(node) in self.seen: + return + self.seen.add(id(node)) + if isinstance(node, yaml.SequenceNode): + for index, item in enumerate(node.value): + self.visit(item, f"{path}[{index}]") + elif isinstance(node, yaml.MappingNode): + self.mapping(node, path) + + def mapping(self, node: yaml.MappingNode, path: str) -> None: + firsts: dict[Any, yaml.Node] = {} + for key_node, value_node in node.value: + key = self.key(key_node) + key_text = _text(key_node, key) + key_path = child(path, key_text) + if key in firsts: + first = firsts[key].start_mark + again = key_node.start_mark + self.found.append(DuplicateKey(key_path, key_text, first, again)) + elif key is not _UNKEYED: + firsts[key] = key_node + self.visit(value_node, key_path) + + def key(self, node: yaml.Node) -> Any: + """The key as `safe_load` builds it, or `_UNKEYED` for a merge key or a bad key. + + A bad key, such as a list or an unknown tag, fails when the document is built. + """ + if not isinstance(node, yaml.ScalarNode) or node.tag == _MERGE_TAG: + return _UNKEYED + if node.tag == _VALUE_TAG: + return node.value # `=`, which building the mapping reads as a string + try: + key = self.keys.construct_object(node, deep=True) + except yaml.YAMLError: + return _UNKEYED + return key if isinstance(key, Hashable) else _UNKEYED + + +def _text(node: yaml.Node, key: Any) -> str: + """How a key reads in a key path: as `str()` of the built key, like other problems.""" + if key is _UNKEYED: + return str(node.value) if isinstance(node, yaml.ScalarNode) else "?" + return str(key) diff --git a/ch_migrate/access/grants.py b/ch_migrate/access/grants.py new file mode 100644 index 0000000..eed32cd --- /dev/null +++ b/ch_migrate/access/grants.py @@ -0,0 +1,165 @@ +"""The grant syntax: ` ON [WITH GRANT OPTION]`, in ClickHouse's own words. + +A target is `*.*`, `.*` or `.`. `READ` and `WRITE` also take a data source, as +in `READ ON REMOTE`. Column grants and prefix targets (`db.t*`) aren't in v1. Names are +checked offline against the bundled 26.3 list: an alias becomes its canonical name, and an +unknown name is a warning, because `access plan` checks names against the live server. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, replace + +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.bootstrap import validate_identifier + +# The privileges that take a data source as their target. +SOURCE_PRIVILEGES = frozenset({"READ", "WRITE"}) + +_GRANT = re.compile( + r"^(?P.+?)\s+ON\s+(?P\S+)(?P
` or a source such as `REMOTE`" +_SCOPE_WORDS = {"database": "a database (`.*`)", "table": "a table", "global": "`*.*`"} + + +class GrantSyntaxError(ValueError): + """A grant that doesn't parse. The message says why, in words for the person who wrote it.""" + + +@dataclass(frozen=True) +class CheckedGrant: + """A grant with canonical names, and what the offline check found.""" + + grant: Grant + errors: tuple[str, ...] = () + warnings: tuple[str, ...] = () + + +def parse_grant(text: str, *, best_effort: bool = False) -> Grant: + """Parse one grant as written in access.yaml or a profile; names are checked later.""" + text = " ".join(text.split()) + if not text: + raise GrantSyntaxError("the grant is empty") + for pattern, reason in _MISPLACED: + if pattern.search(text): + raise GrantSyntaxError(reason) + match = _GRANT.match(text) + if not match: + raise GrantSyntaxError("expected ` ON [WITH GRANT OPTION]`") + return Grant( + _privileges(match["privileges"]), + _target(match["target"]), + grant_option=bool(match["option"]), + best_effort=best_effort, + ) + + +def check_grant(grant: Grant, tree: PrivilegeTree) -> CheckedGrant: + """Rewrite aliases to canonical names and check the names against the tree.""" + names = [] + warnings = [] + for name in grant.privileges: + canonical = tree.canonical(name) + names.append(canonical or name) + if canonical is None: + warnings.append(_unknown(name)) + privileges = tuple(names) + errors = _source_errors(replace(grant, privileges=privileges), tree) + if errors: + return CheckedGrant(grant, tuple(errors), tuple(warnings)) + target = grant.target + if target.source is not None: + source = tree.source(target.source) + if source is None: + warnings.append(f"the bundled 26.3 list has no source named {target.source}") + target = Target(source=source or target.source) + for name in privileges: + if name in tree.levels and not tree.flags(name, target.scope): + warnings.append(_applies_nowhere(name, target)) + checked = replace(grant, privileges=privileges, target=target) + return CheckedGrant(checked, (), tuple(warnings)) + + +def _privileges(text: str) -> tuple[str, ...]: + if "(" in text: + raise GrantSyntaxError("column grants, such as SELECT(id), aren't supported in v1") + names = tuple(" ".join(name.split()) for name in text.split(",")) + if not all(names): + raise GrantSyntaxError("a privilege in the list is empty") + for name in names: + if not _PRIVILEGE_NAME.match(name): + raise GrantSyntaxError( + f"`{name}` isn't a privilege name: use letters, digits, underscores and spaces" + ) + return names + + +def _target(text: str) -> Target: + if text == "*.*": + return Target() + if "." not in text: + if "*" in text: + raise GrantSyntaxError(f"`{text}` isn't a target: {_TARGET_FORMS}") + return Target(source=_identifier(text, "source name")) + database, table = text.split(".", 1) + if database == "*": + raise GrantSyntaxError(f"`{text}` isn't a target: {_TARGET_FORMS}") + if "*" in database or ("*" in table and table != "*"): + raise GrantSyntaxError(f"prefix targets such as `{text}` aren't supported in v1") + database = _identifier(database, "database name") + return Target(database, None if table == "*" else _identifier(table, "table name")) + + +def _source_errors(grant: Grant, tree: PrivilegeTree) -> list[str]: + """The old source spelling, and READ and WRITE on anything but a source or `*.*`.""" + errors = [] + alone = len(grant.privileges) == 1 + for name in grant.privileges: + new = tree.new_source_spelling(name) + if new is not None: + subject, where = ("this is", "") if alone else (f"{name} is", " in an entry of its own") + spelling = f"`READ, WRITE ON {new}`" + errors.append(f"{subject} the old spelling of a source grant: write {spelling}{where}") + reads = sorted(SOURCE_PRIVILEGES.intersection(grant.privileges)) + if grant.target.scope == "source" and set(grant.privileges) - SOURCE_PRIVILEGES: + errors.append( + "only READ and WRITE take a source as their target; a table is `.
`" + ) + elif reads and grant.target.scope in ("database", "table"): + verb = "takes" if len(reads) == 1 else "take" + errors.append( + f"{' and '.join(reads)} {verb} a source, as in `READ ON REMOTE`, or `*.*` for all" + ) + return errors + + +def _identifier(name: str, label: str) -> str: + try: + return validate_identifier(name, label) + except ValueError as error: + raise GrantSyntaxError(str(error)) from None + + +def _unknown(name: str) -> str: + return f"ClickHouse 26.3 has no privilege named {name}; `access plan` checks it on the server" + + +def _applies_nowhere(name: str, target: Target) -> str: + where = _SCOPE_WORDS.get(target.scope, "a source") + return f"in ClickHouse 26.3, {name} can't be granted on {where}, so the server rejects it" diff --git a/ch_migrate/access/legacy.py b/ch_migrate/access/legacy.py new file mode 100644 index 0000000..6aef8d0 --- /dev/null +++ b/ch_migrate/access/legacy.py @@ -0,0 +1,46 @@ +"""Legacy mode: a project with no access.yaml gets what 0.8's `bootstrap` creates (2.4). + +The migration role holds the `legacy` profile. Each of config.yaml's `mcp_user_name` and +`dict_reader_name` adds the role and user that `legacy_mode.yaml` declares, as 0.8 does. +0.8 also needs that user's password; validation never reads one, so the name alone counts. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from ch_migrate.access.blocks import Block, merge, read_block, role, user +from ch_migrate.access.model import AccessSpec, MigrationIdentity, Profile +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.access.reading import Reader +from ch_migrate.access.settings import ProjectSettings + +LEGACY_MODE_FILE = Path(__file__).with_name("legacy_mode.yaml") +# The config.yaml keys that each add a role and a user in legacy mode. +OPTIONAL_USERS = ("mcp_user_name", "dict_reader_name") +# The secret holding each optional user's password. 0.8 made the user only when it was set. +OPTIONAL_PASSWORDS = {"mcp_user_name": "mcp_password", "dict_reader_name": "dict_reader_password"} + + +def legacy_spec( + settings: ProjectSettings, profile: Profile, tree: PrivilegeTree +) -> tuple[AccessSpec, Reader]: + """The legacy-mode declaration for one environment, and the reader holding its problems.""" + names = {key: getattr(settings, key) for key in OPTIONAL_USERS if getattr(settings, key)} + values = {**settings.placeholders(), **names} + reader = Reader(f"{LEGACY_MODE_FILE.name} (built in)", values, tree, canonical=False) + sections = yaml.safe_load(LEGACY_MODE_FILE.read_text()) + block = Block() + for key in names: + section = reader.mapping(sections[key], key, ("roles", "users")) or {} + block = merge(block, read_block(reader, section, key)) + spec = AccessSpec( + settings.environment, + MigrationIdentity(settings.migration_role, settings.migration_user, profile), + roles=tuple(role(name, entry) for name, entry in block.roles.items()), + users=tuple(user(name, entry) for name, entry in block.users.items()), + legacy=True, + ) + return spec, reader diff --git a/ch_migrate/access/legacy_mode.yaml b/ch_migrate/access/legacy_mode.yaml new file mode 100644 index 0000000..f9dfc93 --- /dev/null +++ b/ch_migrate/access/legacy_mode.yaml @@ -0,0 +1,23 @@ +# Legacy mode: what 0.8's `bootstrap` creates for a project with no access.yaml (design +# note, 2.4). The migration role holds the `legacy` profile. Besides that, config.yaml's +# `mcp_user_name` and `dict_reader_name` each add the role and user below, written as +# access.yaml writes them. They stay additive: 0.8 never converged them. +mcp_user_name: + roles: + '{project}_readonly_role': + grants: + - SELECT ON {db}.* + - SHOW TABLES ON {db}.* + users: + '{mcp_user_name}': + password: {secret: mcp_password} + roles: ['{project}_readonly_role'] + +dict_reader_name: + roles: + # SELECT grants are added per table when dictionaries are created. + '{project}_dict_role': {} + users: + '{dict_reader_name}': + password: {secret: dict_reader_password} + roles: ['{project}_dict_role'] diff --git a/ch_migrate/access/live.py b/ch_migrate/access/live.py new file mode 100644 index 0000000..0d987ba --- /dev/null +++ b/ch_migrate/access/live.py @@ -0,0 +1,445 @@ +"""Read users, roles, grants and memberships as the admin; SQL is in sql/live.sql. + +Use the first creatable storage, never a read-only directory. Local disk is read once. +For replicated storage, read every replica through the configured or unambiguous cluster. +Agreement settles the read; disagreement retries within a deadline, then the connected +node counts. Unavailable replicas fall back to that node's timed missing-row retry. +A fallback reason is emitted once per command, only before an actual wait. +Implicit CLUSTER is detected independently of stored grant rows. See design 2.5. +""" + +from __future__ import annotations + +import json +import time +from dataclasses import dataclass, field, replace +from typing import Any, Callable, Mapping + +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.privileges import PrivilegeTree, tree_from_document +from ch_migrate.access.rights import Holdings, Right, rights_of, stored_rows +from ch_migrate.access.server import server_errors, server_message +from ch_migrate.access.settings import READ_TIMEOUT +from ch_migrate.access.templates import statement + +# `system.user_directories` types: each node's own disk, and Keeper. +LOCAL_STORAGE = "local_directory" +REPLICATED_STORAGE = "replicated" + +_KINDS = ("user", "role") +# What one read takes, one query each. +_TABLES = ("users", "roles", "grants", "role_grants") +# A replica that can't be reached fails the read; it never reads as one that holds nothing. +_EVERY_REPLICA = {"skip_unavailable_shards": 0} +# What some servers grant every login: CLUSTER, where ON CLUSTER needs no grant. +_CLUSTER = Grant(("CLUSTER",), Target()) + + +@dataclass(frozen=True) +class Membership: + """A role that a user or role holds.""" + + role: str + default: bool = True + admin_option: bool = False + + +@dataclass(frozen=True) +class LiveEntity: + """One user or role on the server: its grant rows and the roles it holds. + + A role granted to a user whose default roles are `ALL` becomes a default role at once; + `default_all` and `default_except` say whether that is so. + """ + + holdings: Holdings = Holdings() + memberships: tuple[Membership, ...] = () + default_all: bool = True + default_except: tuple[str, ...] = () + + +@dataclass(frozen=True) +class LiveState: + """One read of the server: its privilege tree, and the users and roles asked about.""" + + tree: PrivilegeTree + # Where a create is stored: `local_directory`, `replicated`, or None when unreadable. + storage: str | None = None + users: Mapping[str, LiveEntity] = field(default_factory=dict) + roles: Mapping[str, LiveEntity] = field(default_factory=dict) + # Of the data sources asked about, those the server takes as a grant target. + sources: frozenset[str] = frozenset() + # The privileges the server grants every login on `*.*`, such as CLUSTER on Cloud. + granted_to_all: frozenset[str] = frozenset() + # Whether every replica returned the same rows; None where only one node was read. + agreed: bool | None = None + # Where they didn't: every replica read. Then the rows are the node connected to's own. + disagreeing: tuple[str, ...] = () + + def find(self, kind: str, name: str) -> LiveEntity | None: + """The user or role with this name, if the read found it.""" + return (self.users if kind == "user" else self.roles).get(name) + + def held_by_all(self, right: Right) -> bool: + """Whether every login holds `right` without a grant, as CLUSTER ON *.* on Cloud.""" + return ( + right.flag in self.granted_to_all and right.scope.depth == 0 and not right.grant_option + ) + + def behind(self, unsettled: Callable[[LiveState], bool]) -> bool: + """Whether to read again: replicas that disagree, or, where one node was read and + it may lag, a row that `unsettled` finds missing.""" + if self.agreed is not None: + return not self.agreed + return self.may_lag and unsettled(self) + + @property + def may_lag(self) -> bool: + """Whether a read can be behind a recent write: anything but a node's own disk.""" + return self.storage != LOCAL_STORAGE + + +@dataclass(frozen=True) +class Wanted: + """What to read: users and roles by name, and the data-source names to check.""" + + names: tuple[str, ...] + sources: tuple[str, ...] = () + + +@dataclass(frozen=True) +class Patience: + """How long to keep reading again before a missing row counts as absent.""" + + seconds: float = READ_TIMEOUT + first_wait: float = 0.05 + longest_wait: float = 2.0 + sleep: Callable[[float], None] = time.sleep + # The clock the time limit is measured on. It runs while a read does, too. + clock: Callable[[], float] = time.monotonic + # Called once, with `seconds`, before the first wait. + on_wait: Callable[[float], None] = lambda seconds: None + + +@dataclass +class Reader: + """Reads what the server holds for one command, as `client`'s login. It only reads. + + How it reads is settled at its first read and kept for the command: every replica + through a cluster, or the node connected to. A fallback is announced through + `on_fallback` only before an actual wait, once per command. Replicas that still + disagree at the deadline are named through `on_disagreement`. + """ + + client: Any + patience: Patience = field(default_factory=Patience) + cluster: str | None = None # config.yaml's `cluster`, when it is set + on_fallback: Callable[[str], None] = lambda reason: None + on_disagreement: Callable[[tuple[str, ...]], None] = lambda replicas: None + _through: str | None = field(default=None, init=False, repr=False) + _chosen: bool = field(default=False, init=False, repr=False) + _fallback_reason: str | None = field(default=None, init=False, repr=False) + + def settled(self, wanted: Wanted, unsettled: Callable[[LiveState], bool]) -> LiveState: + """Read, and read again while a replica may be behind (`read_settled`). + + Replicas that still disagree at the deadline are named, and the last read, of the + node connected to, counts. + """ + patience = replace(self.patience, sleep=self._sleep) + state = read_settled(lambda: self.read(wanted), unsettled, patience) + if state.disagreeing: + self.on_disagreement(state.disagreeing) + return state + + def read(self, wanted: Wanted) -> LiveState: + """One read of everything `wanted` names: of every replica, where they can be read.""" + client = self.client + with server_errors(): + tree = read_tree(client) + storage = _storage(client) + rows = self._rows(tree, storage, {"names": list(wanted.names)}) + return LiveState( + tree=tree, + storage=storage, + users=rows.entities("user"), + roles=rows.entities("role"), + sources=_accepted_sources(client, wanted.sources), + granted_to_all=_granted_to_all(client, tree), + agreed=rows.agreed, + disagreeing=rows.disagreeing, + ) + + def _rows(self, tree: PrivilegeTree, storage: str | None, names: dict[str, Any]) -> _Rows: + from clickhouse_connect.driver.exceptions import DatabaseError + + cluster = self._replicas_through(storage) + if cluster is not None: + try: + return _every_replica(self.client, tree, {**names, "cluster": cluster}) + except (DatabaseError, _NoReplica) as error: + message = server_message(error) if isinstance(error, DatabaseError) else error + self._fall_back(f"Reading every replica of cluster {cluster} failed: {message}") + return _node_rows(self.client, tree, names) + + def _replicas_through(self, storage: str | None) -> str | None: + """The cluster every replica is read through, or None to read one node.""" + if not self._chosen: + self._chosen = True + if storage == REPLICATED_STORAGE: + self._through = self.cluster or self._discovered() + return self._through + + def _discovered(self) -> str | None: + """The cluster that holds this node and other hosts, or None with a fallback reason.""" + from clickhouse_connect.driver.exceptions import DatabaseError + + try: + rows = _query(self.client, "clusters") + except DatabaseError as error: + self._fall_back(f"Can't read system.clusters: {server_message(error)}") + return None + candidates = [row for row in rows if len(row["hosts"]) > 1] + by_hosts: dict[tuple[str, ...], str] = {} + for row in candidates: + by_hosts.setdefault(tuple(row["hosts"]), str(row["cluster"])) + if len(by_hosts) == 1: + return next(iter(by_hosts.values())) + found = ( + f"Clusters {_and(sorted(str(row['cluster']) for row in candidates))} hold this " + "node and list different hosts" + if by_hosts + else "No cluster in system.clusters holds this node and another host" + ) + advice = ( + "Set `cluster` in config.yaml to the cluster whose nodes share these users and roles." + if by_hosts + else "If other nodes share these users and roles, set `cluster` in config.yaml " + "to a cluster that lists them." + ) + self._fall_back(f"{found}. {advice}") + return None + + def _fall_back(self, reason: str) -> None: + self._through = None + self._fallback_reason = reason + + def _sleep(self, seconds: float) -> None: + """Announce a pending fallback only when a missing row really makes us wait.""" + if self._fallback_reason is not None: + self.on_fallback(self._fallback_reason) + self._fallback_reason = None + self.patience.sleep(seconds) + + +def read_settled( + read: Callable[[], LiveState], unsettled: Callable[[LiveState], bool], patience: Patience +) -> LiveState: + """Read, and while a replica may be behind, read again (`LiveState.behind`). + + The waits double from `first_wait` up to `longest_wait`, and none runs past a deadline + `patience.seconds` after the first read starts, on `patience.clock`. The reads count + toward it as well as the waits, so slow reads can't stretch it. One last read may start + at the deadline, so the last wait can see the replicas agree. A read is several + requests, and each is bounded by the driver's request timeout, not the read as a whole. + Once it has passed, the last read counts as it is. + """ + deadline = patience.clock() + patience.seconds + state, wait, announced = read(), patience.first_wait, False + while (left := deadline - patience.clock()) > 0 and state.behind(unsettled): + if not announced: + patience.on_wait(patience.seconds) + announced = True + patience.sleep(min(wait, left)) + wait = min(wait * 2, patience.longest_wait) + state = read() + return state + + +def read_live(client: Any, wanted: Wanted) -> LiveState: + """One read of everything `wanted` names, as the login `client` holds. It only reads.""" + return Reader(client).read(wanted) + + +def read_tree(client: Any) -> PrivilegeTree: + """The server's own `system.privileges`: the images differ, so no bundled list is used. + + Any login can read it, the migration user included. + """ + rows = _query(client, "privileges") + return tree_from_document({"privileges": rows, "source_spellings": {}}) + + +def read_node(client: Any) -> str | None: + """The server's `hostName()`: the node `client` reads. None when the server won't say.""" + from clickhouse_connect.driver.exceptions import ClickHouseError + + try: + rows = _query(client, "node") + except ClickHouseError: + return None + return str(rows[0]["name"]) if rows else None + + +@dataclass(frozen=True) +class _Rows: + """The rows one read returned, before they are sorted by user and role.""" + + tree: PrivilegeTree + existing: Mapping[str, list[dict[str, Any]]] # by kind: the rows of system.users or .roles + grants: list[dict[str, Any]] + memberships: list[dict[str, Any]] + agreed: bool | None = None # whether every replica returned these rows; None: one node + disagreeing: tuple[str, ...] = () # where they didn't, every replica read + + def entities(self, kind: str) -> dict[str, LiveEntity]: + return {row["name"]: self._entity(kind, row) for row in self.existing[kind]} + + def _entity(self, kind: str, row: dict[str, Any]) -> LiveEntity: + column, name = f"{kind}_name", row["name"] + stored = tuple( + flag_row + for grant in self.grants + if grant[column] == name + for flag_row in stored_rows(self.tree, grant) + ) + held = (_membership(held) for held in self.memberships if held[column] == name) + return LiveEntity( + Holdings(stored), + tuple(sorted(held, key=lambda membership: membership.role)), + default_all=bool(row.get("default_roles_all", True)), + default_except=tuple(row.get("default_roles_except", ())), + ) + + +@dataclass(frozen=True) +class _Copies: + """One table as every replica returned it: each row once, and which replicas hold it.""" + + rows: Mapping[str, dict[str, Any]] # by the row's text + held: Mapping[str, frozenset[str]] # by replica: the text of each row it returned + + @property + def agreed(self) -> bool: + return len(set(self.held.values())) <= 1 + + def ordered(self) -> list[dict[str, Any]]: + """Each distinct row, ordered by its text.""" + return [self.rows[text] for text in sorted(self.rows)] + + +class _NoReplica(Exception): + """A read of every replica that no replica answered.""" + + +def _every_replica(client: Any, tree: PrivilegeTree, parameters: dict[str, Any]) -> _Rows: + """The rows of every replica of `parameters["cluster"]`, where they all agree. + + Where they don't, it is the rows of the node `client` is connected to, as when only that + node is read, with the replicas named: no row counts as present or absent from replicas + that disagree. + """ + replicas = [row["replica"] for row in _query_every_replica(client, "replicas", parameters)] + if not replicas: + raise _NoReplica("no replica answered.") + copies = { + name: _copies(_query_every_replica(client, f"replica_{name}", parameters), replicas) + for name in _TABLES + } + if not all(table.agreed for table in copies.values()): + names = {"names": parameters["names"]} + disagreeing = tuple(sorted({r for table in copies.values() for r in table.held})) + return replace(_node_rows(client, tree, names), agreed=False, disagreeing=disagreeing) + return _Rows( + tree, + {kind: copies[f"{kind}s"].ordered() for kind in _KINDS}, + copies["grants"].ordered(), + copies["role_grants"].ordered(), + agreed=True, + ) + + +def _copies(rows: list[dict[str, Any]], replicas: list[str]) -> _Copies: + """Each row by its text, and the texts each replica returned; none for a replica with + no row.""" + by_text: dict[str, dict[str, Any]] = {} + held: dict[str, set[str]] = {replica: set() for replica in replicas} + for row in rows: + replica = str(row.pop("replica")) + text = json.dumps(row, sort_keys=True, default=str) + by_text[text] = row + held.setdefault(replica, set()).add(text) + return _Copies(by_text, {replica: frozenset(texts) for replica, texts in held.items()}) + + +def _node_rows(client: Any, tree: PrivilegeTree, names: dict[str, Any]) -> _Rows: + """The rows of the node `client` is connected to.""" + tables = {name: _query(client, name, names) for name in _TABLES} + return _Rows( + tree, + {kind: tables[f"{kind}s"] for kind in _KINDS}, + tables["grants"], + tables["role_grants"], + ) + + +def _storage(client: Any) -> str | None: + """The storage a create goes to; None when the login can't read `system.user_directories`, + or it lists none that can take a create.""" + from clickhouse_connect.driver.exceptions import DatabaseError + + try: + rows = _query(client, "storage") + except DatabaseError as error: + if "ACCESS_DENIED" in str(error): + return None + raise + return str(rows[0]["type"]) if rows else None + + +def _accepted_sources(client: Any, sources: tuple[str, ...]) -> frozenset[str]: + if not sources: + return frozenset() + rows = _query(client, "accepted_sources", {"sources": list(sources)}) + return frozenset(row["source"] for row in rows) + + +def _granted_to_all(client: Any, tree: PrivilegeTree) -> frozenset[str]: + """CLUSTER, where the server grants it to every login; otherwise nothing. + + `CHECK GRANT` answers 1 for a right the server grants everyone, so CLUSTER is taken to + be granted to all only where the admin's own grants, and its enabled roles', don't hold + it. They are read through the server's privilege tree, so `ALL ON *.*` holds it too. + """ + rights = rights_of(tree, _CLUSTER) + if not rights or int(client.command(statement("live", "cluster_check"))) != 1: + return frozenset() + rows = _query(client, "own_grants") + own = Holdings(tuple(stored for row in rows for stored in stored_rows(tree, row))) + if all(own.holds(right) for right in rights): + return frozenset() + return frozenset(right.flag for right in rights) + + +def _query(client: Any, name: str, parameters: dict[str, Any] | None = None) -> list[dict]: + result = client.query(statement("live", name), parameters=parameters or {}) + return list(result.named_results()) + + +def _query_every_replica(client: Any, name: str, parameters: dict[str, Any]) -> list[dict]: + """`_query`, where a replica that can't be reached fails the read (`_EVERY_REPLICA`).""" + result = client.query(statement("live", name), parameters=parameters, settings=_EVERY_REPLICA) + return list(result.named_results()) + + +def _membership(row: dict[str, Any]) -> Membership: + return Membership( + row["granted_role_name"], + default=bool(row["granted_role_is_default"]), + admin_option=bool(row["with_admin_option"]), + ) + + +def _and(names: list[str]) -> str: + """`a`, `a and b`, or `a, b and c`.""" + return " and ".join(names) if len(names) < 3 else ", ".join(names[:-1]) + f" and {names[-1]}" diff --git a/ch_migrate/access/loader.py b/ch_migrate/access/loader.py new file mode 100644 index 0000000..b264c5b --- /dev/null +++ b/ch_migrate/access/loader.py @@ -0,0 +1,203 @@ +"""Read and validate access.yaml for one environment, or build legacy mode without one. + +`validate_access` is what `access validate` runs. It never connects to a server and never +resolves a secret. It checks the built-in profiles too, and collects every problem: +- errors, which make the file invalid; +- warnings, such as a privilege name the bundled 26.3 list doesn't know. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import yaml + +from ch_migrate.access.blocks import BLOCK_KEYS, Block, Entry, merge, read_block, role, user +from ch_migrate.access.document import parse_document +from ch_migrate.access.legacy import legacy_spec +from ch_migrate.access.model import AccessSpec, MigrationIdentity, Profile +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.profiles import load_profiles +from ch_migrate.access.reading import Problem, Reader, child, describe, yaml_problem +from ch_migrate.access.rights import one_direction +from ch_migrate.access.settings import ProjectSettings + +ACCESS_FILE = "access.yaml" +# An access.yaml that declares nothing would read as `core` with nothing declared, though a +# project that has one empty, or one `access show ENV > access.yaml` emptied before it ran, +# means legacy mode or the file it had. +EMPTY_ACCESS_FILE = ( + "access.yaml is empty. Delete it to keep legacy mode, or declare migration_role in it. " + "`access show ENV > access.yaml` empties the file before `show` runs: write to another " + "file and review it." +) +TOP_KEYS = (*BLOCK_KEYS, "environments") + + +@dataclass(frozen=True) +class Validation: + """The declaration, unless there were errors, and every problem found.""" + + spec: AccessSpec | None + errors: tuple[Problem, ...] = () + warnings: tuple[Problem, ...] = () + + +def validate_access(settings: ProjectSettings, root: Path) -> Validation: + """Validate `root/access.yaml` for one environment; without one, build legacy mode.""" + profiles, profile_reader = load_profiles(settings.placeholders(), bundled_tree()) + path = root / ACCESS_FILE + if path.exists(): + spec, reader = read_access_file(path, settings, profiles) + else: + spec, reader = legacy_spec(settings, profiles["legacy"], bundled_tree()) + errors = (*profile_reader.errors, *reader.errors) + warnings = (*profile_reader.warnings, *reader.warnings) + return Validation(None if errors else spec, errors, warnings) + + +def read_access_file( + path: Path, settings: ProjectSettings, profiles: dict[str, Profile] +) -> tuple[AccessSpec, Reader]: + """Read access.yaml, merge the environment's block over the base, and check the result.""" + reader = Reader(ACCESS_FILE, settings.placeholders(), bundled_tree()) + top = reader.mapping(_load_yaml(path, reader), "", TOP_KEYS) or {} + base = read_block(reader, top, "") + merged = merge(base, _environment_block(reader, top.get("environments"), settings)) + _check_identities(reader, merged, settings) + _check_memberships(reader, merged) + _check_passwords(reader, merged) + _check_source_directions(reader, merged) + return _spec(merged, settings, profiles), reader + + +def declares_access(root: Path) -> bool: + """Whether `root` has an access.yaml; False without one, for legacy mode. + + One that is empty, or holds only comments, raises `ValueError` with `validate`'s message, + so a migration helper decides the same way the access commands do. + """ + path = root / ACCESS_FILE + if not path.exists(): + return False + try: + document = parse_document(path.read_text()) + except yaml.YAMLError as error: + raise ValueError(f"{ACCESS_FILE} can't be read: {error}") from None + if document.data is None: + raise ValueError(EMPTY_ACCESS_FILE) + return True + + +def _load_yaml(path: Path, reader: Reader) -> Any: + """The file as `yaml.safe_load` reads it; each key written twice in a mapping is an error, + and so is a file that holds nothing, or only comments.""" + try: + document = parse_document(path.read_text()) + except yaml.YAMLError as error: + reader.error(*yaml_problem(error)) + return None + if document.data is None: + reader.error("", EMPTY_ACCESS_FILE) + for duplicate in document.duplicates: + reader.error(duplicate.path, duplicate.message) + return document.data + + +def _environment_block(reader: Reader, value: Any, settings: ProjectSettings) -> Block: + """Check every `environments.` block, and return the one for this environment.""" + if value is None: + return Block() + if not isinstance(value, dict): + reader.error("environments", f"expected a mapping of environments, found {describe(value)}") + return Block() + selected = Block() + for name, body in value.items(): + path = child("environments", str(name)) + if str(name) not in settings.environments: + reader.error(path, f"config.yaml has no environment named {name}") + block = read_block(reader, reader.mapping(body, path, BLOCK_KEYS) or {}, path) + if str(name) == settings.environment: + selected = block + return selected + + +def _check_identities(reader: Reader, block: Block, settings: ProjectSettings) -> None: + """The migration identity is the profile's (2.2), and the admin is config.yaml's (2.1).""" + if settings.migration_role in block.roles: + path = block.roles[settings.migration_role].path + reader.error(path, "this is the migration role: add its grants under migration_role.grants") + reserved = { + settings.migration_user: "this is the migration user, which `bootstrap` manages", + settings.admin_user: "this is config.yaml's admin_user, which ch-migrate never changes", + } + for name, reason in reserved.items(): + if name in block.users: + reader.error(block.users[name].path, reason) + + +def _check_memberships(reader: Reader, block: Block) -> None: + """Default roles are among the user's roles, and nothing holds a role declared absent.""" + absent = {name for name, entry in block.roles.items() if entry.get("absent")} + for entry in _present(block): + held = entry.get("roles", ()) + for name in absent.intersection(held): + reader.error(entry.where("roles"), f"{name} is declared absent, so nothing can hold it") + defaults = entry.get("default_roles") + extra = [name for name in defaults or () if name not in held] + if extra: + verb = "isn't" if len(extra) == 1 else "aren't" + reader.error(entry.where("default_roles"), f"{', '.join(extra)} {verb} in roles") + + +def _check_passwords(reader: Reader, block: Block) -> None: + for entry in block.users.values(): + if not entry.get("absent") and "password" not in entry.fields: + reader.warn( + entry.path, + "no password, so it is never created and must already exist. " + "Set `password: {secret: NAME}` to have it created.", + ) + + +def _check_source_directions(reader: Reader, block: Block) -> None: + """`READ` without `WRITE` on a source, or the reverse, holds only with a server setting. + + The built-in profiles aren't checked: what they declare isn't the user's to change. + """ + entries = _present(block) + if block.migration: + entries.insert(0, block.migration) + for entry in entries: + for grant in one_direction(entry.get("grants", ())): + [direction] = grant.privileges + reader.warn( + entry.where("grants"), + f"`{grant}` gives {direction} alone, which the server keeps only with " + "access_control_improvements.enable_read_write_grants on. With it off, " + f"ClickHouse's default, it holds READ and WRITE on {grant.target} together, " + "and `plan` compares them as one grant.", + ) + + +def _spec(block: Block, settings: ProjectSettings, profiles: dict[str, Profile]) -> AccessSpec: + migration = block.migration or Entry("migration_role") + identity = MigrationIdentity( + settings.migration_role, + settings.migration_user, + profiles[migration.get("profile", "core")], + grants=migration.get("grants", ()), + ) + return AccessSpec( + settings.environment, + identity, + roles=tuple(role(name, entry) for name, entry in block.roles.items()), + users=tuple(user(name, entry) for name, entry in block.users.items()), + ) + + +def _present(block: Block) -> list[Entry]: + entries = [*block.roles.values(), *block.users.values()] + return [entry for entry in entries if not entry.get("absent")] diff --git a/ch_migrate/access/model.py b/ch_migrate/access/model.py new file mode 100644 index 0000000..37ba673 --- /dev/null +++ b/ch_migrate/access/model.py @@ -0,0 +1,117 @@ +"""What `access.yaml`, the built-in profiles and legacy mode declare, once validated. + +Every name here is rendered and valid: placeholders such as `{db}` are filled in, and each +name passed `validate_identifier`. Privilege names in `access.yaml` are canonical; the +built-in profiles keep 0.8's spelling, which the server reads the same way. +""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class Target: + """Where a grant applies: `*.*`, `db.*`, `db.table`, or a data source such as `REMOTE`.""" + + database: str | None = None + table: str | None = None + source: str | None = None + + def __str__(self) -> str: + if self.source is not None: + return self.source + return f"{self.database or '*'}.{self.table or '*'}" + + @property + def scope(self) -> str: + """`global`, `database`, `table` or `source`: which privilege levels can apply.""" + if self.source is not None: + return "source" + if self.database is None: + return "global" + return "database" if self.table is None else "table" + + +@dataclass(frozen=True) +class Grant: + """` ON [WITH GRANT OPTION]`, required or best-effort.""" + + privileges: tuple[str, ...] + target: Target + grant_option: bool = False + # Best-effort: the admin gives what it can, as `GRANT CURRENT GRANTS(...)` or, ON CLUSTER, + # one plain GRANT per privilege, and the rest is a warning (2.4; Decision 12). + best_effort: bool = False + + def __str__(self) -> str: + option = " WITH GRANT OPTION" if self.grant_option else "" + return f"{', '.join(self.privileges)} ON {self.target}{option}" + + +@dataclass(frozen=True) +class Secret: + """`{secret: NAME}`: the SSM path at `environments..ssm.NAME`, else `CH__`.""" + + name: str + + +@dataclass(frozen=True) +class Role: + """A role and the roles and grants it holds.""" + + name: str + grants: tuple[Grant, ...] = () + roles: tuple[str, ...] = () + absent: bool = False + + +@dataclass(frozen=True) +class User: + """A user. `default_roles` None means every role it holds is a default role.""" + + name: str + password: Secret | None = None + grants: tuple[Grant, ...] = () + roles: tuple[str, ...] = () + default_roles: tuple[str, ...] | None = None + absent: bool = False + + +@dataclass(frozen=True) +class Profile: + """A built-in grant set for the migration role: `core` or `legacy` (2.4).""" + + name: str + grants: tuple[Grant, ...] + + +@dataclass(frozen=True) +class MigrationIdentity: + """The migration role and user. `bootstrap` and `apply` only ever add to them (2.2).""" + + role: str + user: str + profile: Profile + grants: tuple[Grant, ...] = () # `migration_role.grants`, beyond the profile + password: Secret = Secret("migration_password") + + @property + def all_grants(self) -> tuple[Grant, ...]: + return self.profile.grants + self.grants + + +@dataclass(frozen=True) +class AccessSpec: + """Everything one environment declares. + + `legacy` is True when the project has no `access.yaml`: the migration role holds the + `legacy` profile, and the read-only and dictionary roles and users that `config.yaml` + names are kept additively, as 0.8 kept them (2.4). + """ + + environment: str + migration: MigrationIdentity + roles: tuple[Role, ...] = () + users: tuple[User, ...] = () + legacy: bool = False diff --git a/ch_migrate/access/planner.py b/ch_migrate/access/planner.py new file mode 100644 index 0000000..3dc3ffb --- /dev/null +++ b/ch_migrate/access/planner.py @@ -0,0 +1,408 @@ +"""Compare a declaration with live access; this module never writes. + +Declared users and roles converge; migration access is additive and undeclared entities +are untouched. Scope narrowing needs a whole-set replace because broader grants absorb +narrower ones. Best-effort shortfalls and implicit privileges are not counted changes. +The shared action catalog fixes display text, markers and execution order (design 2.5). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Iterable + +from ch_migrate.access.live import LiveEntity, LiveState, Wanted +from ch_migrate.access.model import AccessSpec, Grant, Role, User +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.access.rights import Right, Scope, Surplus, fold, grant_problems, rights_of + +# Marker and text, in execution order. Bootstrap alone adds create_database; apply adds +# password resets and best-effort tries. Both use this catalog's order. +_ACTIONS = { + "create_database": ("+", "create {entity} if it doesn't exist"), + "adopt": ("~", "adopt {entity}: it exists on the server, and access.yaml now manages it"), + "create_role": ("+", "create {entity}"), + "create_user": ("+", "create {entity}"), + "reset_password": ("+", "reset the password of {entity}"), + "grant_role": ("+", "grant role {role} to {entity}"), + "grant": ("+", "grant {grant} to {entity}"), + "replace": ( + "-", + "replace the grants of {entity} with its declared set in one statement, " + "instead of: {covers}", + ), + "best_effort": ("+", "grant {entity} as much of {grant} as the admin holds (best-effort)"), + "set_default_roles": ("+", "set the default roles of {entity} to {roles}"), + "revoke": ("-", "revoke {grant} from {entity}"), + "revoke_grant_option": ("-", "revoke the grant option for {grant} from {entity}"), + "revoke_role": ("-", "revoke role {role} from {entity}"), + "revoke_admin_option": ("-", "revoke the admin option for role {role} from {entity}"), + "drop_user": ("-", "drop {entity}"), + "drop_role": ("-", "drop {entity}"), + "extra": ("!", "{entity} holds {grant} beyond its profile"), + "extra_grant_option": ("!", "{entity} holds the grant option for {grant} beyond its profile"), + "extra_role": ("!", "{entity} holds role {role} beyond its profile"), +} +ACTION_ORDER = {action: index for index, action in enumerate(_ACTIONS)} +# The changes that put a row on the server. A replica that is behind shows the same gap. +_ADDITIONS = frozenset({"create_role", "create_user", "grant_role", "grant"}) + + +@dataclass(frozen=True) +class Entity: + """A user or a role, by name.""" + + kind: str # "user" or "role" + name: str + + def __str__(self) -> str: + return f"{self.kind} {self.name}" + + +@dataclass(frozen=True) +class Change: + """One line of the plan: something `apply` would do, or a note on what it leaves alone.""" + + action: str # a key of _ACTIONS + entity: Entity + grant: Grant | None = None # the privileges and target of a grant, revoke or extra + # The role of a membership change. For default roles: the roles, or None for all. + roles: tuple[str, ...] | None = None + covers: tuple[Change, ...] = () # the grants and revokes a replace stands in for + + @property + def marker(self) -> str: + return _ACTIONS[self.action][0] + + def __str__(self) -> str: + return _ACTIONS[self.action][1].format( + entity=self.entity, + grant=self.grant, + role=self.roles[0] if self.roles else "", + roles=_default_roles_text(self.roles), + covers="; ".join(str(change) for change in self.covers), + ) + + +@dataclass(frozen=True) +class Shortfall: + """A best-effort grant that is missing or partly held. It is a warning, never a change. + + `grant` is the part that isn't held. With a `reason`, it is the grant as declared, which + this server can't give at all. + """ + + entity: Entity + grant: Grant + reason: str = "" + + def __str__(self) -> str: + if self.reason: + return f"best-effort: {self.entity} can't be given {self.grant}: {self.reason}" + return f"best-effort: {self.entity} lacks {self.grant}" + + +@dataclass(frozen=True) +class Plan: + """What differs, in the order `apply` would change it.""" + + changes: tuple[Change, ...] = () + shortfalls: tuple[Shortfall, ...] = () + # What makes the declaration impossible on this server. `plan` exits 2 for any of them. + errors: tuple[str, ...] = () + # Whether the plan lacks a row a replica that is behind would also lack (2.5). + missing_rows: bool = False + + @property + def pending(self) -> tuple[Change, ...]: + """The changes `apply` would make: every `+` and `-` line.""" + return tuple(change for change in self.changes if change.marker in "+-") + + @property + def exit_code(self) -> int: + """0 in sync, 1 changes pending, 2 error (design note, 2.5).""" + if self.errors: + return 2 + return 1 if self.pending else 0 + + +def build_plan(spec: AccessSpec, live: LiveState) -> Plan: + """Compare what one environment declares with one read of its server.""" + draft = _Draft(spec, live) + _plan_migration(draft) + for declared in declared_entities(spec): + _plan_declared(draft, declared) + return draft.plan() + + +def wanted(spec: AccessSpec) -> Wanted: + """The users and roles a plan reads, and the data sources its grants name.""" + migration = spec.migration + names = [migration.role, migration.user] + grants = list(migration.all_grants) + for declared in declared_entities(spec): + names += [declared.name, *declared.roles] + grants += declared.grants + sources = {grant.target.source for grant in grants if grant.target.source is not None} + return Wanted(tuple(dict.fromkeys(names)), tuple(sorted(sources))) + + +def declared_entities(spec: AccessSpec) -> tuple[Role | User, ...]: + """The roles, then the users, that a plan converges: none in legacy mode (2.4).""" + declared: tuple[Role | User, ...] = (*spec.roles, *spec.users) + return () if spec.legacy else declared + + +def surplus_grant(tree: PrivilegeTree, scope: Scope, flags: Iterable[str]) -> Grant: + """Flags held on one scope, written as a grant with the fewest privilege names.""" + names = fold(tree, flags, scope.kind) + if scope.column is not None: + names = tuple(f"{name}({scope.column})" for name in names) + return Grant(names, scope.target) + + +@dataclass +class _Draft: + """A plan while it is being built.""" + + spec: AccessSpec + live: LiveState + changes: list[Change] = field(default_factory=list) + shortfalls: list[Shortfall] = field(default_factory=list) + errors: list[str] = field(default_factory=list) + absent: bool = False # an error came from something not being on the server + + def subject(self, entity: Entity, grants: tuple[Grant, ...]) -> _Subject: + found = self.live.find(entity.kind, entity.name) + return _Subject(entity, grants, found or LiveEntity(), found is not None) + + def creatable_roles(self) -> set[str]: + """The roles the plan creates if they are missing.""" + declared = () if self.spec.legacy else self.spec.roles + return {self.spec.migration.role, *(role.name for role in declared if not role.absent)} + + def plan(self) -> Plan: + changes = sorted(self.changes, key=lambda change: ACTION_ORDER[change.action]) + missing = self.absent or any( + item.action in _ADDITIONS for change in changes for item in (change, *change.covers) + ) + return Plan(tuple(changes), tuple(self.shortfalls), tuple(self.errors), missing) + + +@dataclass(frozen=True) +class _Subject: + """A user or role being compared: its declared grants, and what the server holds.""" + + entity: Entity + grants: tuple[Grant, ...] + held: LiveEntity # empty when it isn't on the server + exists: bool + declared: Role | User | None = None # None for the migration role + + +def _plan_migration(draft: _Draft) -> None: + """The migration role and user: created and added to, never revoked from (2.2).""" + migration = draft.spec.migration + role = draft.subject(Entity("role", migration.role), migration.all_grants) + if not role.exists: + draft.changes.append(Change("create_role", role.entity)) + draft.changes += [*_missing_grants(draft, role), *_extras(draft.live.tree, role)] + user = Entity("user", migration.user) + found = draft.live.find("user", migration.user) + if found is None: + draft.changes.append(Change("create_user", user)) + if found is None or migration.role not in {held.role for held in found.memberships}: + draft.changes.append(Change("grant_role", user, roles=(migration.role,))) + + +def _plan_declared(draft: _Draft, declared: Role | User) -> None: + """One declared user or role: dropped if `absent`, else created or converged.""" + entity = Entity("user" if isinstance(declared, User) else "role", declared.name) + subject = replace(draft.subject(entity, declared.grants), declared=declared) + if declared.absent: + if subject.exists: + draft.changes.append(Change(f"drop_{entity.kind}", entity)) + return + if not subject.exists and not _creatable(draft, subject): + return + changes = [ + *_memberships(draft, subject), + *_converged_grants(draft, subject), + *_default_roles(subject), + ] + if not subject.exists: + draft.changes += [Change(f"create_{entity.kind}", entity), *changes] + elif changes: + draft.changes += [Change("adopt", entity), *changes] + + +def _creatable(draft: _Draft, subject: _Subject) -> bool: + """A user with no password is never created: it would be a login anyone can use.""" + if not isinstance(subject.declared, User) or subject.declared.password is not None: + return True + draft.absent = True + draft.errors.append( + f"{subject.entity} isn't on the server and has no password, so it can't be created. " + "Set `password: {secret: NAME}`, or create the user first." + ) + return False + + +def _memberships(draft: _Draft, subject: _Subject) -> list[Change]: + """Grant the declared roles that aren't held, and revoke the held ones not declared.""" + assert subject.declared is not None + entity, declared = subject.entity, tuple(dict.fromkeys(subject.declared.roles)) + held = {membership.role: membership for membership in subject.held.memberships} + changes = [ + Change("grant_role", entity, roles=(role,)) + for role in declared + if role not in held and _role_exists(draft, subject, role) + ] + for role, membership in held.items(): + if role not in declared: + changes.append(Change("revoke_role", entity, roles=(role,))) + elif membership.admin_option: + changes.append(Change("revoke_admin_option", entity, roles=(role,))) + return changes + + +def _role_exists(draft: _Draft, subject: _Subject, role: str) -> bool: + """A membership may name a role access.yaml doesn't declare, if the server has it (2.3).""" + if role in draft.creatable_roles() or draft.live.find("role", role) is not None: + return True + draft.absent = True + draft.errors.append( + f"{subject.entity} is declared to hold role {role}, " + "which access.yaml doesn't declare and the server doesn't have." + ) + return False + + +def _converged_grants(draft: _Draft, subject: _Subject) -> list[Change]: + """The grants and revokes that make the held rows match the declared grants exactly. + + If a revoke would take a declared right with it, the whole declared set is replaced in + one statement instead, and the line says what that stands in for. + """ + tree = draft.live.tree + desired = _desired(tree, subject) + surplus = subject.held.holdings.surplus(desired) + changes = [*_missing_grants(draft, subject), *_revokes(tree, subject.entity, surplus)] + if any(item.undermines(desired) for item in surplus): + return [Change("replace", subject.entity, covers=tuple(changes))] + return changes + + +def _missing_grants(draft: _Draft, subject: _Subject) -> list[Change]: + """A grant for each required grant not fully held; a shortfall for a best-effort one.""" + changes = [] + for grant in subject.grants: + problems = _problems(draft.live, grant) + if problems: + if grant.best_effort: + draft.shortfalls.append(Shortfall(subject.entity, grant, "; ".join(problems))) + else: + draft.errors += [f"{subject.entity}: `{grant}`: {problem}." for problem in problems] + continue + lacking = _lacking(draft.live, subject, grant) + if lacking is not None: + if grant.best_effort: + draft.shortfalls.append(Shortfall(subject.entity, lacking)) + else: + changes.append(Change("grant", subject.entity, grant=lacking)) + return changes + + +def _problems(live: LiveState, grant: Grant) -> list[str]: + """Why this server would reject a grant: its names are checked here, live (2.5).""" + problems = grant_problems(live.tree, grant) + source = grant.target.source + if source is not None and source not in live.sources: + problems.append(f"the server has no data source named {source}") + elif source is not None and source != source.upper(): + problems.append( + f"the server stores {source} under another name: " + "write the source's own name, in upper case, such as REMOTE" + ) + return problems + + +def _lacking(live: LiveState, subject: _Subject, grant: Grant) -> Grant | None: + """The part of a grant that isn't fully held, or None when all of it is. + + A right the server grants every login, such as CLUSTER on Cloud, is held without a row. + """ + holdings, tree = subject.held.holdings, live.tree + missing = [ + right.flag + for right in rights_of(tree, grant) + if not holdings.holds(right) and not live.held_by_all(right) + ] + if not missing: + return None + return replace(grant, privileges=fold(tree, missing, grant.target.scope)) + + +def _revokes(tree: PrivilegeTree, entity: Entity, surplus: tuple[Surplus, ...]) -> list[Change]: + """One revoke for each scope's surplus flags, and one for each scope's grant options.""" + groups: dict[tuple[Scope, bool], list[str]] = {} + for item in surplus: + groups.setdefault((item.row.scope, item.option_only), []).append(item.row.flag) + return [ + Change( + "revoke_grant_option" if option_only else "revoke", + entity, + grant=surplus_grant(tree, scope, flags), + ) + for (scope, option_only), flags in sorted(groups.items(), key=_group_order) + ] + + +def _default_roles(subject: _Subject) -> list[Change]: + """Set a user's default roles when they wouldn't match once its memberships do.""" + user = subject.declared + if not isinstance(user, User): + return [] + roles, held = set(user.roles), subject.held + desired = roles if user.default_roles is None else set(user.default_roles) + if held.default_all: + after = roles - set(held.default_except) + else: + after = {membership.role for membership in held.memberships if membership.default} & roles + if after == desired: + return [] + return [Change("set_default_roles", subject.entity, roles=user.default_roles)] + + +def _extras(tree: PrivilegeTree, role: _Subject) -> list[Change]: + """What the migration role holds beyond its profile: listed, and never revoked.""" + groups: dict[tuple[Scope, bool, bool], list[str]] = {} + for item in role.held.holdings.surplus(_desired(tree, role)): + key = (item.row.scope, item.option_only, item.row.grant_option) + groups.setdefault(key, []).append(item.row.flag) + extras = [] + for (scope, option_only, option), flags in sorted(groups.items(), key=_group_order): + grant = replace(surplus_grant(tree, scope, flags), grant_option=option and not option_only) + action = "extra_grant_option" if option_only else "extra" + extras.append(Change(action, role.entity, grant=grant)) + held = (membership.role for membership in role.held.memberships) + return [*extras, *(Change("extra_role", role.entity, roles=(name,)) for name in held)] + + +def _desired(tree: PrivilegeTree, subject: _Subject) -> frozenset[Right]: + """Every right the declared grants ask for, required and best-effort alike.""" + rights: set[Right] = set() + for grant in subject.grants: + rights |= rights_of(tree, grant) + return frozenset(rights) + + +def _group_order(group: tuple[tuple, list[str]]) -> tuple: + (scope, *flags), _ = group + return (str(scope.target), scope.column or "", *flags) + + +def _default_roles_text(roles: tuple[str, ...] | None) -> str: + if roles is None: + return "all its roles" + return ", ".join(roles) or "none" diff --git a/ch_migrate/access/privileges.py b/ch_migrate/access/privileges.py new file mode 100644 index 0000000..8fd5595 --- /dev/null +++ b/ch_migrate/access/privileges.py @@ -0,0 +1,113 @@ +"""Privilege names offline: the bundled list taken from ClickHouse 26.3's `system.privileges`. + +`access validate` has no server, so it resolves privilege names against this list. An unknown +name is a warning, never an error: `access plan` checks names against the live server. + +A privilege with a `level` carries a flag of its own; one without is a group. A privilege +means its own flag plus its descendants' flags, keeping only the levels the target's scope +allows. `system.privileges` doesn't say which privileges are data sources, so the list also +records the old source spellings (`REMOTE ON *.*`), found by granting each one on a scratch +role. `scripts/bundle_privileges.py` writes the list; a test pins it. +""" + +from __future__ import annotations + +import json +from collections import defaultdict +from dataclasses import dataclass +from functools import lru_cache +from pathlib import Path +from typing import Any, Iterable, Mapping + +BUNDLED_LIST = Path(__file__).with_name("privileges_26_3.json") + +# Levels a flag may have and still apply to a database target, or to a table target. +_DATABASE_LEVELS = frozenset({"DATABASE", "TABLE", "DICTIONARY", "VIEW", "COLUMN"}) +_TABLE_LEVELS = frozenset({"TABLE", "DICTIONARY", "VIEW", "COLUMN"}) + + +@dataclass(frozen=True) +class Privilege: + """One row of `system.privileges`.""" + + name: str + aliases: tuple[str, ...] + level: str | None + parent: str | None + + +class PrivilegeTree: + """Privilege names, aliases, levels and groups, plus the old source spellings.""" + + def __init__(self, privileges: Iterable[Privilege], source_spellings: Mapping[str, str]): + self.levels: dict[str, str | None] = {} + self.children: dict[str, list[str]] = defaultdict(list) + # The privileges with no parent group, such as ALL. + self.roots: list[str] = [] + self._names: dict[str, str] = {} + for privilege in privileges: + self.levels[privilege.name] = privilege.level + if privilege.parent is None: + self.roots.append(privilege.name) + else: + self.children[privilege.parent].append(privilege.name) + for spelling in (privilege.name, *privilege.aliases): + self._names[_spelling(spelling)] = privilege.name + # An old spelling, such as REMOTE, and the source it means; "" means every source. + self.source_spellings = dict(source_spellings) + self._sources = {_spelling(s): s for s in self.source_spellings.values() if s} + + def canonical(self, privilege: str) -> str | None: + """The stored name for a privilege or one of its aliases; None when unknown.""" + return self._names.get(_spelling(privilege)) + + def source(self, name: str) -> str | None: + """The stored spelling of a data source, such as `REMOTE`; None when unknown.""" + return self._sources.get(_spelling(name)) + + def new_source_spelling(self, privilege: str) -> str | None: + """For an old source spelling, the target that replaces it: `REMOTE`, or `*.*`.""" + if privilege not in self.source_spellings: + return None + return self.source_spellings[privilege] or "*.*" + + def flags(self, privilege: str, scope: str) -> frozenset[str]: + """The flags a known privilege grants on a scope: global, database, table or source.""" + flags = {privilege} if _level_allowed(self.levels[privilege], scope) else set() + for child in self.children[privilege]: + flags.update(self.flags(child, scope)) + return frozenset(flags) + + +def bundled_tree() -> PrivilegeTree: + """The tree from the bundled 26.3 list.""" + return tree_from_document(_bundled_document()) + + +def tree_from_document(document: Mapping[str, Any]) -> PrivilegeTree: + """Build a tree from a privilege list in the bundled file's shape.""" + privileges = ( + Privilege(row["privilege"], tuple(row["aliases"]), row["level"], row["parent_group"]) + for row in document["privileges"] + ) + return PrivilegeTree(privileges, document["source_spellings"]) + + +@lru_cache(maxsize=1) +def _bundled_document() -> dict[str, Any]: + document: dict[str, Any] = json.loads(BUNDLED_LIST.read_text()) + return document + + +def _spelling(name: str) -> str: + return " ".join(name.upper().split()) + + +def _level_allowed(level: str | None, scope: str) -> bool: + if level is None: + return False + if scope == "global": + return True + if scope == "source": + return level == "SOURCE" + return level in (_DATABASE_LEVELS if scope == "database" else _TABLE_LEVELS) diff --git a/ch_migrate/access/privileges_26_3.json b/ch_migrate/access/privileges_26_3.json new file mode 100644 index 0000000..97bdd36 --- /dev/null +++ b/ch_migrate/access/privileges_26_3.json @@ -0,0 +1,236 @@ +{ + "version": "26.3.62.3", + "privileges": [ + {"privilege": "SHOW DATABASES", "aliases": [], "level": "DATABASE", "parent_group": "SHOW"}, + {"privilege": "SHOW TABLES", "aliases": [], "level": "TABLE", "parent_group": "SHOW"}, + {"privilege": "CHECK", "aliases": [], "level": "TABLE", "parent_group": "ALL"}, + {"privilege": "SHOW COLUMNS", "aliases": [], "level": "COLUMN", "parent_group": "SHOW"}, + {"privilege": "SHOW DICTIONARIES", "aliases": [], "level": "DICTIONARY", "parent_group": "SHOW"}, + {"privilege": "SHOW", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "SHOW FILESYSTEM CACHES", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "SELECT", "aliases": [], "level": "COLUMN", "parent_group": "ALL"}, + {"privilege": "INSERT", "aliases": [], "level": "COLUMN", "parent_group": "ALL"}, + {"privilege": "ALTER UPDATE", "aliases": ["UPDATE"], "level": "COLUMN", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER DELETE", "aliases": ["DELETE"], "level": "COLUMN", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER ADD COLUMN", "aliases": ["ADD COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER MODIFY COLUMN", "aliases": ["MODIFY COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER DROP COLUMN", "aliases": ["DROP COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER COMMENT COLUMN", "aliases": ["COMMENT COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER CLEAR COLUMN", "aliases": ["CLEAR COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER RENAME COLUMN", "aliases": ["RENAME COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER MATERIALIZE COLUMN", "aliases": ["MATERIALIZE COLUMN"], "level": "COLUMN", "parent_group": "ALTER COLUMN"}, + {"privilege": "ALTER COLUMN", "aliases": [], "level": null, "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER MODIFY COMMENT", "aliases": ["MODIFY COMMENT"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER MODIFY DATABASE COMMENT", "aliases": ["MODIFY DATABASE COMMENT"], "level": "DATABASE", "parent_group": "ALTER DATABASE"}, + {"privilege": "ALTER ORDER BY", "aliases": ["ALTER MODIFY ORDER BY", "MODIFY ORDER BY"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER SAMPLE BY", "aliases": ["ALTER MODIFY SAMPLE BY", "MODIFY SAMPLE BY"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER ADD INDEX", "aliases": ["ADD INDEX"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER DROP INDEX", "aliases": ["DROP INDEX"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER MATERIALIZE INDEX", "aliases": ["MATERIALIZE INDEX"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER CLEAR INDEX", "aliases": ["CLEAR INDEX"], "level": "TABLE", "parent_group": "ALTER INDEX"}, + {"privilege": "ALTER INDEX", "aliases": ["INDEX"], "level": null, "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER ADD STATISTICS", "aliases": ["ALTER ADD STATISTIC"], "level": "TABLE", "parent_group": "ALTER STATISTICS"}, + {"privilege": "ALTER DROP STATISTICS", "aliases": ["ALTER DROP STATISTIC"], "level": "TABLE", "parent_group": "ALTER STATISTICS"}, + {"privilege": "ALTER MODIFY STATISTICS", "aliases": ["ALTER MODIFY STATISTIC"], "level": "TABLE", "parent_group": "ALTER STATISTICS"}, + {"privilege": "ALTER MATERIALIZE STATISTICS", "aliases": ["ALTER MATERIALIZE STATISTIC"], "level": "TABLE", "parent_group": "ALTER STATISTICS"}, + {"privilege": "ALTER STATISTICS", "aliases": ["STATISTIC"], "level": null, "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER ADD PROJECTION", "aliases": ["ADD PROJECTION"], "level": "TABLE", "parent_group": "ALTER PROJECTION"}, + {"privilege": "ALTER DROP PROJECTION", "aliases": ["DROP PROJECTION"], "level": "TABLE", "parent_group": "ALTER PROJECTION"}, + {"privilege": "ALTER MATERIALIZE PROJECTION", "aliases": ["MATERIALIZE PROJECTION"], "level": "TABLE", "parent_group": "ALTER PROJECTION"}, + {"privilege": "ALTER CLEAR PROJECTION", "aliases": ["CLEAR PROJECTION"], "level": "TABLE", "parent_group": "ALTER PROJECTION"}, + {"privilege": "ALTER PROJECTION", "aliases": ["PROJECTION"], "level": null, "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER ADD CONSTRAINT", "aliases": ["ADD CONSTRAINT"], "level": "TABLE", "parent_group": "ALTER CONSTRAINT"}, + {"privilege": "ALTER DROP CONSTRAINT", "aliases": ["DROP CONSTRAINT"], "level": "TABLE", "parent_group": "ALTER CONSTRAINT"}, + {"privilege": "ALTER CONSTRAINT", "aliases": ["CONSTRAINT"], "level": null, "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER TTL", "aliases": ["ALTER MODIFY TTL", "MODIFY TTL"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER MATERIALIZE TTL", "aliases": ["MATERIALIZE TTL"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER REWRITE PARTS", "aliases": ["REWRITE PARTS"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER SETTINGS", "aliases": ["ALTER SETTING", "ALTER MODIFY SETTING", "MODIFY SETTING", "RESET SETTING"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER MOVE PARTITION", "aliases": ["ALTER MOVE PART", "MOVE PARTITION", "MOVE PART"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER FETCH PARTITION", "aliases": ["ALTER FETCH PART", "FETCH PARTITION"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER FREEZE PARTITION", "aliases": ["FREEZE PARTITION", "UNFREEZE"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER UNLOCK SNAPSHOT", "aliases": ["UNLOCK SNAPSHOT"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER EXECUTE", "aliases": ["ALTER TABLE EXECUTE"], "level": "TABLE", "parent_group": "ALTER TABLE"}, + {"privilege": "ALTER DATABASE SETTINGS", "aliases": ["ALTER DATABASE SETTING", "ALTER MODIFY DATABASE SETTING", "MODIFY DATABASE SETTING"], "level": "DATABASE", "parent_group": "ALTER DATABASE"}, + {"privilege": "ALTER NAMED COLLECTION", "aliases": [], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "ALTER TABLE", "aliases": [], "level": null, "parent_group": "ALTER"}, + {"privilege": "ALTER DATABASE", "aliases": [], "level": null, "parent_group": "ALTER"}, + {"privilege": "ALTER VIEW MODIFY QUERY", "aliases": ["ALTER TABLE MODIFY QUERY"], "level": "VIEW", "parent_group": "ALTER VIEW"}, + {"privilege": "ALTER VIEW MODIFY REFRESH", "aliases": ["ALTER TABLE MODIFY QUERY"], "level": "VIEW", "parent_group": "ALTER VIEW"}, + {"privilege": "ALTER VIEW MODIFY SQL SECURITY", "aliases": ["ALTER TABLE MODIFY SQL SECURITY"], "level": "VIEW", "parent_group": "ALTER VIEW"}, + {"privilege": "ALTER VIEW", "aliases": [], "level": null, "parent_group": "ALTER"}, + {"privilege": "ALTER", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "CREATE DATABASE", "aliases": [], "level": "DATABASE", "parent_group": "CREATE"}, + {"privilege": "CREATE TABLE", "aliases": [], "level": "TABLE", "parent_group": "CREATE"}, + {"privilege": "CREATE VIEW", "aliases": [], "level": "VIEW", "parent_group": "CREATE"}, + {"privilege": "CREATE DICTIONARY", "aliases": [], "level": "DICTIONARY", "parent_group": "CREATE"}, + {"privilege": "CREATE TEMPORARY TABLE", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE ARBITRARY TEMPORARY TABLE"}, + {"privilege": "CREATE ARBITRARY TEMPORARY TABLE", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE"}, + {"privilege": "CREATE TEMPORARY VIEW", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE"}, + {"privilege": "CREATE FUNCTION", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE"}, + {"privilege": "CREATE WORKLOAD", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE"}, + {"privilege": "CREATE RESOURCE", "aliases": [], "level": "GLOBAL", "parent_group": "CREATE"}, + {"privilege": "CREATE NAMED COLLECTION", "aliases": [], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "CREATE", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "DROP DATABASE", "aliases": [], "level": "DATABASE", "parent_group": "DROP"}, + {"privilege": "DROP TABLE", "aliases": [], "level": "TABLE", "parent_group": "DROP"}, + {"privilege": "DROP VIEW", "aliases": [], "level": "VIEW", "parent_group": "DROP"}, + {"privilege": "DROP DICTIONARY", "aliases": [], "level": "DICTIONARY", "parent_group": "DROP"}, + {"privilege": "DROP FUNCTION", "aliases": [], "level": "GLOBAL", "parent_group": "DROP"}, + {"privilege": "DROP WORKLOAD", "aliases": [], "level": "GLOBAL", "parent_group": "DROP"}, + {"privilege": "DROP RESOURCE", "aliases": [], "level": "GLOBAL", "parent_group": "DROP"}, + {"privilege": "DROP NAMED COLLECTION", "aliases": [], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "DROP", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "UNDROP TABLE", "aliases": [], "level": "TABLE", "parent_group": "ALL"}, + {"privilege": "TRUNCATE", "aliases": ["TRUNCATE TABLE"], "level": "TABLE", "parent_group": "ALL"}, + {"privilege": "OPTIMIZE", "aliases": ["OPTIMIZE TABLE"], "level": "TABLE", "parent_group": "ALL"}, + {"privilege": "BACKUP", "aliases": [], "level": "TABLE", "parent_group": "ALL"}, + {"privilege": "KILL QUERY", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "KILL TRANSACTION", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "MOVE PARTITION BETWEEN SHARDS", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "CREATE USER", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER USER", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP USER", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "CREATE ROLE", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER ROLE", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP ROLE", "aliases": [], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ROLE ADMIN", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "CREATE ROW POLICY", "aliases": ["CREATE POLICY"], "level": "TABLE", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER ROW POLICY", "aliases": ["ALTER POLICY"], "level": "TABLE", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP ROW POLICY", "aliases": ["DROP POLICY"], "level": "TABLE", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "CREATE MASKING POLICY", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER MASKING POLICY", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP MASKING POLICY", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "CREATE QUOTA", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER QUOTA", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP QUOTA", "aliases": [], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "CREATE SETTINGS PROFILE", "aliases": ["CREATE PROFILE"], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALTER SETTINGS PROFILE", "aliases": ["ALTER PROFILE"], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "DROP SETTINGS PROFILE", "aliases": ["DROP PROFILE"], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ALLOW SQL SECURITY NONE", "aliases": ["CREATE SQL SECURITY NONE", "ALLOW SQL SECURITY NONE", "SQL SECURITY NONE", "SECURITY NONE"], "level": "GLOBAL", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "SHOW USERS", "aliases": ["SHOW CREATE USER"], "level": "GLOBAL", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW ROLES", "aliases": ["SHOW CREATE ROLE"], "level": "GLOBAL", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW ROW POLICIES", "aliases": ["SHOW POLICIES", "SHOW CREATE ROW POLICY", "SHOW CREATE POLICY"], "level": "TABLE", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW QUOTAS", "aliases": ["SHOW CREATE QUOTA"], "level": "GLOBAL", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW SETTINGS PROFILES", "aliases": ["SHOW PROFILES", "SHOW CREATE SETTINGS PROFILE", "SHOW CREATE PROFILE"], "level": "GLOBAL", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW MASKING POLICIES", "aliases": ["SHOW CREATE MASKING POLICY"], "level": "GLOBAL", "parent_group": "SHOW ACCESS"}, + {"privilege": "SHOW ACCESS", "aliases": [], "level": null, "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "IMPERSONATE", "aliases": ["EXECUTE AS"], "level": "USER_NAME", "parent_group": "ACCESS MANAGEMENT"}, + {"privilege": "ACCESS MANAGEMENT", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "SHOW NAMED COLLECTIONS", "aliases": ["SHOW NAMED COLLECTIONS"], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "SHOW NAMED COLLECTIONS SECRETS", "aliases": ["SHOW NAMED COLLECTIONS SECRETS"], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "NAMED COLLECTION", "aliases": ["NAMED COLLECTION USAGE", "USE NAMED COLLECTION"], "level": "NAMED_COLLECTION", "parent_group": "NAMED COLLECTION ADMIN"}, + {"privilege": "NAMED COLLECTION ADMIN", "aliases": ["NAMED COLLECTION CONTROL"], "level": "NAMED_COLLECTION", "parent_group": "ALL"}, + {"privilege": "SET DEFINER", "aliases": [], "level": "DEFINER", "parent_group": "ALL"}, + {"privilege": "TABLE ENGINE", "aliases": ["TABLE ENGINE"], "level": "TABLE_ENGINE", "parent_group": "ALL"}, + {"privilege": "SYSTEM SHUTDOWN", "aliases": ["SYSTEM KILL", "SHUTDOWN"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM DROP DNS CACHE", "aliases": ["SYSTEM CLEAR DNS CACHE", "SYSTEM DROP DNS", "DROP DNS CACHE", "DROP DNS"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP CONNECTIONS CACHE", "aliases": ["SYSTEM CLEAR CONNECTIONS CACHE", "SYSTEM DROP CONNECTIONS CACHE", "DROP CONNECTIONS CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM PREWARM MARK CACHE", "aliases": ["SYSTEM PREWARM MARK", "PREWARM MARK CACHE", "PREWARM MARKS"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP MARK CACHE", "aliases": ["SYSTEM CLEAR MARK CACHE", "SYSTEM DROP MARK", "DROP MARK CACHE", "DROP MARKS"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP ICEBERG METADATA CACHE", "aliases": ["SYSTEM CLEAR ICEBERG_METADATA_CACHE", "SYSTEM DROP ICEBERG_METADATA_CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP PARQUET METADATA CACHE", "aliases": ["SYSTEM DROP PARQUET_METADATA_CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM PREWARM PRIMARY INDEX CACHE", "aliases": ["SYSTEM PREWARM PRIMARY INDEX", "PREWARM PRIMARY INDEX CACHE", "PREWARM PRIMARY INDEX"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP PRIMARY INDEX CACHE", "aliases": ["SYSTEM CLEAR PRIMARY INDEX CACHE", "SYSTEM DROP PRIMARY INDEX", "DROP PRIMARY INDEX CACHE", "DROP PRIMARY INDEX"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP UNCOMPRESSED CACHE", "aliases": ["SYSTEM CLEAR UNCOMPRESSED CACHE", "SYSTEM DROP UNCOMPRESSED", "DROP UNCOMPRESSED CACHE", "DROP UNCOMPRESSED"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP VECTOR SIMILARITY INDEX CACHE", "aliases": ["SYSTEM CLEAR VECTOR SIMILARITY INDEX CACHE", "SYSTEM DROP VECTOR SIMILARITY INDEX CACHE", "DROP VECTOR SIMILARITY INDEX CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP TEXT INDEX TOKENS CACHE", "aliases": ["SYSTEM CLEAR TEXT INDEX TOKENS CACHE", "SYSTEM DROP TEXT INDEX TOKENS CACHE", "DROP TEXT INDEX TOKENS CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP TEXT INDEX HEADER CACHE", "aliases": ["SYSTEM CLEAR TEXT INDEX HEADER CACHE", "SYSTEM DROP TEXT INDEX HEADER CACHE", "DROP TEXT INDEX HEADER CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP TEXT INDEX POSTINGS CACHE", "aliases": ["SYSTEM CLEAR TEXT INDEX POSTINGS CACHE", "SYSTEM DROP TEXT INDEX POSTINGS CACHE", "DROP TEXT INDEX POSTINGS CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP TEXT INDEX CACHES", "aliases": ["SYSTEM CLEAR TEXT INDEX CACHES", "SYSTEM DROP TEXT INDEX CACHES", "DROP TEXT INDEX CACHES"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP MMAP CACHE", "aliases": ["SYSTEM CLEAR MMAP CACHE", "SYSTEM DROP MMAP", "DROP MMAP CACHE", "DROP MMAP"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP QUERY CONDITION CACHE", "aliases": ["SYSTEM CLEAR QUERY CONDITION CACHE", "SYSTEM DROP QUERY CONDITION", "DROP QUERY CONDITION CACHE", "DROP QUERY CONDITION"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP QUERY CACHE", "aliases": ["SYSTEM CLEAR QUERY CACHE", "SYSTEM DROP QUERY", "DROP QUERY CACHE", "DROP QUERY"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP COMPILED EXPRESSION CACHE", "aliases": ["SYSTEM CLEAR COMPILED EXPRESSION CACHE", "SYSTEM DROP COMPILED EXPRESSION", "DROP COMPILED EXPRESSION CACHE", "DROP COMPILED EXPRESSIONS"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP FILESYSTEM CACHE", "aliases": ["SYSTEM CLEAR FILESYSTEM CACHE", "SYSTEM DROP FILESYSTEM CACHE", "DROP FILESYSTEM CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP DISTRIBUTED CACHE", "aliases": ["SYSTEM CLEAR DISTRIBUTED CACHE", "SYSTEM DROP DISTRIBUTED CACHE", "DROP DISTRIBUTED CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM SYNC FILESYSTEM CACHE", "aliases": ["SYSTEM REPAIR FILESYSTEM CACHE", "REPAIR FILESYSTEM CACHE", "SYNC FILESYSTEM CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM DROP PAGE CACHE", "aliases": ["SYSTEM CLEAR PAGE CACHE", "SYSTEM DROP PAGE CACHE", "DROP PAGE CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP SCHEMA CACHE", "aliases": ["SYSTEM CLEAR SCHEMA CACHE", "SYSTEM DROP SCHEMA CACHE", "DROP SCHEMA CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP FORMAT SCHEMA CACHE", "aliases": ["SYSTEM CLEAR FORMAT SCHEMA CACHE", "SYSTEM DROP FORMAT SCHEMA CACHE", "DROP FORMAT SCHEMA CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP S3 CLIENT CACHE", "aliases": ["SYSTEM CLEAR S3 CLIENT CACHE", "SYSTEM DROP S3 CLIENT", "DROP S3 CLIENT CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM DROP CACHE"}, + {"privilege": "SYSTEM DROP CACHE", "aliases": ["DROP CACHE"], "level": null, "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RELOAD CONFIG", "aliases": ["RELOAD CONFIG"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD USERS", "aliases": ["RELOAD USERS"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD DICTIONARY", "aliases": ["SYSTEM RELOAD DICTIONARIES", "RELOAD DICTIONARY", "RELOAD DICTIONARIES"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD MODEL", "aliases": ["SYSTEM RELOAD MODELS", "RELOAD MODEL", "RELOAD MODELS"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD FUNCTION", "aliases": ["SYSTEM RELOAD FUNCTIONS", "RELOAD FUNCTION", "RELOAD FUNCTIONS"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD EMBEDDED DICTIONARIES", "aliases": ["RELOAD EMBEDDED DICTIONARIES"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RELOAD ASYNCHRONOUS METRICS", "aliases": ["RELOAD ASYNCHRONOUS METRICS"], "level": "GLOBAL", "parent_group": "SYSTEM RELOAD"}, + {"privilege": "SYSTEM RECONNECT ZOOKEEPER", "aliases": ["SYSTEM RECONNECT ZOOKEEPER", "RECONNECT ZOOKEEPER"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RELOAD", "aliases": [], "level": null, "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RESTART DISK", "aliases": ["SYSTEM RESTART DISK"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM WAIT BLOBS CLEANUP", "aliases": ["SYSTEM WAIT BLOBS CLEANUP"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM MERGES", "aliases": ["SYSTEM STOP MERGES", "SYSTEM START MERGES", "STOP MERGES", "START MERGES"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM TTL MERGES", "aliases": ["SYSTEM STOP TTL MERGES", "SYSTEM START TTL MERGES", "STOP TTL MERGES", "START TTL MERGES"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM FETCHES", "aliases": ["SYSTEM STOP FETCHES", "SYSTEM START FETCHES", "STOP FETCHES", "START FETCHES"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM MOVES", "aliases": ["SYSTEM STOP MOVES", "SYSTEM START MOVES", "STOP MOVES", "START MOVES"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM PULLING REPLICATION LOG", "aliases": ["SYSTEM STOP PULLING REPLICATION LOG", "SYSTEM START PULLING REPLICATION LOG"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM CLEANUP", "aliases": ["SYSTEM STOP CLEANUP", "SYSTEM START CLEANUP"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM VIEWS", "aliases": ["SYSTEM REFRESH VIEW", "SYSTEM START VIEWS", "SYSTEM STOP VIEWS", "SYSTEM START VIEW", "SYSTEM STOP VIEW", "SYSTEM PAUSE VIEWS", "SYSTEM PAUSE VIEW", "SYSTEM CANCEL VIEW", "REFRESH VIEW", "START VIEWS", "STOP VIEWS", "START VIEW", "STOP VIEW", "PAUSE VIEWS", "PAUSE VIEW", "CANCEL VIEW"], "level": "VIEW", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM DISTRIBUTED SENDS", "aliases": ["SYSTEM STOP DISTRIBUTED SENDS", "SYSTEM START DISTRIBUTED SENDS", "STOP DISTRIBUTED SENDS", "START DISTRIBUTED SENDS"], "level": "TABLE", "parent_group": "SYSTEM SENDS"}, + {"privilege": "SYSTEM REPLICATED SENDS", "aliases": ["SYSTEM STOP REPLICATED SENDS", "SYSTEM START REPLICATED SENDS", "STOP REPLICATED SENDS", "START REPLICATED SENDS"], "level": "TABLE", "parent_group": "SYSTEM SENDS"}, + {"privilege": "SYSTEM SENDS", "aliases": ["SYSTEM STOP SENDS", "SYSTEM START SENDS", "STOP SENDS", "START SENDS"], "level": null, "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM REPLICATION QUEUES", "aliases": ["SYSTEM STOP REPLICATION QUEUES", "SYSTEM START REPLICATION QUEUES", "STOP REPLICATION QUEUES", "START REPLICATION QUEUES"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM VIRTUAL PARTS UPDATE", "aliases": ["SYSTEM STOP VIRTUAL PARTS UPDATE", "SYSTEM START VIRTUAL PARTS UPDATE", "STOP VIRTUAL PARTS UPDATE", "START VIRTUAL PARTS UPDATE"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM REDUCE BLOCKING PARTS", "aliases": ["SYSTEM STOP REDUCE BLOCKING PARTS", "SYSTEM START REDUCE BLOCKING PARTS", "STOP REDUCE BLOCKING PARTS", "START REDUCE BLOCKING PARTS"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM DROP REPLICA", "aliases": ["DROP REPLICA"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM SYNC REPLICA", "aliases": ["SYNC REPLICA"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM REPLICA READINESS", "aliases": ["SYSTEM REPLICA READY", "SYSTEM REPLICA UNREADY"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RESTART REPLICA", "aliases": ["RESTART REPLICA"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RESTORE REPLICA", "aliases": ["RESTORE REPLICA"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RESTORE DATABASE REPLICA", "aliases": ["RESTORE DATABASE REPLICA"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM WAIT LOADING PARTS", "aliases": ["WAIT LOADING PARTS"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM SYNC DATABASE REPLICA", "aliases": ["SYNC DATABASE REPLICA"], "level": "DATABASE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM SYNC TRANSACTION LOG", "aliases": ["SYNC TRANSACTION LOG"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM SYNC FILE CACHE", "aliases": ["SYNC FILE CACHE"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM FLUSH DISTRIBUTED", "aliases": ["FLUSH DISTRIBUTED"], "level": "TABLE", "parent_group": "SYSTEM FLUSH"}, + {"privilege": "SYSTEM FLUSH LOGS", "aliases": ["FLUSH LOGS"], "level": "GLOBAL", "parent_group": "SYSTEM FLUSH"}, + {"privilege": "SYSTEM FLUSH ASYNC INSERT QUEUE", "aliases": ["FLUSH ASYNC INSERT QUEUE"], "level": "GLOBAL", "parent_group": "SYSTEM FLUSH"}, + {"privilege": "SYSTEM FLUSH", "aliases": [], "level": null, "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM THREAD FUZZER", "aliases": ["SYSTEM START THREAD FUZZER", "SYSTEM STOP THREAD FUZZER", "START THREAD FUZZER", "STOP THREAD FUZZER"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM UNFREEZE", "aliases": ["SYSTEM UNFREEZE"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM UNLOCK SNAPSHOT", "aliases": ["SYSTEM UNLOCK_SNAPSHOT"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM FAILPOINT", "aliases": ["SYSTEM ENABLE FAILPOINT", "SYSTEM DISABLE FAILPOINT", "SYSTEM WAIT FAILPOINT"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM MEMORY", "aliases": ["SYSTEM ALLOCATE MEMORY", "SYSTEM FREE MEMORY"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM LISTEN", "aliases": ["SYSTEM START LISTEN", "SYSTEM STOP LISTEN"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM JEMALLOC", "aliases": ["SYSTEM JEMALLOC PURGE", "SYSTEM JEMALLOC ENABLE PROFILE", "SYSTEM JEMALLOC DISABLE PROFILE", "SYSTEM JEMALLOC FLUSH PROFILE"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM LOAD PRIMARY KEY", "aliases": ["SYSTEM LOAD PRIMARY KEY"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM UNLOAD PRIMARY KEY", "aliases": ["SYSTEM UNLOAD PRIMARY KEY"], "level": "TABLE", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM INSTRUMENT ADD", "aliases": ["SYSTEM INSTRUMENT ADD"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM INSTRUMENT REMOVE", "aliases": ["SYSTEM INSTRUMENT REMOVE"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM RESET DDL WORKER", "aliases": ["SYSTEM RESET DDL WORKER", "RESET DDL WORKER"], "level": "GLOBAL", "parent_group": "SYSTEM"}, + {"privilege": "SYSTEM", "aliases": [], "level": null, "parent_group": "ALL"}, + {"privilege": "dictGet", "aliases": ["dictHas", "dictGetHierarchy", "dictIsIn"], "level": "DICTIONARY", "parent_group": "ALL"}, + {"privilege": "displaySecretsInShowAndSelect", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "addressToLine", "aliases": [], "level": "GLOBAL", "parent_group": "INTROSPECTION"}, + {"privilege": "addressToLineWithInlines", "aliases": [], "level": "GLOBAL", "parent_group": "INTROSPECTION"}, + {"privilege": "addressToSymbol", "aliases": [], "level": "GLOBAL", "parent_group": "INTROSPECTION"}, + {"privilege": "demangle", "aliases": [], "level": "GLOBAL", "parent_group": "INTROSPECTION"}, + {"privilege": "INTROSPECTION", "aliases": ["INTROSPECTION FUNCTIONS"], "level": null, "parent_group": "ALL"}, + {"privilege": "READ", "aliases": ["SOURCE READ"], "level": "SOURCE", "parent_group": "ALL"}, + {"privilege": "WRITE", "aliases": ["SOURCE WRITE"], "level": "SOURCE", "parent_group": "ALL"}, + {"privilege": "CLUSTER", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "FILE", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "URL", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "REMOTE", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "MONGO", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "REDIS", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "MYSQL", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "POSTGRES", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "SQLITE", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "ODBC", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "JDBC", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "HDFS", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "S3", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "HIVE", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "AZURE", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "KAFKA", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "NATS", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "RABBITMQ", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "SOURCES", "aliases": [], "level": "GLOBAL", "parent_group": "ALL"}, + {"privilege": "ALL", "aliases": ["ALL PRIVILEGES"], "level": null, "parent_group": null}, + {"privilege": "NONE", "aliases": ["USAGE", "NO PRIVILEGES"], "level": null, "parent_group": null} + ], + "source_spellings": {"FILE": "FILE", "URL": "URL", "REMOTE": "REMOTE", "MONGO": "MONGO", "REDIS": "REDIS", "MYSQL": "MYSQL", "POSTGRES": "POSTGRES", "SQLITE": "SQLITE", "ODBC": "ODBC", "JDBC": "JDBC", "HDFS": "HDFS", "S3": "S3", "HIVE": "HIVE", "AZURE": "AZURE", "KAFKA": "KAFKA", "NATS": "NATS", "RABBITMQ": "RABBITMQ", "SOURCES": ""} +} diff --git a/ch_migrate/access/profiles.py b/ch_migrate/access/profiles.py new file mode 100644 index 0000000..a9a5ab4 --- /dev/null +++ b/ch_migrate/access/profiles.py @@ -0,0 +1,33 @@ +"""The built-in grant sets for the migration role, shipped as `profiles/.yaml` (2.4). + +- `core`: what the migration role needs in a new project, with no grant option. +- `legacy`: 0.8's migration role exactly, one entry per statement of `build_bootstrap_sql`. + +Profiles use access.yaml's grant syntax. They keep 0.8's privilege spelling, such as +`DELETE`, so legacy mode renders 0.8's statements as 0.8 wrote them. +""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from ch_migrate.access.blocks import PROFILE_NAMES +from ch_migrate.access.model import Profile +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.access.reading import Reader + +PROFILE_DIR = Path(__file__).with_name("profiles") + + +def load_profiles(values: dict[str, str], tree: PrivilegeTree) -> tuple[dict[str, Profile], Reader]: + """Every built-in profile, rendered with `values`, and the reader holding its problems.""" + reader = Reader("", values, tree, canonical=False) + profiles = {} + for name in PROFILE_NAMES: + reader.file = f"profiles/{name}.yaml (built in)" + document = yaml.safe_load((PROFILE_DIR / f"{name}.yaml").read_text()) + fields = reader.mapping(document, "", ("grants",)) or {} + profiles[name] = Profile(name, reader.grants(fields.get("grants", []), "grants")) + return profiles, reader diff --git a/ch_migrate/access/profiles/core.yaml b/ch_migrate/access/profiles/core.yaml new file mode 100644 index 0000000..739ffcb --- /dev/null +++ b/ch_migrate/access/profiles/core.yaml @@ -0,0 +1,23 @@ +# The `core` profile: what the migration role needs in a new project (design note, 2.4). +# +# - Required grants carry no grant option. Rights for other users and roles come from +# access.yaml, which the admin applies. +# - Best-effort grants are given as `GRANT CURRENT GRANTS(...)`, or ON CLUSTER as one plain +# GRANT per privilege: the admin gives what it can, and a shortfall is a warning. On a +# self-hosted cluster, `up` needs CLUSTER, READ ON REMOTE, SYSTEM SYNC REPLICA and, while +# a mutation on a replicated table is pending, SELECT ON system.replicas. +grants: + - CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON {db}.* + - CREATE VIEW, DROP VIEW, CREATE DICTIONARY, DROP DICTIONARY ON {db}.* + - SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON {db}.* + - SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON {db}.* + - SELECT ON system.databases + - SELECT ON system.tables + - SELECT ON system.mutations + - SELECT ON system.dictionaries + - {grant: SELECT ON system.parts, best_effort: true} + - {grant: SELECT ON system.replicas, best_effort: true} + - {grant: "SYSTEM SYNC REPLICA, SYSTEM SYNC DATABASE REPLICA ON {db}.*", best_effort: true} + - {grant: CLUSTER ON *.*, best_effort: true} + - {grant: READ ON REMOTE, best_effort: true} + - {grant: CREATE TEMPORARY TABLE ON *.*, best_effort: true} diff --git a/ch_migrate/access/profiles/legacy.yaml b/ch_migrate/access/profiles/legacy.yaml new file mode 100644 index 0000000..8bb6dcd --- /dev/null +++ b/ch_migrate/access/profiles/legacy.yaml @@ -0,0 +1,34 @@ +# The `legacy` profile: 0.8's migration role exactly (design note, 2.4). +# +# Each entry is one GRANT statement from 0.8's `build_bootstrap_sql`, in its order and +# spelling. 0.8's `GRANT CURRENT GRANTS(...)` statements are the best-effort entries. +# For projects whose migrations create users or roles: set `migration_role.profile: legacy`. +grants: + # Schema operations (RENAME is part of ALTER) + - CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON {db}.* WITH GRANT OPTION + - CREATE VIEW, DROP VIEW ON {db}.* WITH GRANT OPTION + - CREATE DICTIONARY, DROP DICTIONARY ON {db}.* WITH GRANT OPTION + - CREATE FUNCTION, DROP FUNCTION ON *.* WITH GRANT OPTION + # User and role management, for migrations that create users and roles + - {grant: "CREATE USER, ALTER USER, DROP USER ON *.* WITH GRANT OPTION", best_effort: true} + - CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* WITH GRANT OPTION + - ROLE ADMIN ON *.* WITH GRANT OPTION + # Row-level security + - ACCESS MANAGEMENT ON {db}.* WITH GRANT OPTION + - CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON {db}.* WITH GRANT OPTION + # Data operations and introspection + - SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON {db}.* WITH GRANT OPTION + - SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON {db}.* WITH GRANT OPTION + - CREATE TEMPORARY TABLE ON *.* WITH GRANT OPTION + # System tables + - {grant: SELECT ON system.* WITH GRANT OPTION, best_effort: true} + - SELECT ON system.grants + - SELECT ON system.databases + - SELECT ON system.tables + - SELECT ON system.mutations + - {grant: SELECT ON system.replicas, best_effort: true} + - {grant: SELECT ON system.parts, best_effort: true} + - {grant: "SYSTEM SYNC REPLICA ON {db}.*", best_effort: true} + - {grant: "SYSTEM SYNC DATABASE REPLICA ON {db}.*", best_effort: true} + - {grant: CLUSTER ON *.*, best_effort: true} + - {grant: READ ON REMOTE, best_effort: true} diff --git a/ch_migrate/access/reading.py b/ch_migrate/access/reading.py new file mode 100644 index 0000000..f5a433a --- /dev/null +++ b/ch_migrate/access/reading.py @@ -0,0 +1,191 @@ +"""Reading access YAML: key paths, placeholders, names, secrets and grant entries. + +A `Reader` collects problems instead of raising, so `access validate` can list every error +at once. Each problem names the file, the key path and the reason. A value that fails a +check is left out, and reading carries on with the rest. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field +from typing import Any + +import yaml + +from ch_migrate.access.grants import GrantSyntaxError, check_grant, parse_grant +from ch_migrate.access.model import Grant, Secret +from ch_migrate.access.privileges import PrivilegeTree +from ch_migrate.bootstrap import validate_identifier +from ch_migrate.sql import render_placeholders + +_PLACEHOLDER = re.compile(r"\{(\w+)\}") +_GRANT_KEYS = ("grant", "best_effort") + + +@dataclass(frozen=True) +class Problem: + """An error or warning: the file, the key path in it, and the reason.""" + + file: str + path: str + message: str + + def __str__(self) -> str: + return ": ".join(part for part in (self.file, self.path, self.message) if part) + + +@dataclass +class Reader: + """Reads values from one YAML file, rendering placeholders and collecting problems. + + `canonical` rewrites privilege aliases to canonical names, as `access.yaml` needs. The + built-in files keep 0.8's spelling, so legacy mode renders 0.8's statements exactly. + """ + + file: str + values: dict[str, str] + tree: PrivilegeTree + canonical: bool = True + errors: list[Problem] = field(default_factory=list) + warnings: list[Problem] = field(default_factory=list) + + def mapping(self, value: Any, path: str, keys: tuple[str, ...]) -> dict[str, Any] | None: + """`value` as a mapping holding only `keys`; null reads as empty. None if not a mapping.""" + if value is None: + return {} + if not isinstance(value, dict): + self.error(path, f"expected a mapping, found {describe(value)}") + return None + fields = {} + for key, item in value.items(): + if key in keys: + fields[key] = item + else: + self.error(child(path, str(key)), f"unknown key; the keys here are {_or(keys)}") + return fields + + def grants(self, value: Any, path: str) -> tuple[Grant, ...]: + """A list of grant entries: strings, or `{grant: ..., best_effort: true}`.""" + if not isinstance(value, list): + self.error(path, f"expected a list of grants, found {describe(value)}") + return () + grants = (self._grant(entry, f"{path}[{index}]") for index, entry in enumerate(value)) + return tuple(grant for grant in grants if grant is not None) + + def names(self, value: Any, path: str) -> tuple[str, ...]: + """A list of role names.""" + if not isinstance(value, list): + self.error(path, f"expected a list of role names, found {describe(value)}") + return () + names = (self.name(item, f"{path}[{index}]") for index, item in enumerate(value)) + return tuple(name for name in names if name is not None) + + def flag(self, value: Any, path: str) -> bool: + if not isinstance(value, bool): + self.error(path, f"expected true or false, found {describe(value)}") + return False + return value + + def secret(self, value: Any, path: str) -> Secret | None: + """`{secret: NAME}`: never a password itself.""" + if not isinstance(value, dict) or set(value) != {"secret"}: + self.error(path, "expected {secret: NAME}; access.yaml never holds a password") + return None + name = self.name(value["secret"], child(path, "secret")) + return None if name is None else Secret(name) + + def name(self, value: Any, path: str) -> str | None: + """A user or role name, rendered, that `validate_identifier` accepts.""" + if isinstance(value, dict): + self.error(path, "found a mapping: quote a name that starts with {, as in '{db}_x'") + return None + if not isinstance(value, str): + self.error(path, f"expected a name, found {describe(value)}") + return None + rendered = self.render(value, path) + try: + return None if rendered is None else validate_identifier(rendered, "name") + except ValueError as error: + self.error(path, str(error)) + return None + + def render(self, text: str, path: str) -> str | None: + """Fill in the placeholders; an unknown one is an error.""" + rendered = render_placeholders(text, self.values) + unknown = _PLACEHOLDER.findall(rendered) + if unknown: + known = _or(tuple("{" + name + "}" for name in self.values)) + self.error(path, f"unknown placeholder {{{unknown[0]}}}; the placeholders are {known}") + return None + return rendered + + def error(self, path: str, message: str) -> None: + self.errors.append(Problem(self.file, path, message)) + + def warn(self, path: str, message: str) -> None: + self.warnings.append(Problem(self.file, path, message)) + + def _grant(self, entry: Any, path: str) -> Grant | None: + text, best_effort = self._grant_entry(entry, path) + if text is None: + return None + rendered = self.render(text, path) + if rendered is None: + return None + try: + grant = parse_grant(rendered, best_effort=best_effort) + except GrantSyntaxError as error: + self.error(path, f"`{text}`: {error}") + return None + checked = check_grant(grant, self.tree) + for message in checked.errors: + self.error(path, f"`{text}`: {message}") + for message in checked.warnings: + self.warn(path, f"`{text}`: {message}") + if checked.errors: + return None + return checked.grant if self.canonical else grant + + def _grant_entry(self, entry: Any, path: str) -> tuple[str | None, bool]: + """The grant text and whether it is best-effort.""" + if isinstance(entry, str): + return entry, False + if not isinstance(entry, dict): + found = describe(entry) + self.error( + path, f"expected a grant or {{grant: ..., best_effort: true}}, found {found}" + ) + return None, False + fields = self.mapping(entry, path, _GRANT_KEYS) or {} + best_effort = self.flag(fields.get("best_effort", False), child(path, "best_effort")) + if not isinstance(fields.get("grant"), str): + self.error(child(path, "grant"), "expected the grant as a string") + return None, best_effort + return fields["grant"], best_effort + + +def child(path: str, key: str) -> str: + """The key path of `key` inside `path`.""" + return f"{path}.{key}" if path else key + + +def describe(value: Any) -> str: + """What a YAML value is, in words: `a list`, `a string`, `nothing`.""" + if value is None: + return "nothing" + if isinstance(value, bool): + return "true or false" + kinds = {dict: "a mapping", list: "a list", str: "a string", int: "a number"} + return next((word for kind, word in kinds.items() if isinstance(value, kind)), "a value") + + +def yaml_problem(error: yaml.YAMLError) -> tuple[str, str]: + """Where a YAML error is (`line 3, column 5`, or empty) and what it is.""" + mark = getattr(error, "problem_mark", None) + where = f"line {mark.line + 1}, column {mark.column + 1}" if mark else "" + return where, f"not valid YAML: {getattr(error, 'problem', None) or error}" + + +def _or(choices: tuple[str, ...]) -> str: + return ", ".join(choices[:-1]) + f" or {choices[-1]}" if len(choices) > 1 else choices[0] diff --git a/ch_migrate/access/render.py b/ch_migrate/access/render.py new file mode 100644 index 0000000..fb835cd --- /dev/null +++ b/ch_migrate/access/render.py @@ -0,0 +1,115 @@ +"""The SQL that creates what a declaration holds, for `access validate --sql` and +`bootstrap --dry-run`. + +A DBA can review it and run it where ch-migrate has no admin login. It follows `apply`'s +order (2.5): roles, users, memberships, grants, default roles, then drops. It has no +revokes, because offline nothing says what the server holds. A best-effort grant is a +`GRANT CURRENT GRANTS(...)`. + +Each password is an unquoted placeholder naming its secret, which is never read, so the SQL +fails to parse until a DBA fills it in. A declared user with no password is never created: +on 26.3 a `CREATE USER` with no `IDENTIFIED` clause is a `no_password` login anyone can use. +Its memberships, grants and default roles are still printed, for a user that must already +exist. + +`build_bootstrap_sql`, kept from 0.8, renders legacy mode here too, with each password +written as a quoted string instead of a placeholder. +""" + +from __future__ import annotations + +from typing import Callable + +from ch_migrate.access.model import AccessSpec, Grant, Role, Secret, User +from ch_migrate.access.templates import statement + +# What a password is written as, from the secret it is read from. +PasswordText = Callable[[Secret], str] + + +def render_bootstrap_sql( + spec: AccessSpec, database: str, password: PasswordText | None = None +) -> list[str]: + """What `bootstrap` makes: the database first, then everything `spec` declares.""" + return [_sql("create_database", name=database), *render_sql(spec, password)] + + +def render_sql(spec: AccessSpec, password: PasswordText | None = None) -> list[str]: + """Every statement, without its trailing semicolon, in the order to run them. + + Each password is `password(secret)`; by default, the placeholder naming the secret. + """ + roles = [role for role in spec.roles if not role.absent] + users = [user for user in spec.users if not user.absent] + holders: list[Role | User] = [*roles, *users] + return [ + _sql("create_role", name=spec.migration.role), + *(_sql("create_role", name=role.name) for role in roles), + *_create_users(spec, users, password or password_placeholder), + *_memberships(spec, holders), + *_grants(spec, holders), + *_default_roles(users), + *(_sql("drop_user", name=user.name) for user in spec.users if user.absent), + *(_sql("drop_role", name=role.name) for role in spec.roles if role.absent), + ] + + +def users_that_must_exist(spec: AccessSpec) -> list[str]: + """Declared users with no password: `--sql` doesn't create them, so they must exist.""" + return [user.name for user in spec.users if not user.absent and user.password is None] + + +def password_placeholder(secret: Secret) -> str: + """What `--sql` prints, unquoted, in place of a password: it names the secret to fill in.""" + return f"" + + +def _create_users(spec: AccessSpec, users: list[User], password: PasswordText) -> list[str]: + migration = spec.migration + passwords = [(migration.user, migration.password), *((u.name, u.password) for u in users)] + return [ + _sql("create_user", name=name, password=password(secret)) + for name, secret in passwords + if secret is not None + ] + + +def _memberships(spec: AccessSpec, holders: list[Role | User]) -> list[str]: + statements = [_sql("grant_roles", roles=spec.migration.role, grantee=spec.migration.user)] + for holder in holders: + if holder.roles: + statements.append( + _sql("grant_roles", roles=", ".join(holder.roles), grantee=holder.name) + ) + return statements + + +def _grants(spec: AccessSpec, holders: list[Role | User]) -> list[str]: + statements = [_grant(grant, spec.migration.role) for grant in spec.migration.all_grants] + for holder in holders: + statements += [_grant(grant, holder.name) for grant in holder.grants] + return statements + + +def _default_roles(users: list[User]) -> list[str]: + statements = [] + for user in users: + if user.default_roles: + statements.append( + _sql("set_default_roles", roles=", ".join(user.default_roles), user=user.name) + ) + elif user.default_roles is not None: + statements.append(_sql("set_no_default_roles", user=user.name)) + return statements + + +def _grant(grant: Grant, grantee: str) -> str: + name = "grant_best_effort" if grant.best_effort else "grant" + if grant.grant_option: + name += "_with_grant_option" + privileges = ", ".join(grant.privileges) + return _sql(name, privileges=privileges, target=str(grant.target), grantee=grantee) + + +def _sql(template: str, /, **values: str) -> str: + return statement("render", template, values) diff --git a/ch_migrate/access/report.py b/ch_migrate/access/report.py new file mode 100644 index 0000000..46565b0 --- /dev/null +++ b/ch_migrate/access/report.py @@ -0,0 +1,122 @@ +"""How `access plan`, `apply`, `check` and `bootstrap` print what they do, in `ui`'s style. + +A change made is its plan line on stdout. A failure is an error and a refused best-effort +grant a warning, both on stderr. On a cluster whose users and roles are on each node's own +disk, the node that was read is named on stdout, before any change (Decision 14). Where users +and roles are replicated but every replica can't be read at once, one line on stderr says +why, and another when a read is repeated for a replica that may be behind (2.5). +""" + +from __future__ import annotations + +from typing import Any + +from rich.text import Text + +from ch_migrate import ui +from ch_migrate.access.applier import Step +from ch_migrate.access.check import Checked +from ch_migrate.access.live import LOCAL_STORAGE, LiveState, Patience, Reader, read_node +from ch_migrate.access.planner import Change +from ch_migrate.access.server import address +from ch_migrate.access.settings import ProjectSettings + +# How each marker of a plan line is coloured in a terminal. +MARKER_STYLES = {"+": "green", "-": "red", "~": "cyan", "!": "yellow"} + + +def report_step(step: Step) -> None: + """One change as it is made: its line on stdout, a failure or a skip on stderr.""" + change = step.change + if step.skipped: + ui.warn(f"skipped: {change}, because {step.skipped}") + elif step.failure is None: + print_change(change) + else: + report = ui.warn if change.action == "best_effort" else ui.error + report(f"{change}: {step.failure}") + + +def report_node(client: Any, settings: ProjectSettings, live: LiveState) -> None: + """Name the node `live` was read from, where that is the only node read (Decision 14). + + With `cluster` set and users and roles on each node's own disk, `plan`, `apply` and + `bootstrap` read only the node `client` is connected to. An ON CLUSTER change that + failed on another node goes unseen there, so the line says to run `plan` against each + node. Nothing prints on Keeper storage or on a single node, and legacy `bootstrap` + never calls this. + """ + if settings.server.cluster is None or live.storage != LOCAL_STORAGE: + return + node = read_node(client) or address(settings) + ui.step( + f"Read node {node} only: users and roles are on each node's own disk. After a failed " + f"ON CLUSTER apply, run `ch-migrate access plan {settings.environment}` against each node." + ) + + +def report_check(checked: Checked, *, best_effort: bool) -> None: + """Each required grant the migration user lacks, then the verdict. + + With `best_effort`, each best-effort grant it lacks is a warning too. `bootstrap` leaves + them out, because it has already warned about them as the admin read them. + """ + who = f"user {checked.user}" + missing = checked.missing + for verdict in missing: + ui.error(f"{who} lacks {verdict}") + for verdict in checked.shortfalls if best_effort else (): + ui.warn(f"best-effort: {who} lacks {verdict}") + count, role = len(missing), f"role {checked.role}" + if count: + ui.error(f"{who} lacks {count} of the {checked.required} required grants of {role}.") + else: + ui.success(f"{who} holds every required grant of {role} ({checked.required}).") + + +def reader(client: Any, settings: ProjectSettings) -> Reader: + """How a command reads the server, as `client`'s login (2.5). + + Every replica at once where users and roles are replicated, through config.yaml's + `cluster` or the one found. A replica that is behind is waited for up to + `access_read_timeout`. When the replicas can't be read, one line on stderr says why + only if a missing row makes the command wait. At the deadline, disagreements are named. + """ + seconds = settings.server.read_timeout + return Reader( + client, + Patience(seconds=seconds, on_wait=_say_waiting), + cluster=settings.server.cluster, + on_fallback=lambda reason: _say_fallback(reason, seconds), + on_disagreement=lambda replicas: _say_disagreement(replicas, seconds), + ) + + +def print_change(change: Change) -> None: + marker = (f"{change.marker} ", MARKER_STYLES[change.marker]) + ui.out.print(Text.assemble(marker, str(change))) + + +def _say_waiting(seconds: float) -> None: + ui.step( + f"Something isn't on the server yet. Reading again for up to {seconds:g} s, " + "in case a replica is behind.", + stderr=True, + ) + + +def _say_fallback(reason: str, seconds: float) -> None: + ui.step( + f"Can't read every replica at once, so a missing row is read again for up to " + f"{seconds:g} s. {reason}", + stderr=True, + ) + + +def _say_disagreement(replicas: tuple[str, ...], seconds: float) -> None: + names = ", ".join(replicas[:-1]) + f" and {replicas[-1]}" if len(replicas) > 1 else replicas[0] + ui.step( + f"Replicas {names} still disagree after {seconds:g} s, so what the node connected to " + "holds counts.", + stderr=True, + ) diff --git a/ch_migrate/access/rights.py b/ch_migrate/access/rights.py new file mode 100644 index 0000000..0d90939 --- /dev/null +++ b/ch_migrate/access/rights.py @@ -0,0 +1,280 @@ +"""Rights: what a grant means, one privilege flag at a time (design note, 2.7). + +ClickHouse folds what it stores in `system.grants`. A group may be stored as itself or as +its children, a narrower grant is absorbed by a broader one, and an alias is stored under +its canonical name. So grants are never compared as text. Both sides become rights, one per +privilege flag, scope and grant option, using the `system.privileges` tree of the server +being compared: + +- a privilege with a level carries a flag of its own, and one without is a group; +- a privilege means its own flag plus its descendants' flags, keeping only the flags whose + level the target's scope allows. + +What a user or role holds is read as the server reads it: at each scope the nearest row +decides, and a row with `is_partial_revoke = 1` takes a right away inside a broader grant. + +`READ` and `WRITE` on one source, or on every source at `*.*`, are one grant to ClickHouse +unless `access_control_improvements.enable_read_write_grants` is on. That setting is off by +default and can't be read from SQL. With it off, `READ ON S3` reads back as `READ` and +`WRITE`: at once where users and roles are stored in Keeper or the grant ran ON CLUSTER, and +after a restart elsewhere. So a declared right in one direction covers the other direction +too: that one is never surplus (design note, Decision 12). +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Iterable, Mapping + +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.privileges import PrivilegeTree + +_SCOPE_WORDS = { + "global": "`*.*`", + "database": "a database", + "table": "a table", + "source": "a source", +} +# The two directions of a source grant, each mapped to the other. +_OTHER_DIRECTION = {"READ": "WRITE", "WRITE": "READ"} + + +@dataclass(frozen=True) +class Scope: + """Where a right applies: `*.*`, `db.*`, `db.table`, a column, or a data source.""" + + database: str | None = None + table: str | None = None + column: str | None = None + source: str | None = None + + @classmethod + def of(cls, target: Target) -> Scope: + return cls(target.database, target.table, None, target.source) + + def contains(self, other: Scope) -> bool: + """True when everything `other` covers is inside this scope.""" + if self.depth == 0: + return True + if self.source is not None or other.source is not None: + return self.source == other.source + if self.database != other.database: + return False + if self.table is None: + return True + return self.table == other.table and self.column in (None, other.column) + + @property + def depth(self) -> int: + """How narrow the scope is: 0 for `*.*`, up to 3 for a column.""" + if self.column is not None: + return 3 + return {"global": 0, "database": 1, "source": 1, "table": 2}[self.kind] + + @property + def kind(self) -> str: + """`global`, `database`, `table` or `source`: which privilege levels can apply.""" + return self.target.scope + + @property + def target(self) -> Target: + """The grant target this scope is on; a column is on its table.""" + return Target(self.database, self.table, self.source) + + +@dataclass(frozen=True) +class Right: + """One privilege flag on one scope, with or without grant option.""" + + flag: str + scope: Scope + grant_option: bool = False + + +@dataclass(frozen=True) +class StoredRow: + """One flag of a `system.grants` row: a grant, or a revoke inside a broader grant.""" + + flag: str + scope: Scope + grant_option: bool = False + revoke: bool = False + + def decides(self, option: bool) -> bool: + """Whether the row says anything about the right itself, or about its grant option. + + A grant with grant option gives both. A revoke takes both away, unless it carries + `grant_option`, which takes away only the option. + """ + if self.revoke: + return option or not self.grant_option + return self.grant_option or not option + + +@dataclass(frozen=True) +class Surplus: + """A held row that no desired right covers: the whole right, or only its grant option.""" + + row: StoredRow + option_only: bool = False + + def undermines(self, desired: Iterable[Right]) -> bool: + """Whether revoking it takes a desired right with it: the same flag, strictly inside. + + The narrower grant can't be granted first, because the broader one absorbs it. So + this is the case `apply` replaces the whole declared set for (design note, 2.5). + """ + held = self.row + return any( + right.flag == held.flag + and right.scope != held.scope + and held.scope.contains(right.scope) + and (right.grant_option or not self.option_only) + for right in desired + ) + + +@dataclass(frozen=True) +class Holdings: + """Every `system.grants` row of one user or role, one flag each.""" + + rows: tuple[StoredRow, ...] = () + + def holds(self, right: Right) -> bool: + """Whether every part of a right is held, with its grant option if it has one.""" + if not self._decided(right, option=False): + return False + return not right.grant_option or self._decided(right, option=True) + + def surplus(self, desired: frozenset[Right]) -> tuple[Surplus, ...]: + """The grant rows that the desired rights don't cover. + + A desired `READ` or `WRITE` covers the other direction on the same scope too. + """ + found = [] + covers = _both_directions(desired) + for row in self.rows: + if row.revoke: + continue + covering = [ + right + for right in covers + if right.flag == row.flag and right.scope.contains(row.scope) + ] + if not covering: + found.append(Surplus(row)) + elif row.grant_option and not any(right.grant_option for right in covering): + found.append(Surplus(row, option_only=True)) + return tuple(found) + + def _decided(self, right: Right, *, option: bool) -> bool: + """The nearest row at or above the scope grants it, and no revoke sits inside it.""" + nearest: StoredRow | None = None + for row in self.rows: + if row.flag != right.flag or not row.decides(option): + continue + if row.revoke and row.scope != right.scope and right.scope.contains(row.scope): + return False + if row.scope.contains(right.scope): + if nearest is None or row.scope.depth > nearest.scope.depth: + nearest = row + return nearest is not None and not nearest.revoke + + +def rights_of(tree: PrivilegeTree, grant: Grant) -> frozenset[Right]: + """The rights a grant asks for; a name the server doesn't know asks for nothing.""" + scope = Scope.of(grant.target) + flags: set[str] = set() + for name in grant.privileges: + privilege = tree.canonical(name) + if privilege is not None: + flags.update(tree.flags(privilege, scope.kind)) + return frozenset(Right(flag, scope, grant.grant_option) for flag in flags) + + +def grant_problems(tree: PrivilegeTree, grant: Grant) -> list[str]: + """Why the server would reject a grant: a name it doesn't know, or one with no flag here.""" + problems = [] + kind = grant.target.scope + for name in grant.privileges: + privilege = tree.canonical(name) + if privilege is None: + problems.append(f"the server has no privilege named {name}") + elif not tree.flags(privilege, kind): + problems.append(f"the server can't grant {privilege} on {_SCOPE_WORDS[kind]}") + return problems + + +def stored_rows(tree: PrivilegeTree, row: Mapping[str, Any]) -> list[StoredRow]: + """One `system.grants` row as the flags it stands for. + + A row the tree can't expand keeps its own name, so it still counts as held and is + never skipped. That covers a grant on something other than a database, table or data + source, such as `TABLE ENGINE ON MergeTree`: its `access_object` reads as the scope. + """ + scope = Scope(row["database"], row["table"], row["column"], row["access_object"] or None) + name = str(row["access_type"]) + known = tree.canonical(name) + flags = tree.flags(known, scope.kind) if known is not None else frozenset() + option, revoke = bool(row["grant_option"]), bool(row["is_partial_revoke"]) + return [StoredRow(flag, scope, option, revoke) for flag in sorted(flags or {name})] + + +def fold(tree: PrivilegeTree, flags: Iterable[str], kind: str) -> tuple[str, ...]: + """The fewest privilege names that mean exactly these flags on a scope of this kind. + + A group is named only when the set holds every flag the group has there. So a revoke + written with these names never takes away more than the set: narrowing `ALTER` to + `ALTER UPDATE` revokes the other `ALTER` leaves, never `ALTER` itself (design note, 2.7). + + On a data source the flags stay as they are: `READ, WRITE ON S3` is never `ALL ON S3`, + which the server doesn't take. + """ + if kind == "source": + return tuple(sorted(flags)) + folding = _Folding(tree, kind, set(flags)) + for root in tree.roots: + folding.visit(root) + return tuple(sorted([*folding.names, *folding.left])) + + +def one_direction(grants: Iterable[Grant]) -> list[Grant]: + """Where one user's or role's grants give `READ` or `WRITE` but not both. + + One grant for each source, or `*.*`, naming the one direction given there. + """ + directions: dict[Target, set[str]] = {} + for grant in grants: + named = set(_OTHER_DIRECTION).intersection(grant.privileges) + if named and grant.target.scope in ("source", "global"): + directions.setdefault(grant.target, set()).update(named) + return [Grant(tuple(named), target) for target, named in directions.items() if len(named) == 1] + + +@dataclass +class _Folding: + """A walk down the privilege tree, naming each group the flags left hold all of.""" + + tree: PrivilegeTree + kind: str + left: set[str] + names: list[str] = field(default_factory=list) + + def visit(self, privilege: str) -> None: + flags = self.tree.flags(privilege, self.kind) + if flags and flags <= self.left: + self.names.append(privilege) + self.left -= flags + return + for child in self.tree.children.get(privilege, ()): + self.visit(child) + + +def _both_directions(rights: frozenset[Right]) -> frozenset[Right]: + """The rights, plus the other direction of each `READ` or `WRITE`, on the same scope.""" + others = { + Right(_OTHER_DIRECTION[right.flag], right.scope, right.grant_option) + for right in rights + if right.flag in _OTHER_DIRECTION + } + return rights | others diff --git a/ch_migrate/access/server.py b/ch_migrate/access/server.py new file mode 100644 index 0000000..222db4d --- /dev/null +++ b/ch_migrate/access/server.py @@ -0,0 +1,196 @@ +"""Connecting for the live `access` commands, and the server version they need. + +`show` and `plan` log in as config.yaml's `admin_user` and resolve only the admin's secret. +`apply` logs in the same way, then reads the passwords of the users it sets one for, through +`read_secret`, before its first write. `check` logs in as the migration user. Every live +command connects through `connect`, so each one refuses a server older than 25.8 the same +way: 24.8 has no `CHECK GRANT` and no `READ ON ` (design note, 2.5). `bootstrap` +opens its clients with `open_client` and checks the version itself, legacy mode included. + +Whatever stops a live command is an `AccessError`. The command prints it and exits 2, +because exit 1 means "changes pending" for `plan`. +""" + +from __future__ import annotations + +import io +import os +import re +from contextlib import contextmanager, redirect_stderr +from dataclasses import dataclass +from typing import Any, Iterator + +from ch_migrate.access.settings import ProjectSettings, ServerSettings +from ch_migrate.secrets import ( # hide_secrets is re-exported for the access commands + SSMJsonKeyError, + SSMSecretNotFoundError, + get_secret, + hide_secrets, +) +from ch_migrate.sql import clean_database_error + +# The oldest ClickHouse the live access commands run on (design note, Decision 11). +MINIMUM_VERSION = (25, 8) + +_VERSION = re.compile(r"^(\d+)\.(\d+)") +# The driver's wrapping around the server's own message, and the URL it adds. +_DRIVER_PREFIX = re.compile(r"^.*?DB::Exception: ") +_FOR_URL = re.compile(r"\s*\(for url [^)]*\)") +# The server's name for an error, such as `(ACCESS_DENIED)`. +_ERROR_NAME = re.compile(r"\(([A-Z][A-Z0-9_]+)\)") + + +class AccessError(Exception): + """A live access command can't go on. The command prints the message and exits 2.""" + + +@dataclass(frozen=True) +class Login: + """A user to log in as, and the name of the secret holding its password.""" + + user: str + secret: str + + +def connect_admin(settings: ProjectSettings) -> Any: + """Log in as config.yaml's `admin_user`. No other secret is read.""" + return connect(settings, Login(settings.admin_user, "admin_password")) + + +def connect_migration(settings: ProjectSettings) -> Any: + """Log in as the migration user, as `access check` does. No other secret is read.""" + return connect(settings, Login(settings.migration_user, "migration_password")) + + +def connect(settings: ProjectSettings, login: Login) -> Any: + """A client for `login` on the environment's server, once the server is new enough.""" + client = open_client(settings, login) + require_supported_version(str(client.server_version)) + return client + + +def open_client(settings: ProjectSettings, login: Login) -> Any: + """A client for `login`, whatever the server's version. + + `bootstrap` checks the version itself. Every other caller goes through `connect`. + """ + import clickhouse_connect + + server = settings.server + if not server.host: + raise AccessError( + f"host is required in config.yaml for environment '{settings.environment}'" + ) + password = read_secret(settings, login.secret) + with server_errors(), redirect_stderr(io.StringIO()): + # clickhouse-connect prints connection failures straight to stderr. + return clickhouse_connect.get_client( + host=server.host, + port=_port(server), + username=login.user, + password=password, + secure=server.secure, + interface="https" if server.secure else "http", + connect_timeout=10, + send_receive_timeout=60, + # Bound parameters, such as a password `apply` sets, go in the request body. In the + # URL, a proxy's log or a connection error could show them. + form_encode_query_params=True, + ) + + +def address(settings: ProjectSettings) -> str: + """`host:port`, as `open_client` connects to them.""" + server = settings.server + return f"{server.host}:{_port(server)}" + + +def require_supported_version(version: str) -> None: + """Refuse a server older than 25.8, naming its version.""" + parsed = _version(version) + if parsed is None: + raise AccessError(f"Can't read the server's version from {version!r}.") + if parsed < MINIMUM_VERSION: + needed = ".".join(str(part) for part in MINIMUM_VERSION) + raise AccessError( + f"The server runs ClickHouse {version}. " + f"`bootstrap` and the `access` commands that connect need {needed} or later." + ) + + +@contextmanager +def server_errors() -> Iterator[None]: + """Turn the driver's errors into `AccessError`, keeping the server's first line.""" + from clickhouse_connect.driver.exceptions import ClickHouseError + + try: + yield + except ClickHouseError as error: + lines = str(error).strip().splitlines() + reason = clean_database_error(lines[0]) if lines else type(error).__name__ + raise AccessError(reason) from error + + +def server_message(error: Exception) -> str: + """The first line of the server's message, with its error name, from a driver error. + + The driver's wrapping, the URL it adds, which names the host, and the server's version + are left out. Where the message runs on past its first line, as a failed connection's + log does, the error name from its end is kept. + """ + whole = str(error).strip() + lines = whole.splitlines() + text = lines[0] if lines else type(error).__name__ + text = clean_database_error(_FOR_URL.sub("", _DRIVER_PREFIX.sub("", text, count=1))) + names = _ERROR_NAME.findall(whole) + if names and f"({names[-1]})" not in text: + text = f"{text.removesuffix(' Log:')} ({names[-1]})" + return text + + +def read_secret(settings: ProjectSettings, name: str) -> str: + """One secret: the SSM path at `environments..ssm.`, else `CH__`.""" + value = _lookup(settings, name, required=True) + assert value is not None # get_secret raises when a required secret is missing + return value + + +def secret_is_set(settings: ProjectSettings, name: str) -> bool: + """Whether a secret has an SSM path or a `CH__` value, without reading SSM.""" + variable = f"CH_{settings.environment.upper()}_{name.upper()}" + return bool(settings.ssm.get(name)) or bool(os.environ.get(variable)) + + +def optional_secret(settings: ProjectSettings, name: str) -> str | None: + """`read_secret`, or None when neither an SSM path nor `CH__` is set. + + An SSM path that can't be read is still an `AccessError`. + """ + return _lookup(settings, name, required=False) + + +def _port(server: ServerSettings) -> int: + """config.yaml's port, or HTTP's default: 8443 with TLS, else 8123.""" + return server.port or (8443 if server.secure else 8123) + + +def _version(version: str) -> tuple[int, int] | None: + """The major and minor version, or None when the text doesn't start with them.""" + match = _VERSION.match(version) + return None if match is None else (int(match[1]), int(match[2])) + + +def _lookup(settings: ProjectSettings, name: str, required: bool) -> str | None: + try: + value = get_secret( + settings.environment, + name, + ssm_path=settings.ssm.get(name), + aws_region=settings.server.aws_region, + required=required, + ) + except (ValueError, ImportError, SSMSecretNotFoundError, SSMJsonKeyError) as error: + raise AccessError(str(error)) from error + if value is None: + return None + return str(value) diff --git a/ch_migrate/access/settings.py b/ch_migrate/access/settings.py new file mode 100644 index 0000000..f846406 --- /dev/null +++ b/ch_migrate/access/settings.py @@ -0,0 +1,187 @@ +"""What `config.yaml` says about one environment, without resolving any secret. + +`ch_migrate.config.get_env_config` reads every password as it loads, from SSM or the +environment. `access validate` must run with neither, so this loader reads the same keys, +merged the same way, and keeps SSM paths as paths. `get_env_config` keeps its shape, +because client code imports it. + +The live commands, `access show` and `access plan`, read the server's address from here too, +and then resolve only the admin's secret (`server.py`). +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import yaml + +from ch_migrate.access.reading import yaml_problem +from ch_migrate.bootstrap import validate_identifier +from ch_migrate.config import load_config + +# How long a live read waits for a replica that is behind before a row counts as absent (2.5). +READ_TIMEOUT = 30.0 + + +class SettingsError(ValueError): + """config.yaml is missing, or doesn't describe the environment well enough.""" + + +@dataclass(frozen=True) +class ServerSettings: + """Where the environment's server is; the live `access` commands connect to it.""" + + host: str | None = None + port: int | None = None + secure: bool = True + cluster: str | None = None + aws_region: str | None = None + # `access_read_timeout`: seconds to keep re-reading before a missing row counts as absent. + read_timeout: float = READ_TIMEOUT + + +@dataclass(frozen=True) +class ProjectSettings: + """One environment's names from config.yaml. Secrets stay where they are.""" + + environment: str + database: str + project: str + migration_user: str + admin_user: str = "default" + mcp_user_name: str | None = None + dict_reader_name: str | None = None + # SSM paths by secret name, as written; nothing here has been read. + ssm: dict[str, Any] = field(default_factory=dict) + environments: tuple[str, ...] = () + server: ServerSettings = ServerSettings() + # config.yaml's `migration_role`: a role another project directory shares (2.8). + shared_role: str | None = None + + def placeholders(self) -> dict[str, str]: + """Values for `{db}`, `{project}`, `{env}` and `{migration_role}` (2.3).""" + return { + "db": self.database, + "project": self.project, + "env": self.environment, + "migration_role": self.migration_role, + } + + @property + def migration_role(self) -> str: + """config.yaml's `migration_role`, else the role 0.8's `bootstrap` names after the + project.""" + return self.shared_role or f"{self.project}_migration_role" + + +def load_settings(environment: str, config_path: Path) -> ProjectSettings: + """Read one environment from config.yaml, as `get_env_config` would, minus the secrets.""" + config = _read_config(config_path) + environments = _mapping(config, "environments", "environments") + if environment not in environments: + available = ", ".join(environments) or "(none)" + raise SettingsError(f"Unknown environment: {environment}. Available: {available}") + own = _mapping(environments, environment, f"environments.{environment}") + merged = {**_mapping(config, "defaults", "defaults"), **own} + database = _required(merged, ("database",), environment) + settings = ProjectSettings( + environment=environment, + database=database, + project=_project_name(config, merged, database), + migration_user=_required(merged, ("migration_user", "user"), environment), + admin_user=merged.get("admin_user") or "default", + mcp_user_name=merged.get("mcp_user_name"), + dict_reader_name=merged.get("dict_reader_name"), + ssm=_mapping(own, "ssm", f"environments.{environment}.ssm"), + environments=tuple(environments), + server=_server(merged), + shared_role=str(merged["migration_role"]) if merged.get("migration_role") else None, + ) + _check_names(settings) + return settings + + +def _read_config(path: Path) -> dict[str, Any]: + try: + config = load_config(path) + except FileNotFoundError as error: + raise SettingsError(str(error)) from None + except yaml.YAMLError as error: + raise SettingsError(": ".join(part for part in (path.name, *yaml_problem(error)) if part)) + if not isinstance(config, dict): + raise SettingsError(f"{path.name} must be a mapping") + return config + + +def _mapping(parent: dict[str, Any], key: str, label: str) -> dict[str, Any]: + """`parent[key]` as a mapping; unset reads as empty.""" + value = parent.get(key) or {} + if not isinstance(value, dict): + raise SettingsError(f"{label} in config.yaml must be a mapping") + return dict(value) + + +def _required(merged: dict[str, Any], keys: tuple[str, ...], environment: str) -> str: + """The first of `keys` that is set; `migration_user` falls back to 0.8's `user`.""" + value = next((merged[key] for key in keys if merged.get(key)), None) + if not value: + raise SettingsError(f"{keys[0]} is required in config.yaml for environment '{environment}'") + return str(value) + + +def _project_name(config: dict[str, Any], merged: dict[str, Any], database: str) -> str: + """`project.name`, else a `project` key in the environment, else the database name up + to its first underscore: the order 0.8's `bootstrap` uses.""" + project = config.get("project") + if isinstance(project, dict) and project.get("name"): + return str(project["name"]) + return str(merged.get("project") or database.split("_")[0]) + + +def _server(merged: dict[str, Any]) -> ServerSettings: + """The connection keys, read as `get_env_config` and `connection.get_client` read them.""" + return ServerSettings( + host=merged.get("host"), + port=merged.get("port"), + secure=bool(merged.get("secure", True)), + cluster=_cluster(merged.get("cluster")), + aws_region=merged.get("aws_region"), + read_timeout=_read_timeout(merged.get("access_read_timeout", READ_TIMEOUT)), + ) + + +def _cluster(value: Any) -> str | None: + """The cluster's name, when set. Its characters aren't checked: the SQL quotes it.""" + if value is not None and not isinstance(value, str): + raise SettingsError("cluster in config.yaml must be a string") + return value + + +def _read_timeout(value: Any) -> float: + # The bound refuses .inf and .nan, and an integer too large to be seconds as a float. + number = isinstance(value, (int, float)) and not isinstance(value, bool) + if not number or not 0 <= value <= sys.float_info.max: + raise SettingsError( + "access_read_timeout in config.yaml must be a number of seconds, 0 or more" + ) + return float(value) + + +def _check_names(settings: ProjectSettings) -> None: + labels = { + "database name": settings.database, + "project name": settings.project, + "migration user": settings.migration_user, + "migration role": settings.shared_role, + "MCP user": settings.mcp_user_name, + "dict reader user": settings.dict_reader_name, + } + for label, name in labels.items(): + if name is not None: + try: + validate_identifier(name, label) + except ValueError as error: + raise SettingsError(str(error)) from None diff --git a/ch_migrate/access/show.py b/ch_migrate/access/show.py new file mode 100644 index 0000000..b49aee1 --- /dev/null +++ b/ch_migrate/access/show.py @@ -0,0 +1,218 @@ +"""`access show`: what the server holds for some users and roles, in access.yaml's form. + +The output is YAML that `access validate` accepts. Copied into access.yaml, it declares what +the server already holds, which is the starting point for adopting existing users and roles: + +- a user or role prints under `users:` or `roles:`, with its grants, the roles it holds and, + for a user, its default roles when they aren't all of them; +- the migration role prints under `migration_role:`, with its profile and what it holds + beyond it; +- the project's own database is written `{db}`, so the file suits every environment; +- no password is ever read or shown. + +What access.yaml can't declare is left out with a warning: a column grant, a partial +revoke, a role held with admin option, and a grant on something other than a database, a +table or a data source, such as `TABLE ENGINE ON MergeTree`. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +from typing import Any, Iterable + +import yaml + +from ch_migrate.access.grants import SOURCE_PRIVILEGES +from ch_migrate.access.live import LiveEntity, LiveState, Wanted +from ch_migrate.access.model import AccessSpec, Grant, Target +from ch_migrate.access.planner import Entity, surplus_grant +from ch_migrate.access.rights import Scope, StoredRow, rights_of +from ch_migrate.access.server import AccessError +from ch_migrate.access.settings import ProjectSettings + +_HEADER = ( + "# What the server holds for {env}, in access.yaml's form (`ch-migrate access show`).\n" + "# Passwords are never shown. For ch-migrate to create a user, add its\n" + "# `password: {{secret: NAME}}`.\n" +) + + +@dataclass(frozen=True) +class Showing: + """What `access show` was asked for: names given, or else everything declared.""" + + settings: ProjectSettings + spec: AccessSpec + given: tuple[str, ...] = () + + def check(self) -> None: + """Refuse a name that access.yaml can't declare, before anything is read.""" + reasons = { + self.settings.admin_user: "config.yaml's admin_user, which ch-migrate never changes", + self.spec.migration.user: "the migration user, which `bootstrap` manages", + } + for name in self.given: + if name in reasons: + raise AccessError(f"{name} is {reasons[name]}, so access.yaml can't declare it.") + + @property + def wanted(self) -> Wanted: + return Wanted(self.names) + + def unsettled(self, live: LiveState) -> bool: + """Whether a name isn't on the server, which a replica that is behind would also show.""" + return any(self._absent(live, name) for name in self.expected) + + @property + def expected(self) -> tuple[str, ...]: + """The names that should be on the server: all but those declared `absent: true`.""" + absent = {role.name for role in self.spec.roles if role.absent} + absent |= {user.name for user in self.spec.users if user.absent} + return tuple(name for name in self.names if name in self.given or name not in absent) + + @property + def names(self) -> tuple[str, ...]: + if self.given: + return tuple(dict.fromkeys(self.given)) + declared = [role.name for role in self.spec.roles] + [user.name for user in self.spec.users] + return tuple(dict.fromkeys(declared)) + + def _absent(self, live: LiveState, name: str) -> bool: + return live.find("role", name) is None and live.find("user", name) is None + + +@dataclass(frozen=True) +class Shown: + """The YAML text, and a warning for each thing access.yaml can't declare.""" + + text: str + warnings: tuple[str, ...] = () + + +def show_access(showing: Showing, live: LiveState) -> Shown: + """What `live` holds for the names asked for, as access.yaml text.""" + page = _Page(showing, live) + for name in showing.names: + page.add(name) + header = _HEADER.format(env=showing.spec.environment) + return Shown(header + page.text(), tuple(page.warnings)) + + +@dataclass +class _Page: + """The document while it is being filled in.""" + + showing: Showing + live: LiveState + migration: dict[str, Any] | None = None + roles: dict[str, Any] = field(default_factory=dict) + users: dict[str, Any] = field(default_factory=dict) + warnings: list[str] = field(default_factory=list) + + def add(self, name: str) -> None: + role, user = self.live.find("role", name), self.live.find("user", name) + if role is None and user is None: + self._not_found(name) + if role is not None and name == self.showing.spec.migration.role: + self.migration = self._migration_block(Entity("role", name), role) + elif role is not None: + self.roles[name] = self._block(Entity("role", name), role) + if user is not None: + self.users[name] = self._block(Entity("user", name), user) + + def text(self) -> str: + sections = {"migration_role": self.migration, "roles": self.roles, "users": self.users} + document = {key: value for key, value in sections.items() if value} + return yaml.dump( + document, + Dumper=_Dumper, + sort_keys=False, + default_flow_style=False, + allow_unicode=True, + width=10_000, + ) + + def _not_found(self, name: str) -> None: + if name in self.showing.given: + raise AccessError(f"The server has no user or role named {name}.") + if name in self.showing.expected: + self.warnings.append(f"{name} is declared but isn't on the server, so it isn't shown.") + + def _migration_block(self, entity: Entity, held: LiveEntity) -> dict[str, Any]: + """The profile, and the grants the role holds beyond it.""" + migration, tree = self.showing.spec.migration, self.live.tree + profile = frozenset( + right for grant in migration.profile.grants for right in rights_of(tree, grant) + ) + beyond = [item.row for item in held.holdings.surplus(profile)] + for membership in held.memberships: + self.warnings.append( + f"{entity} holds role {membership.role}, which migration_role can't declare." + ) + grants = self._grants(entity, beyond) + return {"profile": migration.profile.name, **({"grants": grants} if grants else {})} + + def _block(self, entity: Entity, held: LiveEntity) -> dict[str, Any]: + """A role's `grants` then `roles`; a user's `roles`, `default_roles`, then `grants`.""" + roles = [membership.role for membership in held.memberships] + defaults = [membership.role for membership in held.memberships if membership.default] + for membership in held.memberships: + if membership.admin_option: + self.warnings.append( + f"{entity} holds role {membership.role} with admin option, " + "which access.yaml can't declare." + ) + grants = self._grants(entity, held.holdings.rows) + block: dict[str, Any] = {"grants": grants} if grants and entity.kind == "role" else {} + if roles: + block["roles"] = roles + if entity.kind == "user" and defaults != roles: + block["default_roles"] = defaults + if grants and entity.kind == "user": + block["grants"] = grants + return block + + def _grants(self, entity: Entity, rows: Iterable[StoredRow]) -> list[str]: + """Grant entries for the rows access.yaml can declare; a warning for the others.""" + groups: dict[tuple[Scope, bool, bool], list[str]] = {} + for row in rows: + groups.setdefault((row.scope, row.grant_option, row.revoke), []).append(row.flag) + entries = [] + for (scope, option, revoke), flags in groups.items(): + grant = replace(surplus_grant(self.live.tree, scope, flags), grant_option=option) + if revoke or scope.column is not None or _other_object(scope, flags): + self.warnings.append(_undeclarable(entity, grant, revoke)) + else: + entries.append(str(replace(grant, target=self._placeholder(grant.target)))) + return sorted(entries) + + def _placeholder(self, target: Target) -> Target: + """The project's own database as `{db}`, as access.yaml writes it.""" + if target.database != self.showing.settings.database: + return target + return replace(target, database="{db}") + + +class _Dumper(yaml.SafeDumper): + """Block style with list items indented under their key, as access.yaml is written.""" + + def increase_indent(self, flow: bool = False, indentless: bool = False) -> Any: + return super().increase_indent(flow, False) + + +def _other_object(scope: Scope, flags: Iterable[str]) -> bool: + """A grant on a name that isn't a data source: only READ and WRITE take one of those.""" + return scope.source is not None and not SOURCE_PRIVILEGES.issuperset(flags) + + +def _undeclarable(entity: Entity, grant: Grant, revoke: bool) -> str: + if revoke: + what = "the grant option for " if grant.grant_option else "" + plain = replace(grant, grant_option=False) + return ( + f"{entity} has a partial revoke of {what}{plain}, which access.yaml can't declare. " + "`access plan` shows the grant that clears it." + ) + if grant.target.source is not None: + return f"{entity} holds {grant}, which access.yaml can't declare, so it is left out." + return f"{entity} holds {grant}: column grants aren't in v1, so it is left out." diff --git a/ch_migrate/access/sql/apply.sql b/ch_migrate/access/sql/apply.sql new file mode 100644 index 0000000..74bbd31 --- /dev/null +++ b/ch_migrate/access/sql/apply.sql @@ -0,0 +1,70 @@ +-- What `ch_migrate/access/applier.py` sends, for `access apply` and `bootstrap`, named by +-- the comment above each statement. +-- `writes.py` fills in names already quoted and privileges the server's own list knows. +-- {cluster} is empty, or ON CLUSTER and the cluster's quoted name where users and roles +-- live on each node's disk. Quoted, a name such as `c-1` parses. +-- A password is never part of the text: the server binds {password:String}. + +-- The login `apply` is connected as, which access.yaml can't declare. +-- current_user +SELECT currentUser() AS name; + +-- The roles the login holds, through other roles too: `apply` won't change them. +-- current_roles +SELECT arrayJoin(enabledRoles()) AS name; + +-- Only `bootstrap` sends this, before anything else (design note, 2.5). +-- create_database +CREATE DATABASE IF NOT EXISTS {name}{cluster}; + +-- create_role +CREATE ROLE IF NOT EXISTS {name}{cluster}; + +-- create_user +CREATE USER IF NOT EXISTS {name}{cluster} IDENTIFIED BY {password:String}; + +-- reset_password +ALTER USER {name}{cluster} IDENTIFIED BY {password:String}; + +-- grant_role +GRANT{cluster} {role} TO {grantee}; + +-- grant +GRANT{cluster} {grants} TO {grantee}; + +-- grant_with_grant_option +GRANT{cluster} {grants} TO {grantee} WITH GRANT OPTION; + +-- Narrowing a scope: the whole declared set in one statement, which takes away the rest. +-- replace +GRANT{cluster} {grants} TO {grantee} WITH REPLACE OPTION; + +-- A best-effort grant lands what the admin holds of it and raises no error for the rest. +-- ClickHouse refuses it ON CLUSTER, so there each privilege is a plain `grant` instead. +-- best_effort +GRANT CURRENT GRANTS({grants}) TO {grantee}; + +-- best_effort_with_grant_option +GRANT CURRENT GRANTS({grants}) TO {grantee} WITH GRANT OPTION; + +-- SET DEFAULT ROLE takes no ON CLUSTER; ALTER USER does. {roles} is ALL, NONE or a list. +-- set_default_roles +ALTER USER {name}{cluster} DEFAULT ROLE {roles}; + +-- revoke +REVOKE{cluster} {grants} FROM {grantee}; + +-- revoke_grant_option +REVOKE{cluster} GRANT OPTION FOR {grants} FROM {grantee}; + +-- revoke_role +REVOKE{cluster} {role} FROM {grantee}; + +-- revoke_admin_option +REVOKE{cluster} ADMIN OPTION FOR {role} FROM {grantee}; + +-- drop_user +DROP USER IF EXISTS {name}{cluster}; + +-- drop_role +DROP ROLE IF EXISTS {name}{cluster}; diff --git a/ch_migrate/access/sql/bundle.sql b/ch_migrate/access/sql/bundle.sql new file mode 100644 index 0000000..331ba4b --- /dev/null +++ b/ch_migrate/access/sql/bundle.sql @@ -0,0 +1,24 @@ +-- What `ch_migrate/access/bundle.py` runs to record the bundled privilege list. +-- Only the scratch role it is given is ever written to. + +-- privileges +SELECT privilege, aliases, level, parent_group +FROM system.privileges +ORDER BY privilege; + +-- create_scratch_role +CREATE ROLE IF NOT EXISTS {role}; + +-- clear_scratch_role +REVOKE ALL ON *.* FROM {role}; + +-- grant_on_everything +GRANT {privilege} ON *.* TO {role}; + +-- scratch_grants +SELECT access_type, access_object +FROM system.grants +WHERE role_name = {role:String}; + +-- drop_scratch_role +DROP ROLE IF EXISTS {role}; diff --git a/ch_migrate/access/sql/check.sql b/ch_migrate/access/sql/check.sql new file mode 100644 index 0000000..2af03f9 --- /dev/null +++ b/ch_migrate/access/sql/check.sql @@ -0,0 +1,7 @@ +-- What `ch_migrate/access/check.py` sends, as the migration user. It only reads. +-- `check.py` fills in privilege names from the server's own list, and quoted names. + +-- 1 when the current user holds every privilege named on the target, else 0. It takes no +-- WITH GRANT OPTION. +-- check_grant +CHECK GRANT {grants}; diff --git a/ch_migrate/access/sql/live.sql b/ch_migrate/access/sql/live.sql new file mode 100644 index 0000000..89b5571 --- /dev/null +++ b/ch_migrate/access/sql/live.sql @@ -0,0 +1,105 @@ +-- What `ch_migrate/access/live.py` reads from the server. Every statement only reads. +-- {names:Array(String)} and {sources:Array(String)} are bound by the server. + +-- The privilege tree of this server: names, aliases, levels and groups (design note, 2.7). +-- privileges +SELECT privilege, aliases, level, parent_group +FROM system.privileges; + +-- Where a CREATE USER or CREATE ROLE is stored: the first storage, by precedence, that a +-- create can go to. `local_directory` is each node's disk, `replicated` is Keeper, and +-- `memory` is each node's memory. users.xml, LDAP and ClickHouse Cloud's `jwt` only read. +-- storage +SELECT type +FROM system.user_directories +WHERE type IN ('local_directory', 'replicated', 'memory') +ORDER BY precedence +LIMIT 1; + +-- 1 when this login holds CLUSTER on *.*, which also holds where the server grants it to +-- every login (`on_cluster_queries_require_cluster_grant` off, as on ClickHouse Cloud). +-- cluster_check +CHECK GRANT CLUSTER ON *.*; + +-- This login's own grants, and those of the roles it has enabled, nested ones included. +-- own_grants +SELECT access_type, access_object, database, table, column, is_partial_revoke, grant_option +FROM system.grants +WHERE user_name = currentUser() OR role_name IN enabledRoles(); + +-- The clusters that hold this node, each with its hosts as `host:port`. Of those that list +-- another host too, one, or several that list the same hosts, is where every replica is read. +-- clusters +SELECT cluster, arraySort(groupUniqArray(concat(host_name, ':', toString(port)))) AS hosts +FROM system.clusters +GROUP BY cluster +HAVING max(is_local) = 1 +ORDER BY cluster; + +-- The node this login reads, named where users and roles are on each node's own disk +-- (Decision 14). +-- node +SELECT hostName() AS name; + +-- roles +SELECT name +FROM system.roles +WHERE name IN {names:Array(String)}; + +-- With default_roles_all = 1, a role granted later becomes a default role at once, unless +-- default_roles_except names it. +-- users +SELECT name, default_roles_all, default_roles_except +FROM system.users +WHERE name IN {names:Array(String)}; + +-- A row with is_partial_revoke = 1 takes a right away inside a broader grant; with +-- grant_option = 1 it takes away only the grant option. +-- grants +SELECT user_name, role_name, access_type, access_object, database, table, column, + is_partial_revoke, grant_option +FROM system.grants +WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}; + +-- The roles each user or role holds. +-- role_grants +SELECT user_name, role_name, granted_role_name, granted_role_is_default, with_admin_option +FROM system.role_grants +WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}; + +-- The data sources this server's parser takes as a grant target, such as REMOTE. +-- system.privileges doesn't list them all, and the statement is parsed, never run. +-- accepted_sources +SELECT source +FROM (SELECT arrayJoin({sources:Array(String)}) AS source) +WHERE formatQueryOrNull(concat('GRANT READ ON ', source, ' TO probe')) IS NOT NULL; + +-- Every replica of {cluster:String}, by the name it gives itself. Each read of every replica +-- runs with skip_unavailable_shards = 0, so a replica that can't be reached is an error and +-- never reads as one that holds nothing. Every server lists users.xml here. +-- replicas +SELECT DISTINCT materialize(hostName()) AS replica +FROM clusterAllReplicas({cluster:String}, system.user_directories); + +-- The reads above, of every replica at once, each row tagged with the replica it came from. +-- replica_roles +SELECT materialize(hostName()) AS replica, name +FROM clusterAllReplicas({cluster:String}, system.roles) +WHERE name IN {names:Array(String)}; + +-- replica_users +SELECT materialize(hostName()) AS replica, name, default_roles_all, default_roles_except +FROM clusterAllReplicas({cluster:String}, system.users) +WHERE name IN {names:Array(String)}; + +-- replica_grants +SELECT materialize(hostName()) AS replica, user_name, role_name, access_type, access_object, + database, table, column, is_partial_revoke, grant_option +FROM clusterAllReplicas({cluster:String}, system.grants) +WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}; + +-- replica_role_grants +SELECT materialize(hostName()) AS replica, user_name, role_name, granted_role_name, + granted_role_is_default, with_admin_option +FROM clusterAllReplicas({cluster:String}, system.role_grants) +WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}; diff --git a/ch_migrate/access/sql/render.sql b/ch_migrate/access/sql/render.sql new file mode 100644 index 0000000..b5686ca --- /dev/null +++ b/ch_migrate/access/sql/render.sql @@ -0,0 +1,43 @@ +-- The statements `access validate --sql` and `bootstrap --dry-run` print, named by the +-- comment above each. +-- `render.py` fills in names that already passed `validate_identifier`. + +-- Only `bootstrap --dry-run` prints this, before anything else. +-- create_database +CREATE DATABASE IF NOT EXISTS {name}; + +-- create_role +CREATE ROLE IF NOT EXISTS {name}; + +-- {password} is an unquoted placeholder, so the statement fails to parse until a DBA +-- replaces it with the quoted secret. There is no CREATE USER without IDENTIFIED: on 26.3 +-- that is a no_password login anyone can use. +-- create_user +CREATE USER IF NOT EXISTS {name} IDENTIFIED BY {password}; + +-- grant_roles +GRANT {roles} TO {grantee}; + +-- grant +GRANT {privileges} ON {target} TO {grantee}; + +-- grant_with_grant_option +GRANT {privileges} ON {target} TO {grantee} WITH GRANT OPTION; + +-- grant_best_effort +GRANT CURRENT GRANTS({privileges} ON {target}) TO {grantee}; + +-- grant_best_effort_with_grant_option +GRANT CURRENT GRANTS({privileges} ON {target}) TO {grantee} WITH GRANT OPTION; + +-- set_default_roles +SET DEFAULT ROLE {roles} TO {user}; + +-- set_no_default_roles +SET DEFAULT ROLE NONE TO {user}; + +-- drop_user +DROP USER IF EXISTS {name}; + +-- drop_role +DROP ROLE IF EXISTS {name}; diff --git a/ch_migrate/access/templates.py b/ch_migrate/access/templates.py new file mode 100644 index 0000000..44dcae0 --- /dev/null +++ b/ch_migrate/access/templates.py @@ -0,0 +1,27 @@ +"""Named SQL statements from the package's `sql/` files. + +Each statement in a file is named by the comment line directly above it. `{name}` +placeholders are filled in by `ch_migrate.sql.render_placeholders`; ClickHouse's own +`{name:Type}` query parameters are left for the server to bind. +""" + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import Mapping + +from ch_migrate.sql import render_placeholders, split_statements + +SQL_DIR = Path(__file__).with_name("sql") + + +def statement(file: str, name: str, values: Mapping[str, str] | None = None) -> str: + """The statement `name` from `sql/.sql`, with its placeholders filled in.""" + return render_placeholders(_statements(file)[name], dict(values or {})) + + +@lru_cache(maxsize=None) +def _statements(file: str) -> dict[str, str]: + text = (SQL_DIR / f"{file}.sql").read_text() + return {sql.comments[-1]: sql.sql for sql in split_statements(text) if sql.comments} diff --git a/ch_migrate/access/writes.py b/ch_migrate/access/writes.py new file mode 100644 index 0000000..8dfee9c --- /dev/null +++ b/ch_migrate/access/writes.py @@ -0,0 +1,260 @@ +"""Render access changes using sql/apply.sql; quote names and bind passwords. + +Local-storage cluster writes use ON CLUSTER with wait_end_of_query. Best-effort grants +use CURRENT GRANTS elsewhere, or one plain grant per privilege ON CLUSTER. +Scope narrowing replaces the whole declared set, then restores grant options in a second +statement when needed. Keep held best-effort access; Unkept refuses a replace that cannot +preserve a partial revoke exactly. The migration identity is never replaced (design 2.5). +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass, field, replace +from typing import Any, Mapping + +from ch_migrate.access.live import LiveEntity, LiveState +from ch_migrate.access.model import AccessSpec, Grant, Role, Target, User +from ch_migrate.access.planner import Change, Entity, declared_entities, surplus_grant +from ch_migrate.access.rights import Right, Scope, rights_of +from ch_migrate.access.templates import statement + +# Sent with every ON CLUSTER statement. ClickHouse stops waiting for a host before the +# client's 60-second read timeout (`server.connect`), so a slow host is an error with a code. +ON_CLUSTER_SETTINGS = { + "wait_end_of_query": 1, + "distributed_ddl_output_mode": "throw", + "distributed_ddl_task_timeout": 45, +} +# The changes that set a password, bound as {password:String}. +_PASSWORD_ACTIONS = frozenset({"create_user", "reset_password"}) +# A data source, or another object the server names, that is one word is written bare, as +# in `READ ON REMOTE`. +_WORD = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") +# A column grant, as the planner writes one: `SELECT(column)`. +_COLUMN = re.compile(r"^(?P[^(]+)\((?P.+)\)$") + + +@dataclass(frozen=True) +class Write: + """One statement, the parameters the server binds, and the settings it is sent with.""" + + sql: str + parameters: Mapping[str, str] = field(default_factory=dict, repr=False) + settings: Mapping[str, Any] = field(default_factory=dict) + gives: Grant | None = None # a best-effort statement's grant, which a refusal names + + +@dataclass(frozen=True) +class Writing: + """What the statements are written from: the declaration, one read, and passwords.""" + + spec: AccessSpec + live: LiveState + cluster: str | None = None # ON CLUSTER this: users and roles are on each node's disk + passwords: Mapping[str, str] = field(default_factory=dict, repr=False) # by user name + + def declared(self, entity: Entity) -> Role | User: + """The declared user or role a change is for.""" + kind = User if entity.kind == "user" else Role + return next( + declared + for declared in declared_entities(self.spec) + if isinstance(declared, kind) and declared.name == entity.name + ) + + +class Unkept(Exception): + """A replace isn't sent: it can't keep exactly what is held of a best-effort grant (2.5). + + The message says why, worded to follow "because". + """ + + +def writes_for(change: Change, writing: Writing) -> tuple[Write, ...]: + """The statements that make one change; none for a line that only notes something.""" + if change.action == "replace": + return _replace(change, writing) + if change.action == "best_effort" and change.grant is not None: + return best_effort_writes(change.entity.name, change.grant, writing.cluster) + if change.marker not in "+-": + return () + write = _write(writing.cluster, _template(change.action, change.grant), _values(change)) + if change.action in _PASSWORD_ACTIONS: + write = replace(write, parameters={"password": writing.passwords[change.entity.name]}) + return (write,) + + +def best_effort_writes(grantee: str, grant: Grant, cluster: str | None) -> tuple[Write, ...]: + """How a best-effort grant is sent; each statement may be refused, as only a warning. + + With no cluster: one `GRANT CURRENT GRANTS(...)`. ON CLUSTER: one plain GRANT for each + privilege, since ClickHouse refuses CURRENT GRANTS there (Decision 12). Each statement + `gives` the part of the grant it is for. + """ + if cluster is None: + forms = [("best_effort", grant)] + else: + forms = [("grant", replace(grant, privileges=(name,))) for name in grant.privileges] + return tuple( + replace( + _write(cluster, _template(action, part), _granting(grantee, part)), + gives=part, + ) + for action, part in forms + ) + + +def grant_clause(grant: Grant) -> str: + """` ON `, written as every statement here writes it.""" + return _clauses([grant]) + + +def quote(name: str) -> str: + """A name as a quoted identifier.""" + return "`" + name.replace("\\", "\\\\").replace("`", "\\`") + "`" + + +def _replace(change: Change, writing: Writing) -> tuple[Write, ...]: + """The whole declared set in one statement, then the grant options it carries.""" + entity = change.entity + if entity.kind == "role" and entity.name == writing.spec.migration.role: + raise ValueError(f"{entity} is only ever added to, never replaced (design note, 2.2)") + plain, optioned = _replacement(writing, entity) + if not plain: + # Nothing declared is held now or required, so there is no gap to avoid. + return tuple(write for inner in change.covers for write in writes_for(inner, writing)) + grantee = quote(entity.name) + writes = [_write(writing.cluster, "replace", {"grants": _clauses(plain), "grantee": grantee})] + if optioned: + values = {"grants": _clauses(optioned), "grantee": grantee} + writes.append(_write(writing.cluster, "grant_with_grant_option", values)) + return tuple(writes) + + +def _replacement(writing: Writing, entity: Entity) -> tuple[list[Grant], list[Grant]]: + """The declared grants a replace gives, without grant option, and those that carry it.""" + held = writing.live.find(entity.kind, entity.name) or LiveEntity() + plain, optioned = [], [] + for grant in writing.declared(entity).grants: + parts = _held_parts(writing.live, held, grant) if grant.best_effort else [grant] + for part in parts: + plain.append(replace(part, grant_option=False)) + if part.grant_option: + optioned.append(part) + return plain, optioned + + +def _held_parts(live: LiveState, held: LiveEntity, grant: Grant) -> list[Grant]: + """What a user or role holds of a best-effort grant now: none, some or all of it. + + That is each flag it holds on the grant's whole scope, and each held row inside the + scope for another of its flags, such as `system.tables` of `SELECT ON system.*`. A part + keeps its grant option only where every flag held there has one. Raises `Unkept` when a + revoke inside the scope means no set of grants keeps what is held. + """ + _refuse_revokes_inside(live, held, grant) + holdings, scope = held.holdings, Scope.of(grant.target) + flags = {right.flag for right in rights_of(live.tree, grant)} + parts = {scope: {flag for flag in flags if holdings.holds(Right(flag, scope))}} + for row in holdings.rows: + inside = row.scope != scope and scope.contains(row.scope) and not row.revoke + if inside and row.flag in flags - parts[scope]: + parts.setdefault(row.scope, set()).add(row.flag) + return [ + replace( + surplus_grant(live.tree, where, kept), + grant_option=grant.grant_option + and all(holdings.holds(Right(flag, where, grant_option=True)) for flag in kept), + best_effort=True, + ) + for where, kept in parts.items() + if kept + ] + + +def _refuse_revokes_inside(live: LiveState, held: LiveEntity, grant: Grant) -> None: + """Raise `Unkept` if, for one of the grant's flags, a revoke sits inside its scope. + + The grant above that revoke, at the scope or above it, is held but for the revoke. A + replace can't write "all but", so it would drop the rest, such as `system.tables` of + `SELECT ON system.*` held less `system.users`. A revoke of only the grant option counts + where the grant carries one. + """ + scope = Scope.of(grant.target) + flags = {right.flag for right in rights_of(live.tree, grant)} + revoked = sorted( + ("the grant option for " if row.grant_option else "") + + str(surplus_grant(live.tree, row.scope, [row.flag])) + for row in held.holdings.rows + if row.revoke + and row.flag in flags + and row.scope != scope + and scope.contains(row.scope) + and row.decides(grant.grant_option) + ) + if revoked: + raise Unkept( + f"what it holds of the best-effort grant {grant} has {', '.join(revoked)} revoked " + "inside it, which a replace can't keep, so it keeps the access it has" + ) + + +def _template(action: str, grant: Grant | None) -> str: + """The statement's name in `sql/apply.sql`: a grant with grant option has its own.""" + if action in ("grant", "best_effort") and grant is not None and grant.grant_option: + return action + "_with_grant_option" + return action + + +def _values(change: Change) -> dict[str, str]: + name = quote(change.entity.name) + values = {"name": name, "grantee": name} + if change.grant is not None: + values["grants"] = _clauses([change.grant]) + if change.action == "set_default_roles": + values["roles"] = _default_roles(change.roles) + elif change.roles: + values["role"] = quote(change.roles[0]) + return values + + +def _granting(grantee: str, grant: Grant) -> dict[str, str]: + return {"grantee": quote(grantee), "grants": _clauses([grant])} + + +def _write(cluster: str | None, template: str, values: Mapping[str, str]) -> Write: + """A statement from `sql/apply.sql`, ON CLUSTER and sent with its settings where needed.""" + on_cluster = f" ON CLUSTER {quote(cluster)}" if cluster else "" + sql = statement("apply", template, {**values, "cluster": on_cluster}) + return Write(sql, settings=dict(ON_CLUSTER_SETTINGS) if cluster else {}) + + +def _clauses(grants: list[Grant]) -> str: + """` ON ` for each grant, joined: one GRANT takes several.""" + return ", ".join( + f"{', '.join(_privilege(name) for name in grant.privileges)} ON {_target(grant.target)}" + for grant in grants + ) + + +def _privilege(name: str) -> str: + column = _COLUMN.match(name) + if column is None: + return name + return f"{column['privilege']}({quote(column['column'])})" + + +def _target(target: Target) -> str: + if target.source is not None: + return target.source if _WORD.match(target.source) else quote(target.source) + database = quote(target.database) if target.database is not None else "*" + table = quote(target.table) if target.table is not None else "*" + return f"{database}.{table}" + + +def _default_roles(roles: tuple[str, ...] | None) -> str: + """`ALL` when every role a user holds is a default role, `NONE` for none of them.""" + if roles is None: + return "ALL" + return ", ".join(quote(role) for role in roles) or "NONE" diff --git a/ch_migrate/alembic_env.py b/ch_migrate/alembic_env.py index 8d55bff..c3327af 100644 --- a/ch_migrate/alembic_env.py +++ b/ch_migrate/alembic_env.py @@ -21,6 +21,7 @@ from ch_migrate import ui from ch_migrate.config import get_env_config +from ch_migrate.helpers import DICT_READER_PASSWORD_ATTRIBUTE from ch_migrate.hooks import HookRegistry, run_hooks from ch_migrate.rebase import _literal_assignment from ch_migrate.version_table import ( @@ -82,8 +83,8 @@ def _exec_version_update(self, construct, execution_options=None): return SimpleNamespace(rowcount=1) def _insert_version_row(self, construct) -> None: - # Replicated and Shared MergeTree silently drop a block identical to an earlier insert - # (DRY-1447), so re-inserting a previous head after `down` left no version row at all. + # Replicated and Shared MergeTree silently drop a block identical to an earlier insert, + # so re-inserting a previous head after `down` left no version row at all. # A token unique to this write keeps every intentional version row. value = self._compile_clause(next(iter(construct._values.values()))) token = f"'chm_version_{uuid4().hex}'" @@ -105,6 +106,10 @@ def run() -> None: "ch_migrate_environment", os.environ.get("CH_ENVIRONMENT", "dev") ) env_config = get_env_config(environment, root / "config.yaml") + # In memory, not the process environment: create_dictionary reads it during the run. + context.config.attributes[DICT_READER_PASSWORD_ATTRIBUTE] = env_config.get( + "dict_reader_password" + ) os.environ["CH_DATABASE"] = env_config["database"] if env_config.get("cluster"): os.environ["CH_CLUSTER"] = env_config["cluster"] diff --git a/ch_migrate/bootstrap.py b/ch_migrate/bootstrap.py index 5954db7..c51be09 100644 --- a/ch_migrate/bootstrap.py +++ b/ch_migrate/bootstrap.py @@ -1,31 +1,91 @@ -""" -Bootstrap script for initializing ClickHouse database and users. +"""`ch-migrate bootstrap`: the database and the migration role and user for an environment. Usage: ch-migrate bootstrap ch-migrate bootstrap --dry-run -This script: -1. Connects using admin credentials -2. Creates the target database (if not exists) -3. Creates roles for migration, read-only, and dict access -4. Creates users and assigns roles -5. Is idempotent - safe to run multiple times +It runs on the access engine (`ch_migrate.access.bootstrap`; design note, 2.5): +- with an access.yaml, it adds the role's profile and `migration_role.grants`; +- without one, legacy mode gives the grants 0.8 gave, plus the read-only and dictionary + roles and users config.yaml names, with every failure reported (Decisions 6 and 13); +- either way, it needs ClickHouse 25.8 or later, and ends with `access check`, logged in + as the migration user. + +Its exit codes are `access apply`'s: 0 when done, 1 when something failed (each failure +named), and 2 on an error before any change. `--dry-run` prints the SQL without connecting +or reading a secret. It is safe to run again. + +`run_bootstrap` and `build_bootstrap_sql` keep their 0.8 signatures, because client code may +call them. `build_bootstrap_sql` is deprecated. """ +from __future__ import annotations + import re import sys from pathlib import Path from typing import Optional +import click + from ch_migrate import ui -from ch_migrate.config import get_env_config -from ch_migrate.secrets import get_secret # Pattern for valid SQL identifiers (database, user, role names) _IDENTIFIER_PATTERN = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$") +def main() -> None: + """CLI entrypoint for bootstrap.""" + if len(sys.argv) < 2: + print("Usage: ch-migrate bootstrap [--dry-run]") + print("Example: ch-migrate bootstrap dev") + sys.exit(1) + + dry_run = "--dry-run" in sys.argv + env_name = sys.argv[1] + + try: + run_bootstrap(env_name, dry_run=dry_run) + except BootstrapFailed as failure: + sys.exit(failure.exit_code) + except Exception as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(2) + + +class BootstrapFailed(Exception): + """`bootstrap` changed something and then failed; what failed is already printed.""" + + def __init__(self, exit_code: int = 1): + super().__init__(f"bootstrap failed (exit code {exit_code})") + self.exit_code = exit_code + + +@click.command("bootstrap") +@click.argument("environment") +@click.option("--dry-run", is_flag=True, help="Show SQL without connecting or reading a secret") +@click.option("--verbose", "-v", is_flag=True, help="Show SQL statements as they execute") +def bootstrap_command(environment: str, dry_run: bool, verbose: bool) -> None: + """Set up the database, migration role and user for an environment. + + With access.yaml, the migration role gets its profile and `migration_role.grants`; + `access apply` makes the rest. Without it, bootstrap gives what 0.8 gave: the migration + role and user, and the optional MCP and dict_reader users. Then it checks the grants, + logged in as the migration user. Safe to run again. + + Requires admin and migration credentials in .env.local or SSM, but none with --dry-run. + Exits 0 when done, 1 when something failed (each failure named), and 2 on an error + before any change. + """ + try: + run_bootstrap(environment, dry_run=dry_run, verbose=verbose) + except BootstrapFailed as failure: + raise click.exceptions.Exit(failure.exit_code) from None + except Exception as error: # noqa: BLE001 - run_bootstrap raises these before any change + _report_error(error) + raise click.exceptions.Exit(2) from None + + def validate_identifier(name: str, label: str) -> str: """ Validate a SQL identifier (database, user, role name). @@ -58,7 +118,7 @@ def escape_sql_string(s: str) -> str: return s.replace("\\", "\\\\").replace("'", "''") -def build_bootstrap_sql( +def build_bootstrap_sql( # style-ok: public signature kept for compatibility *, project: str, db: str, @@ -69,321 +129,82 @@ def build_bootstrap_sql( mcp_user_name: Optional[str] = None, mcp_password: Optional[str] = None, ) -> str: - """ - Build the bootstrap SQL with optional users. + """Deprecated: the SQL 0.8's `bootstrap` ran, rendered from the built-in `legacy` profile. - Args: - project: Project name (used for role prefixes) - db: Database name - migration_user: Migration user name - migration_password: Migration user password - dict_reader_name: Optional dict reader user name - dict_reader_password: Optional dict reader password - mcp_user_name: Optional MCP user name - mcp_password: Optional MCP user password + `ch-migrate bootstrap` doesn't run this text any more; it runs the access engine. This + stays because client code may call it. It returns 0.8's statements, each password a + quoted string, with the roles and users created before any grant (Decision 6). An MCP or + dict reader user is included only with its password, as in 0.8. - Returns: - Complete SQL string for bootstrap - - Raises: - ValueError: If any identifier contains invalid characters + Raises ValueError for a name that isn't a valid identifier. """ - # Validate all identifiers to prevent SQL injection - project = validate_identifier(project, "project name") - db = validate_identifier(db, "database name") - migration_user = validate_identifier(migration_user, "migration user") - if dict_reader_name: - dict_reader_name = validate_identifier(dict_reader_name, "dict reader user") - if mcp_user_name: - mcp_user_name = validate_identifier(mcp_user_name, "MCP user") - - lines = [ - "-- Bootstrap script for ClickHouse database", - "-- Safe to run multiple times (idempotent)", - "", - "-- Create database", - f"CREATE DATABASE IF NOT EXISTS {db};", - "", - "-- =============================================================================", - "-- ROLES", - "-- =============================================================================", - "", - "-- Migration role: schema changes and data operations", - "-- (Explicit grants instead of ALL for ClickHouse Cloud compatibility)", - f"CREATE ROLE IF NOT EXISTS {project}_migration_role;", - "", - "-- Schema operations (RENAME is part of ALTER)", - f"GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT CREATE VIEW, DROP VIEW ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT CREATE DICTIONARY, DROP DICTIONARY ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT CREATE FUNCTION, DROP FUNCTION ON *.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- User/role management (for migrations that create RLS users/roles)", - "-- CURRENT GRANTS: ClickHouse Cloud's admin cannot grant ALTER/DROP USER on its managed sql-console user", - f"GRANT CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*) TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT ROLE ADMIN ON *.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- Row-level security management", - f"GRANT ACCESS MANAGEMENT ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - f"GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- Data operations", - f"GRANT SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- Introspection (needed by Alembic)", - f"GRANT SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON {db}.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- Temp tables (for zero-downtime migrations with EXCHANGE TABLES)", - "-- Note: EXCHANGE TABLES requires DROP on both tables, already granted above", - f"GRANT CREATE TEMPORARY TABLE ON *.* TO {project}_migration_role WITH GRANT OPTION;", - "", - "-- System table access (monitoring migrations, RLS introspection, user/role management)", - "-- Use CURRENT GRANTS to avoid failure when admin lacks access to some system tables", - "-- (e.g., system.zookeeper on ClickHouse Cloud)", - f"GRANT CURRENT GRANTS(SELECT ON system.*) TO {project}_migration_role WITH GRANT OPTION;", - "-- ClickHouse Cloud requires explicit grants for individual system tables", - f"GRANT SELECT ON system.grants TO {project}_migration_role;", - f"GRANT SELECT ON system.databases TO {project}_migration_role;", - f"GRANT SELECT ON system.tables TO {project}_migration_role;", - f"GRANT SELECT ON system.mutations TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(SELECT ON system.replicas) TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(SELECT ON system.parts) TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON {db}.*) TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON {db}.*) TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(CLUSTER ON *.*) TO {project}_migration_role;", - f"GRANT CURRENT GRANTS(READ ON REMOTE) TO {project}_migration_role;", - ] - - # MCP readonly role (optional) - if mcp_user_name and mcp_password: - lines.extend( - [ - "", - "-- Read-only role: for MCP tools", - f"CREATE ROLE IF NOT EXISTS {project}_readonly_role;", - f"GRANT SELECT ON {db}.* TO {project}_readonly_role;", - f"GRANT SHOW TABLES ON {db}.* TO {project}_readonly_role;", - ] - ) - - # Dict reader role (optional) - if dict_reader_name and dict_reader_password: - lines.extend( - [ - "", - "-- Dict reader role: for dictionary sources", - f"CREATE ROLE IF NOT EXISTS {project}_dict_role;", - "-- SELECT grants added per-table when dictionaries are created", - ] - ) - - lines.extend( - [ - "", - "-- =============================================================================", - "-- USERS", - "-- =============================================================================", - "", - "-- Migration user (required)", - f"CREATE USER IF NOT EXISTS {migration_user}", - f"IDENTIFIED BY '{escape_sql_string(migration_password)}';", - f"GRANT {project}_migration_role TO {migration_user};", - ] + from ch_migrate.access.bootstrap import legacy_bootstrap_sql + from ch_migrate.access.settings import ProjectSettings + + settings = ProjectSettings( + environment="", + project=validate_identifier(project, "project name"), + database=validate_identifier(db, "database name"), + migration_user=validate_identifier(migration_user, "migration user"), + dict_reader_name=_optional_name(dict_reader_name, dict_reader_password, "dict reader user"), + mcp_user_name=_optional_name(mcp_user_name, mcp_password, "MCP user"), + ) + passwords = { + "migration_password": migration_password, + "dict_reader_password": dict_reader_password or "", + "mcp_password": mcp_password or "", + } + return legacy_bootstrap_sql( + settings, lambda secret: f"'{escape_sql_string(passwords[secret.name])}'" ) - - # MCP user (optional) - if mcp_user_name and mcp_password: - lines.extend( - [ - "", - "-- MCP user: read-only access for AI tools", - f"CREATE USER IF NOT EXISTS {mcp_user_name}", - f"IDENTIFIED BY '{escape_sql_string(mcp_password)}';", - f"GRANT {project}_readonly_role TO {mcp_user_name};", - ] - ) - - # Dict reader user (optional) - if dict_reader_name and dict_reader_password: - lines.extend( - [ - "", - "-- Dict reader user: for dictionary sources", - f"CREATE USER IF NOT EXISTS {dict_reader_name}", - f"IDENTIFIED BY '{escape_sql_string(dict_reader_password)}';", - f"GRANT {project}_dict_role TO {dict_reader_name};", - ] - ) - - return "\n".join(lines) -def run_bootstrap( +def run_bootstrap( # style-ok: public signature kept for compatibility env_name: str, config_path: Optional[Path] = None, dry_run: bool = False, verbose: bool = False, ) -> None: - """ - Run bootstrap for the specified environment. + """Bootstrap one environment, as `ch-migrate bootstrap ENV` does. - Args: - env_name: Environment name (dev, staging, production, etc.) - config_path: Path to config.yaml (defaults to ./config.yaml) - dry_run: If True, print SQL without executing - verbose: If True, print each SQL statement as it executes + `config_path` defaults to ./config.yaml; access.yaml is read from the same directory. + Before any change it raises: ValueError for config.yaml, and + `ch_migrate.access.server.AccessError` for access.yaml, a secret or the server. Once a + change may have been made, a failure is printed, then raises `BootstrapFailed`. """ - if config_path is None: - config_path = Path.cwd() / "config.yaml" - - env_config = get_env_config(env_name, config_path) - - # Get SSM paths if configured - ssm_config = env_config.get("ssm", {}) - - # Get AWS region for SSM lookups (optional, uses AWS default if not set) - aws_region = env_config.get("aws_region") - - # Get required credentials - admin_password = get_secret( - env_name, - "admin_password", - ssm_path=ssm_config.get("admin_password"), - aws_region=aws_region, - required=True, - ) - - migration_password = get_secret( - env_name, - "migration_password", - ssm_path=ssm_config.get("migration_password"), - aws_region=aws_region, - required=True, - ) - assert admin_password is not None # required=True ensures this - assert migration_password is not None # required=True ensures this - - # Get optional credentials - dict_reader_name = env_config.get("dict_reader_name") - dict_reader_password = None - if dict_reader_name: - dict_reader_password = get_secret( - env_name, - "dict_reader_password", - ssm_path=ssm_config.get("dict_reader_password"), - aws_region=aws_region, - required=True, - ) - - mcp_user_name = env_config.get("mcp_user_name") - mcp_password = None - if mcp_user_name: - mcp_password = get_secret( - env_name, - "mcp_password", - ssm_path=ssm_config.get("mcp_password"), - aws_region=aws_region, - required=True, - ) - - # Get migration user - support both new 'migration_user' and legacy 'user' field - migration_user = env_config.get("migration_user") or env_config.get("user") - if not migration_user: - raise ValueError(f"migration_user is required in config.yaml for environment '{env_name}'") - - # Build SQL - project_config = env_config.get("project") - if project_config: - project = project_config - else: - # Derive from database name (e.g., myproject_dev -> myproject) - project = env_config["database"].split("_")[0] - - sql = build_bootstrap_sql( - project=project, - db=env_config["database"], - migration_user=migration_user, - migration_password=migration_password, - dict_reader_name=dict_reader_name, - dict_reader_password=dict_reader_password, - mcp_user_name=mcp_user_name, - mcp_password=mcp_password, - ) + from ch_migrate.access.bootstrap import Bootstrap, dry_run_sql, run + from ch_migrate.access.settings import load_settings + path = config_path or Path.cwd() / "config.yaml" + request = Bootstrap(load_settings(env_name, path), path.parent, verbose) if dry_run: - ui.step(f"Dry run for {env_name}: the SQL bootstrap would run") - # Mask passwords in output - masked_sql = sql - for pw in [migration_password, dict_reader_password, mcp_password]: - if pw: - masked_sql = masked_sql.replace(pw, "********") - print(masked_sql) + ui.step(f"Dry run for {env_name}: the SQL `bootstrap` would run", stderr=True) + click.echo(dry_run_sql(request)) return + code = run(request) + if code: + raise BootstrapFailed(code) # 1, or 130 when interrupted - host = env_config["host"] - admin_user = env_config.get("admin_user", "default") - secure = env_config.get("secure", True) - port = env_config.get("port", 8443 if secure else 8123) - ui.step( - f"Bootstrapping {env_name}: database {env_config['database']} on {host}, as {admin_user}" - ) - ui.detail(f"Migration user: {migration_user}") - if dict_reader_name: - ui.detail(f"Dict reader: {dict_reader_name}") - if mcp_user_name: - ui.detail(f"MCP user: {mcp_user_name}") - - import clickhouse_connect - - client = clickhouse_connect.get_client( - host=host, - port=port, - username=admin_user, - password=admin_password, - secure=secure, - interface="https" if secure else "http", - ) +def _optional_name(name: Optional[str], password: Optional[str], label: str) -> Optional[str]: + """An optional user's name, validated; 0.8 creates the user only with its password.""" + if name: + validate_identifier(name, label) + return name if name and password else None - # Collect passwords for masking in verbose output - passwords_to_mask = [p for p in [migration_password, dict_reader_password, mcp_password] if p] - - # Execute each statement - for statement in sql.split(";"): - statement = statement.strip() - # Strip leading comment lines to get to the actual SQL - lines = statement.split("\n") - sql_lines = [line for line in lines if not line.strip().startswith("--")] - actual_sql = "\n".join(sql_lines).strip() - if actual_sql: - if verbose: - # Mask passwords in output - masked = statement - for pw in passwords_to_mask: - masked = masked.replace(pw, "********") - ui.detail(f"{masked};") - client.command(actual_sql) - - ui.success(f"Bootstrap complete for {env_name}.") - ui.hint(f"Next: `ch-migrate new {env_name} NAME --table TABLE`, or `ch-migrate up {env_name}`.") +def _report_error(error: Exception) -> None: + """What stopped `bootstrap` before any change: each reason a `Refusal` gives, or one.""" + from ch_migrate.access.server import AccessError, hide_secrets -def main() -> None: - """CLI entrypoint for bootstrap.""" - if len(sys.argv) < 2: - print("Usage: ch-migrate bootstrap [--dry-run]") - print("Example: ch-migrate bootstrap dev") - sys.exit(1) - - dry_run = "--dry-run" in sys.argv - env_name = sys.argv[1] - - try: - run_bootstrap(env_name, dry_run=dry_run) - except Exception as e: - print(f"Error: {e}", file=sys.stderr) - sys.exit(1) + messages = getattr(error, "messages", None) + if messages: + for message in messages: + ui.error(hide_secrets(message)) + return + known = isinstance(error, (ValueError, AccessError)) + reason = str(error) if known else f"{type(error).__name__}: {error}" + ui.error(f"Bootstrap failed: {hide_secrets(reason)}") if __name__ == "__main__": diff --git a/ch_migrate/cli.py b/ch_migrate/cli.py index 144741e..5c1cb3e 100644 --- a/ch_migrate/cli.py +++ b/ch_migrate/cli.py @@ -17,7 +17,9 @@ from dotenv import load_dotenv from ch_migrate import __version__, ui +from ch_migrate.access.cli import access from ch_migrate.authoring import NewOptions +from ch_migrate.bootstrap import bootstrap_command from ch_migrate.config import get_env_config from ch_migrate.json_output import ( JsonCommand, @@ -28,6 +30,7 @@ lint_document, status_document, ) +from ch_migrate.project_init import get_template_path, init, render_template # noqa: F401 from ch_migrate.runner import alembic_failure, run_alembic, run_migrations if TYPE_CHECKING: @@ -41,19 +44,6 @@ load_dotenv(_env_local) -def get_template_path(name: str) -> Path: - """Get path to a template file.""" - return Path(__file__).parent / "templates" / "project" / f"{name}.template" - - -def render_template(template_path: Path, **kwargs: str) -> str: - """Render a template with substitutions.""" - content = template_path.read_text() - for key, value in kwargs.items(): - content = content.replace(f"{{{key}}}", value) - return content - - def _require_current_env() -> None: from ch_migrate.alembic_env import has_current_env @@ -147,95 +137,6 @@ def main() -> None: pass -@main.command() -@click.argument("path", default=".", type=click.Path()) -@click.option("--name", "-n", default=None, help="Project name (defaults to directory name)") -def init(path: str, name: str | None) -> None: - """Initialize a new ClickHouse migration project. - - Creates the project structure with config.yaml and migrations directory. - """ - project_path = Path(path).resolve() - - if name is None: - name = project_path.name - - # Normalize project name (replace spaces/hyphens with underscores for database names) - safe_name = name.replace("-", "_").replace(" ", "_").lower() - - ui.step(f"Creating ClickHouse migration project {name} in {project_path}") - - # Create directories - project_path.mkdir(parents=True, exist_ok=True) - (project_path / "migrations" / "sql" / "bootstrap").mkdir(parents=True, exist_ok=True) - (project_path / "migrations" / "sql" / "history" / "tables").mkdir(parents=True, exist_ok=True) - (project_path / "migrations" / "sql" / "history" / "views").mkdir(parents=True, exist_ok=True) - (project_path / "migrations" / "sql" / "history" / "dictionaries").mkdir( - parents=True, exist_ok=True - ) - (project_path / "migrations" / "versions").mkdir(parents=True, exist_ok=True) - - # Copy/render templates - templates = [ - ("alembic.ini", "alembic.ini"), - ("config.yaml", "config.yaml"), - ("env.local.example", ".env.local.example"), - ("script.py.mako", "migrations/script.py.mako"), - ] - - for template_name, output_name in templates: - template_path = get_template_path(template_name) - output_path = project_path / output_name - - if output_path.exists(): - ui.detail(f"Skipped {output_name} (already exists)") - continue - - content = render_template(template_path, project_name=safe_name) - output_path.write_text(content) - ui.detail(f"Created {output_name}") - - # Copy env.py from package - env_py_src = Path(__file__).parent / "env.py" - env_py_dst = project_path / "migrations" / "env.py" - if not env_py_dst.exists(): - shutil.copy(env_py_src, env_py_dst) - ui.detail("Created migrations/env.py") - - # Create .gitignore - gitignore_path = project_path / ".gitignore" - if not gitignore_path.exists(): - gitignore_path.write_text(".env.local\n__pycache__/\n*.pyc\n") - ui.detail("Created .gitignore") - - ui.success("Project created. Next steps:") - ui.hint(" 1. Point config.yaml at your ClickHouse servers.") - ui.hint(" 2. Copy .env.local.example to .env.local and add the passwords.") - ui.hint(" 3. Run `ch-migrate bootstrap dev`.") - ui.hint(" 4. Run `ch-migrate new dev create_users --table users`, then write the SQL") - ui.hint(" in the .up.sql and .down.sql files it creates.") - - -@main.command() -@click.argument("environment") -@click.option("--dry-run", is_flag=True, help="Show SQL without executing") -@click.option("--verbose", "-v", is_flag=True, help="Show SQL statements as they execute") -def bootstrap(environment: str, dry_run: bool, verbose: bool) -> None: - """Initialize database and users for an environment. - - Creates the database, roles, and users (migration user, optional MCP user, - optional dict_reader user). Safe to run multiple times (idempotent). - - Requires admin credentials in .env.local or SSM. - """ - from ch_migrate.bootstrap import run_bootstrap - - try: - run_bootstrap(environment, dry_run=dry_run, verbose=verbose) - except Exception as e: - ui.fail(f"Bootstrap failed: {e}") - - @main.command() @click.argument("environment") @click.option("--revision", "-r", default="head", help="Revision to upgrade to (default: head)") @@ -1209,5 +1110,9 @@ def should_include(name: str) -> bool: ) +main.add_command(init) +main.add_command(bootstrap_command) +main.add_command(access) + if __name__ == "__main__": main() diff --git a/ch_migrate/helpers.py b/ch_migrate/helpers.py index def0364..0dc003d 100644 --- a/ch_migrate/helpers.py +++ b/ch_migrate/helpers.py @@ -7,10 +7,9 @@ from pathlib import Path from typing import Any - -def _get_sql_dir() -> Path: - """Get the SQL directory relative to current working directory.""" - return Path.cwd() / "migrations" / "sql" +# The Alembic config attribute that carries the environment's dict_reader_password secret +# from the migration environment to create_dictionary. +DICT_READER_PASSWORD_ATTRIBUTE = "ch_migrate_dict_reader_password" def read_sql(path: str, **kwargs: Any) -> str: @@ -96,18 +95,23 @@ def get_config_value(key: str) -> str | None: def create_dictionary(path: str, *, db: str | None = None, password: str | None = None) -> None: """ - Create a dictionary with automatic SELECT grant for dict_reader. + Create a dictionary; without an access.yaml, first grant dict_reader SELECT on its source. This helper: - 1. Reads the dictionary SQL file - 2. Parses the source table from the SQL - 3. Grants SELECT on that table to dict_reader - 4. Creates the dictionary + 1. Reads the dictionary SQL file, filling in `{db}` and `{password}` + 2. Without an access.yaml, grants SELECT on the source table to dict_reader + 3. Creates the dictionary + + With an access.yaml, the dictionary's reader and its SELECT are declared there, so the + helper grants nothing: the core profile can't grant, and `access apply` would revoke a + grant a migration gave that access.yaml doesn't declare. Args: path: Relative path to dictionary SQL file db: Database name (defaults to get_db()) - password: dict_reader password (defaults to DICT_READER_PASSWORD env var) + password: the reader's password (defaults to DICT_READER_PASSWORD, else the + environment's dict_reader_password secret: its SSM path in config.yaml, or + CH__DICT_READER_PASSWORD) Example: create_dictionary("history/dictionaries/dict_users/001_abc.sql") @@ -115,27 +119,21 @@ def create_dictionary(path: str, *, db: str | None = None, password: str | None # Import here to avoid circular imports and allow usage without alembic context from alembic import op + from ch_migrate.secrets import remember_secret + if db is None: db = get_db() - if password is None: - password = os.environ.get("DICT_READER_PASSWORD") - if not password: - raise ValueError( - "DICT_READER_PASSWORD environment variable is required for dictionaries." - ) - - # Read and format the dictionary SQL + password = password or _dict_reader_password() + # The statement carries the password as a literal, so an error that quotes it must hide it. + remember_secret(password) dict_sql = read_sql(path, db=db, password=password) - - # Parse the source table from the SQL source_table = _parse_source_table(dict_sql) - - if source_table: - # Grant SELECT to dict_reader before creating dictionary + if source_table and not _has_access_file(): + # style-ok: GRANT names identifiers, which ClickHouse can't take as bound parameters op.execute(f"GRANT SELECT ON {db}.{source_table} TO dict_reader") - - # Create the dictionary - op.execute(dict_sql) + # SQLAlchemy reads `:name` as a bind parameter, so a password starting with `:` broke the + # statement. `\:` keeps the colon, as run_sql does. + op.execute(dict_sql.replace(":", r"\:")) def _parse_source_table(dict_sql: str) -> str | None: @@ -160,3 +158,34 @@ def _parse_source_table(dict_sql: str) -> str | None: return query_match.group(1) return None + + +def _dict_reader_password() -> str: + # The migration environment resolves config.yaml's dict_reader_password secret, from SSM + # or CH__DICT_READER_PASSWORD, and hands it over in memory (alembic_env.run). + from alembic import context + + password = os.environ.get("DICT_READER_PASSWORD") or context.config.attributes.get( + DICT_READER_PASSWORD_ATTRIBUTE + ) + if not password: + raise ValueError( + "create_dictionary needs the dictionary reader's password: set " + "CH__DICT_READER_PASSWORD, an ssm path for dict_reader_password in " + "config.yaml, or DICT_READER_PASSWORD." + ) + return password + + +def _has_access_file() -> bool: + # access.yaml sits beside config.yaml in the project root, the working directory during + # a migration, as migrations/sql does for _get_sql_dir. The access commands' rule decides: + # an empty one is an error, not legacy mode. + from ch_migrate.access.loader import declares_access + + return declares_access(Path.cwd()) + + +def _get_sql_dir() -> Path: + """Get the SQL directory relative to current working directory.""" + return Path.cwd() / "migrations" / "sql" diff --git a/ch_migrate/migration_runner.py b/ch_migrate/migration_runner.py index f444fc6..ca1cbfc 100644 --- a/ch_migrate/migration_runner.py +++ b/ch_migrate/migration_runner.py @@ -11,6 +11,7 @@ import logging import os import re +import sys import traceback from contextlib import contextmanager from dataclasses import dataclass @@ -28,6 +29,7 @@ _report_success, _start_migration, ) +from ch_migrate.secrets import hide_secrets from ch_migrate.sql import clean_database_error from ch_migrate.waiting.display import WaitDisplay from ch_migrate.waiting.errors import ( @@ -137,7 +139,7 @@ def _report_failure(upgrade: Upgrade, progress: _Progress, error: Exception) -> elif isinstance(waiting, InterruptedStep): _report_interrupted_step(upgrade.environment, waiting) elif waiting is not None: - ui.error(f"{where}: {waiting}") + ui.error(f"{where}: {hide_secrets(str(waiting))}") else: _report_statement_failure(upgrade, where, error) @@ -151,7 +153,7 @@ def _report_mutation_failure(environment: str, where: str, failure: FailedMutati ) else: ui.error(f"{where} failed: mutation {failure.mutation} on {failure.table} failed{on_host}") - ui.detail(clean_database_error(failure.reason), stderr=True) + ui.detail(hide_secrets(clean_database_error(failure.reason)), stderr=True) ui.hint( "It was not recorded as applied. ClickHouse keeps retrying a failed mutation, and later " f"mutations on {failure.table} wait behind it.", @@ -188,7 +190,8 @@ def _report_interrupted_step(environment: str, stop: InterruptedStep) -> None: ) for item in stop.unvouched: where = f"{item.statement.source}:{item.statement.line}" - ui.detail(f"{where} {item.why}: {item.statement.sql.splitlines()[0]}", stderr=True) + first_line = hide_secrets(item.statement.sql.splitlines()[0]) + ui.detail(f"{where} {item.why}: {first_line}", stderr=True) ui.hint( "Some of its statements may already have applied. Check what the earlier run changed, " f"then run `ch-migrate up {environment} --rerun-interrupted {revision}`.", @@ -198,14 +201,16 @@ def _report_interrupted_step(environment: str, stop: InterruptedStep) -> None: def _report_statement_failure(upgrade: Upgrade, where: str, error: Exception) -> None: ui.error(f"{where} failed") - ui.detail(_reason(error), stderr=True) + ui.detail(hide_secrets(_reason(error)), stderr=True) ui.hint( "It was not recorded as applied. Anything it ran before the failure stays in place, " f"so make the SQL safe to re-run, then run `ch-migrate up {upgrade.environment}` again.", stderr=True, ) if upgrade.verbose: - traceback.print_exception(error) + # SQLAlchemy's message quotes the statement, which can carry a password, such as a + # dictionary source's. + sys.stderr.write(hide_secrets("".join(traceback.format_exception(error)))) else: ui.hint("Add `--verbose` to see the full traceback.", stderr=True) diff --git a/ch_migrate/project_init.py b/ch_migrate/project_init.py new file mode 100644 index 0000000..94fd727 --- /dev/null +++ b/ch_migrate/project_init.py @@ -0,0 +1,101 @@ +"""`ch-migrate init`: a new project's directories and starter files. + +A new project gets an access.yaml whose migration role holds the `core` profile, with +commented examples (design note, Decision 5). Files that already exist are left alone. +""" + +from __future__ import annotations + +import shutil +from pathlib import Path + +import click + +from ch_migrate import ui + +# Each template under templates/project/, and the file it becomes in the project. +TEMPLATES = ( + ("alembic.ini", "alembic.ini"), + ("config.yaml", "config.yaml"), + ("access.yaml", "access.yaml"), + ("env.local.example", ".env.local.example"), + ("script.py.mako", "migrations/script.py.mako"), +) +DIRECTORIES = ( + "migrations/sql/bootstrap", + "migrations/sql/history/tables", + "migrations/sql/history/views", + "migrations/sql/history/dictionaries", + "migrations/versions", +) +NEXT_STEPS = ( + " 1. Point config.yaml at your ClickHouse servers.", + " 2. Copy .env.local.example to .env.local and add the passwords.", + " 3. Run `ch-migrate bootstrap dev`.", + " 4. Run `ch-migrate new dev create_users --table users`, then write the SQL", + " in the .up.sql and .down.sql files it creates.", +) + + +@click.command() +@click.argument("path", default=".", type=click.Path()) +@click.option("--name", "-n", default=None, help="Project name (defaults to directory name)") +def init(path: str, name: str | None) -> None: + """Initialize a new ClickHouse migration project. + + Creates the project structure with config.yaml, access.yaml and the migrations directory. + """ + project_path = Path(path).resolve() + if name is None: + name = project_path.name + # Normalize project name (replace spaces/hyphens with underscores for database names) + safe_name = name.replace("-", "_").replace(" ", "_").lower() + ui.step(f"Creating ClickHouse migration project {name} in {project_path}") + project_path.mkdir(parents=True, exist_ok=True) + for directory in DIRECTORIES: + (project_path / directory).mkdir(parents=True, exist_ok=True) + _write_templates(project_path, safe_name) + _write_env_py(project_path) + _write_gitignore(project_path) + ui.success("Project created. Next steps:") + for line in NEXT_STEPS: + ui.hint(line) + + +def get_template_path(name: str) -> Path: + """Get path to a template file.""" + return Path(__file__).parent / "templates" / "project" / f"{name}.template" + + +def render_template(template_path: Path, **kwargs: str) -> str: + """Render a template with substitutions.""" + content = template_path.read_text() + for key, value in kwargs.items(): + content = content.replace(f"{{{key}}}", value) + return content + + +def _write_templates(project_path: Path, safe_name: str) -> None: + for template_name, output_name in TEMPLATES: + output_path = project_path / output_name + if output_path.exists(): + ui.detail(f"Skipped {output_name} (already exists)") + continue + content = render_template(get_template_path(template_name), project_name=safe_name) + output_path.write_text(content) + ui.detail(f"Created {output_name}") + + +def _write_env_py(project_path: Path) -> None: + """Copy env.py from the package.""" + env_py_dst = project_path / "migrations" / "env.py" + if not env_py_dst.exists(): + shutil.copy(Path(__file__).parent / "env.py", env_py_dst) + ui.detail("Created migrations/env.py") + + +def _write_gitignore(project_path: Path) -> None: + gitignore_path = project_path / ".gitignore" + if not gitignore_path.exists(): + gitignore_path.write_text(".env.local\n__pycache__/\n*.pyc\n") + ui.detail("Created .gitignore") diff --git a/ch_migrate/secrets.py b/ch_migrate/secrets.py index b54a725..24b730c 100644 --- a/ch_migrate/secrets.py +++ b/ch_migrate/secrets.py @@ -2,7 +2,8 @@ import json import os -from typing import Optional, Union +from typing import Iterable, Optional, Union +from urllib.parse import quote, quote_plus class SSMSecretNotFoundError(Exception): @@ -17,6 +18,83 @@ class SSMJsonKeyError(Exception): pass +# Every secret `get_secret` has returned in this process, so that no error ch-migrate prints +# later shows one, raw or URL-encoded. +_SEEN: set[str] = set() + + +# style-ok: get_secret's public keyword signature predates 0.9; callers pass these by name +def get_secret( + env_name: str, + key: str, + *, + ssm_path: Optional[Union[str, dict]] = None, + aws_region: Optional[str] = None, + required: bool = True, +) -> Optional[str]: + """ + Get a secret value from SSM or environment variable. + + Precedence: + 1. SSM parameter at ssm_path (if provided) - use SSM directly + 2. Environment variable CH_{ENV}_{KEY} (e.g., CH_DEV_MIGRATION_PASSWORD) + 3. Legacy env var for migration_password: CH_{ENV}_PASSWORD + 4. None (if not required) or raise ValueError + + SSM path formats: + - Simple string: "/myproject/dev/password" + - With JSON key (hash suffix): "/myproject/credentials#password" + - With JSON key (object): {"path": "/myproject/credentials", "json_key": "password"} + + Args: + env_name: Environment name (dev, staging, production) + key: Secret key (migration_password, admin_password, dict_reader_password) + ssm_path: Optional SSM parameter path (string or dict with path/json_key) + aws_region: Optional AWS region for SSM lookups (e.g., 'us-east-1') + required: Whether to raise if secret not found + + Returns: + Secret value or None if not required and not found + + Raises: + ValueError: If required and not found in env or SSM + SSMSecretNotFoundError: If SSM path provided but parameter not found + SSMJsonKeyError: If JSON key specified but not found in parameter value + ImportError: If SSM path provided but boto3 not installed + """ + value = _find_secret(env_name, key, ssm_path=ssm_path, aws_region=aws_region, required=required) + if value: + remember_secret(value) + return value + + +def remember_secret(value: str) -> None: + """Hide `value` in every error printed from now on, as `get_secret` does for its own.""" + if value: + _SEEN.add(str(value)) + + +def hide_secrets(text: str, secrets: Iterable[str] = ()) -> str: + """`text` with every secret seen so far, and each of `secrets`, replaced by `[hidden]`. + + Each is hidden raw, as a URL or a form encodes it, since a driver error can quote the + request, and as SQLAlchemy escapes it in a statement it quotes: `%` doubled, and `:` + after a backslash. + """ + for secret in sorted({*_SEEN, *secrets}, key=len, reverse=True): + if not secret: # "" would put the mark between every two characters + continue + for form in sorted(_forms(secret), key=len, reverse=True): + text = text.replace(form, "[hidden]") + return text + + +def _forms(secret: str) -> set[str]: + """`secret` as it can appear in an error: raw, URL- or form-encoded, or SQL-escaped.""" + escaped = {secret.replace("%", "%%"), secret.replace(":", "\\:")} + return {secret, quote(secret), quote(secret, safe=""), quote_plus(secret), *escaped} + + def _get_ssm_client(region: Optional[str] = None): # type: ignore[no-untyped-def] """Get boto3 SSM client, raising helpful error if boto3 not installed. @@ -69,7 +147,8 @@ def _parse_ssm_path(ssm_path: Union[str, dict]) -> tuple[str, Optional[str]]: return ssm_path, None -def get_secret( +# style-ok: 0.8's get_secret body, unchanged apart from its name +def _find_secret( env_name: str, key: str, *, @@ -77,36 +156,7 @@ def get_secret( aws_region: Optional[str] = None, required: bool = True, ) -> Optional[str]: - """ - Get a secret value from SSM or environment variable. - - Precedence: - 1. SSM parameter at ssm_path (if provided) - use SSM directly - 2. Environment variable CH_{ENV}_{KEY} (e.g., CH_DEV_MIGRATION_PASSWORD) - 3. Legacy env var for migration_password: CH_{ENV}_PASSWORD - 4. None (if not required) or raise ValueError - - SSM path formats: - - Simple string: "/myproject/dev/password" - - With JSON key (hash suffix): "/myproject/credentials#password" - - With JSON key (object): {"path": "/myproject/credentials", "json_key": "password"} - - Args: - env_name: Environment name (dev, staging, production) - key: Secret key (migration_password, admin_password, dict_reader_password) - ssm_path: Optional SSM parameter path (string or dict with path/json_key) - aws_region: Optional AWS region for SSM lookups (e.g., 'us-east-1') - required: Whether to raise if secret not found - - Returns: - Secret value or None if not required and not found - - Raises: - ValueError: If required and not found in env or SSM - SSMSecretNotFoundError: If SSM path provided but parameter not found - SSMJsonKeyError: If JSON key specified but not found in parameter value - ImportError: If SSM path provided but boto3 not installed - """ + """`get_secret` without remembering what it found.""" # If SSM path provided, use SSM directly (don't check env vars) if ssm_path: path, json_key = _parse_ssm_path(ssm_path) diff --git a/ch_migrate/skills/ch-migrate/SKILL.md b/ch_migrate/skills/ch-migrate/SKILL.md index 1f74413..a04afd3 100644 --- a/ch_migrate/skills/ch-migrate/SKILL.md +++ b/ch_migrate/skills/ch-migrate/SKILL.md @@ -35,7 +35,12 @@ The `standalone_set` gate rule cannot be lowered through configuration. | Command | Description | |---------|-------------| | `ch-migrate init [PATH] [--name NAME]` | Initialize project structure | -| `ch-migrate bootstrap ENV [--dry-run]` | Create database, roles, users | +| `ch-migrate bootstrap ENV [--dry-run]` | Create the database and the migration role and user | +| `ch-migrate access validate ENV [--sql]` | Check access.yaml offline; `--sql` prints SQL for a DBA | +| `ch-migrate access show ENV [NAME...]` | Print what the server holds, in access.yaml form | +| `ch-migrate access plan ENV` | Show how the server differs from access.yaml (0 in sync, 1 pending, 2 error) | +| `ch-migrate access apply ENV [--reset-passwords]` | Make the server match access.yaml, as the admin | +| `ch-migrate access check ENV` | Check the migration role's grants, as the migration user | | `ch-migrate new ENV NAME [--table X] [--irreversible REASON]` | Create upgrade/downgrade SQL and their revision | | `ch-migrate up ENV [-r REV]` | Apply migrations (default: head, or to REV) | | `ch-migrate down ENV [-r REV]` | Rollback (default: last, or to REV) | @@ -71,6 +76,7 @@ before Alembic writes a revision. ``` project/ ├── config.yaml # ClickHouse hosts and settings +├── access.yaml # Users, roles and grants (init writes it) ├── .env.local # Secrets (gitignored) ├── alembic.ini # Alembic configuration └── migrations/ @@ -251,7 +257,12 @@ inserts arriving during the copy. Review the schema and column mapping. The generated revision is irreversible because it drops the old table. For dictionaries, `create_dictionary("history/dictionaries/NAME/file.sql")` -retains the configured dictionary reader's automatic SELECT grant. +fills in `{db}` and `{password}`: the reader's password, from +`DICT_READER_PASSWORD` or else the environment's `dict_reader_password` secret +(SSM path or `CH__DICT_READER_PASSWORD`). Without an access.yaml it first +grants SELECT on the source table to `dict_reader`. With one it grants nothing: +declare the reader and its SELECT in access.yaml and run `access apply` before +`up`. For offline SQL, set `CH_ENVIRONMENT` and run `alembic upgrade head --sql`. Existing projects need `ch-migrate upgrade-env` for the offline version-table @@ -260,13 +271,46 @@ and literal-rendering fixes. Keep credentials out of SQL files and logs. ## Roles Created by Bootstrap -| Role | Purpose | -|------|---------| -| `{project}_migration_role` | Schema changes (CREATE/DROP/ALTER TABLE/VIEW/DICTIONARY), data ops (SELECT/INSERT/DELETE/TRUNCATE), and introspection including explicit `system.grants` access | -| `{project}_readonly_role` | SELECT + SHOW (if mcp_user configured) | -| `{project}_dict_role` | Dictionary source access (if dict_reader configured) | - -Note: Bootstrap uses explicit grants (not `GRANT ALL`) for ClickHouse Cloud compatibility. +`bootstrap` creates the database and the migration role and user. With an +`access.yaml` (what `init` writes), every other user and role is declared there +and made by `ch-migrate access apply ENV`, logged in as the admin. Without one, +the project is in legacy mode and gets 0.8's roles. + +| Role | When | Grants | +|------|------|--------| +| `{project}_migration_role`, or `migration_role` from config.yaml | Always | With access.yaml: its profile, `core` by default, plus `migration_role.grants`. Core is schema changes (CREATE/DROP/UNDROP/ALTER TABLE, VIEW, DICTIONARY) and data ops (SELECT/INSERT/DELETE/TRUNCATE/OPTIMIZE) on `{db}.*`, SHOW, and SELECT on `system.databases`, `system.tables`, `system.mutations` and `system.dictionaries`, with no grant option and no user or role management. Without access.yaml: the `legacy` profile, 0.8's grants, which add grant option, functions, user, role and row-policy management, and `system.*` | +| `{project}_readonly_role` | Legacy mode, with `mcp_user_name` | SELECT and SHOW TABLES on `{db}.*` | +| `{project}_dict_role` | Legacy mode, with `dict_reader_name` | None at first; `create_dictionary` grants SELECT on each source table to `dict_reader` | +| Roles declared in access.yaml | `access apply` | Exactly what access.yaml declares | + +Notes: +- Grants are explicit, never `GRANT ALL`. Best-effort grants (cluster, + remote-read, sync, `system.parts`, `system.replicas`) land as far as the + admin can give them; the rest are warnings. +- `bootstrap` and `access apply` only ever add to the migration role. Revoke + extras by hand; `access plan` lists them with `!`. +- A core migration role can't create users or roles, or grant to another user. + Declare them in access.yaml, or set `migration_role.profile: legacy` when + migrations do that. A grant a migration gives to a user or role access.yaml + declares is revoked at the next `access apply` unless access.yaml declares it + too. With an access.yaml, `create_dictionary` grants nothing: declare the + dictionary's reader and its SELECT there. +- The `access` commands and `bootstrap`, with or without an access.yaml, need + ClickHouse 25.8 or later. The admin's `ROLE ADMIN` lets it grant any role to anyone. +- On a self-hosted cluster that keeps users and roles on each node's own disk, + with `cluster` set: `access apply`, and `bootstrap` with an access.yaml, run + ON CLUSTER (the admin needs `CLUSTER ON *.*`). Legacy `bootstrap` never does, + so run it on each node, and run `access validate --sql` output on each node. + `access plan`, `access apply`, and `bootstrap` with an access.yaml, read only + the node they connect to, and name it. After a failed ON CLUSTER apply, point `host` at each node in + turn and run `access plan` there: the first node can report in sync while + another still lacks the change. +- Where users and roles are replicated (Keeper, or ClickHouse Cloud), the access + commands read every replica at once through `clusterAllReplicas`, which needs + the admin's `READ ON REMOTE`. Without it, or with no one cluster to read + through, a missing row is read again for up to `access_read_timeout` seconds. + A lone replicated node keeps this wait too. The reason prints once, only + when the command actually waits. ## Troubleshooting @@ -284,9 +328,12 @@ Note: Bootstrap uses explicit grants (not `GRANT ALL`) for ClickHouse Cloud comp # Check what SQL would run ch-migrate bootstrap dev --dry-run -# Should show masked passwords like: -# CREATE USER IF NOT EXISTS migration_dev -# IDENTIFIED BY '********'; +# Shows each password as a placeholder, which fails to parse if run unedited: +# CREATE USER IF NOT EXISTS migration_dev IDENTIFIED BY ; + +# Check access.yaml offline, then compare it with the server +ch-migrate access validate dev +ch-migrate access plan dev ``` ## ClickHouse Cloud Notes @@ -294,4 +341,6 @@ ch-migrate bootstrap dev --dry-run - Uses standard engines (MergeTree, ReplacingMergeTree) - auto-upgraded to Shared* on Cloud - Default port 8443 (HTTPS), use 8123 for local HTTP - DDL is non-transactional - migrations can't be atomically rolled back +- Cloud grants `CLUSTER` to every login, so the access commands treat core's + best-effort `CLUSTER ON *.*` as held and don't warn about it - Each `op.execute()` runs one statement diff --git a/ch_migrate/templates/bootstrap/init_users.sql b/ch_migrate/templates/bootstrap/init_users.sql deleted file mode 100644 index d62fa6e..0000000 --- a/ch_migrate/templates/bootstrap/init_users.sql +++ /dev/null @@ -1,65 +0,0 @@ --- Bootstrap SQL Reference --- This file documents the SQL structure created by `ch-migrate bootstrap` --- The actual SQL is generated dynamically by bootstrap.py --- --- IMPORTANT: This file is NOT executed directly. It serves as documentation. --- To run bootstrap, use: ch-migrate bootstrap - --- ============================================================================= --- DATABASE --- ============================================================================= - -CREATE DATABASE IF NOT EXISTS {db}; - --- ============================================================================= --- ROLES (always created) --- ============================================================================= - --- Migration role: full access for schema changes and data operations -CREATE ROLE IF NOT EXISTS {project}_migration_role; -GRANT ALL ON {db}.* TO {project}_migration_role; -GRANT CREATE TEMPORARY TABLE ON *.* TO {project}_migration_role; -GRANT CURRENT GRANTS(SELECT ON system.*) TO {project}_migration_role WITH GRANT OPTION; --- ClickHouse Cloud requires explicit grants for individual system tables. -GRANT SELECT ON system.grants TO {project}_migration_role; -GRANT SELECT ON system.databases TO {project}_migration_role; -GRANT SELECT ON system.tables TO {project}_migration_role; -GRANT SELECT ON system.mutations TO {project}_migration_role; -GRANT CURRENT GRANTS(SELECT ON system.replicas) TO {project}_migration_role; -GRANT CURRENT GRANTS(SELECT ON system.parts) TO {project}_migration_role; -GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON {db}.*) TO {project}_migration_role; -GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON {db}.*) TO {project}_migration_role; -GRANT CURRENT GRANTS(CLUSTER ON *.*) TO {project}_migration_role; -GRANT CURRENT GRANTS(READ ON REMOTE) TO {project}_migration_role; - --- ============================================================================= --- USERS (always created) --- ============================================================================= - --- Migration user -CREATE USER IF NOT EXISTS {migration_user} -IDENTIFIED BY '{migration_password}'; -GRANT {project}_migration_role TO {migration_user}; - --- ============================================================================= --- OPTIONAL: MCP User (only if mcp_user_name configured in config.yaml) --- ============================================================================= - --- CREATE ROLE IF NOT EXISTS {project}_readonly_role; --- GRANT SELECT ON {db}.* TO {project}_readonly_role; --- GRANT SHOW TABLES ON {db}.* TO {project}_readonly_role; --- --- CREATE USER IF NOT EXISTS {mcp_user_name} --- IDENTIFIED BY '{mcp_password}'; --- GRANT {project}_readonly_role TO {mcp_user_name}; - --- ============================================================================= --- OPTIONAL: Dict Reader (only if dict_reader_name configured in config.yaml) --- ============================================================================= - --- CREATE ROLE IF NOT EXISTS {project}_dict_role; --- SELECT grants added per-table when dictionaries are created --- --- CREATE USER IF NOT EXISTS {dict_reader_name} --- IDENTIFIED BY '{dict_reader_password}'; --- GRANT {project}_dict_role TO {dict_reader_name}; diff --git a/ch_migrate/templates/project/access.yaml.template b/ch_migrate/templates/project/access.yaml.template new file mode 100644 index 0000000..40b4a0e --- /dev/null +++ b/ch_migrate/templates/project/access.yaml.template @@ -0,0 +1,36 @@ +# Users, roles and grants for this project, declared. +# ch-migrate access validate ENV checks this file, offline +# ch-migrate access plan ENV shows how the server differs from it +# ch-migrate access apply ENV makes the server match, logged in as admin_user +# +# The migration role holds the `core` profile: what migrations need on the project's +# database, with no user or role management. `ch-migrate bootstrap ENV` gives it. +migration_role: + profile: core + # Grants the migration role needs beyond core, such as for functions: + # grants: + # - CREATE FUNCTION, DROP FUNCTION ON *.* + +# Roles and users that `access apply` creates and keeps exactly as declared. Users and +# roles not named here are never touched. Placeholders: {db}, {project}, {env} and +# {migration_role}. +# +# roles: +# analyst: +# grants: +# - SELECT, SHOW TABLES ON {db}.* +# reporting: +# roles: [analyst] +# +# users: +# dashboards: +# # Read from environments..ssm.dashboards_password in config.yaml, else from +# # CH__DASHBOARDS_PASSWORD. It is set only when the user is created. +# password: {secret: dashboards_password} +# roles: [reporting] +# +# A block per environment merges over the above; `absent: true` drops a user or role: +# environments: +# production: +# users: +# dashboards: {absent: true} diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 6412738..00b619f 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -1,250 +1,147 @@ # ch-migrate Quick Reference -## New Project Setup +The commands and setup steps on one page. The [README](../README.md) is the full guide; +its [Quick start](../README.md#quick-start) walks through a first migration step by step. + +## New project ```bash # 1. Install -uv add ch-migrate-cli # or: pip install ch-migrate-cli +uv add ch-migrate-cli # or: pip install ch-migrate-cli -# 2. Initialize -ch-migrate init # creates project structure in current dir -ch-migrate init ./migrations # or specify a path +# 2. Initialize: writes config.yaml, access.yaml and migrations/ +ch-migrate init --name my_project +ch-migrate init ./migrations --name my_project # or in a subdirectory: then `cd migrations`, + # since every command runs from there # 3. Configure -# Edit config.yaml with your ClickHouse host -# Copy .env.local.example to .env.local, add passwords - -# 4. Bootstrap (creates DB, roles, users) -ch-migrate bootstrap dev --dry-run # preview first -ch-migrate bootstrap dev # execute +# config.yaml: the server, database and migration_user for each environment +# .env.local: CH_DEV_ADMIN_PASSWORD and CH_DEV_MIGRATION_PASSWORD -# 5. Create first migration -ch-migrate new dev create_users_table -# Edit the generated migration file - -# 6. Run migration -ch-migrate up dev -``` - -## Existing Project Integration - -```bash -# 1. Install in your project -uv add ch-migrate-cli - -# 2. Initialize in a subdirectory (or root) -ch-migrate init ./migrations --name my_project - -# 3. Configure for your existing ClickHouse -# Edit migrations/config.yaml -# Create migrations/.env.local - -# 4. Bootstrap (safe to run on existing DB) +# 4. Bootstrap: creates the database, the migration role and the migration user +ch-migrate bootstrap dev --dry-run # print the SQL; reads no secrets ch-migrate bootstrap dev -# 5. Create baseline migration (captures existing schema) -ch-migrate new dev baseline -# Edit to include existing tables as no-ops or document current state +# 5. Create a migration: an .up.sql and a .down.sql under migrations/sql/history/ +ch-migrate new dev add_status --table logs -# 6. Run to mark baseline as applied +# 6. Apply it ch-migrate up dev -``` -## Daily Commands - -| Command | Description | -|---------|-------------| -| `ch-migrate status dev` | Show current migration state | -| `ch-migrate new dev ` | Create new migration | -| `ch-migrate up dev` | Apply pending migrations | -| `ch-migrate down dev` | Rollback last migration | -| `ch-migrate down dev -r ` | Rollback to specific revision | -| `ch-migrate history dev` | Show migration history | - -## Troubleshooting - -```bash -# Check if .env.local is loaded -ch-migrate bootstrap dev --dry-run # should show masked passwords - -# Verify connection -ch-migrate status dev - -# See what SQL would run -ch-migrate bootstrap dev --dry-run - -# Check ClickHouse directly -curl "http://localhost:8123/?user=default&password=xxx" -d "SHOW DATABASES" -``` - -## Environment Variables - -| Variable | Required | Description | -|----------|----------|-------------| -| `CH__MIGRATION_PASSWORD` | Yes | Migration user password | -| `CH__ADMIN_PASSWORD` | Bootstrap | Admin password for setup | -| `CH__MCP_PASSWORD` | If configured | Read-only user password | - -Example for dev environment: -```bash -CH_DEV_MIGRATION_PASSWORD=secret123 -CH_DEV_ADMIN_PASSWORD=admin123 +# 7. Users and roles: declare them in access.yaml, then +ch-migrate access plan dev # preview +ch-migrate access apply dev # make the server match, as the admin ``` ---- +The migration role gets the `core` profile: what migrations need on the project's +database, with no right to manage users or roles. `bootstrap` and the `access` commands +that connect need ClickHouse 25.8 or later. -See [Appendices](#appendices) for detailed guides. +To set up a fresh environment: `bootstrap`, `up`, then `access apply`. To deploy: `up`, +then `access apply`. With dictionaries whose reader `access.yaml` declares, run `access apply` +before `up`. -# Appendices - -## Appendix A: Greenfield Setup with Docker - -### 1. Start ClickHouse - -```bash -docker run -d \ - --name clickhouse \ - -p 8123:8123 \ - -e CLICKHOUSE_PASSWORD=admin123 \ - clickhouse/clickhouse-server:latest -``` - -### 2. Create Project - -```bash -mkdir my-project && cd my-project -uv init && uv add ch-migrate-cli -ch-migrate init --name my_project -``` - -### 3. Configure for Local Docker - -**config.yaml:** -```yaml -project: - name: my_project - -defaults: - port: 8123 - secure: false - admin_user: default - -environments: - dev: - host: localhost - database: my_project_dev - migration_user: migration_dev -``` - -**.env.local:** -```bash -CH_DEV_ADMIN_PASSWORD=admin123 -CH_DEV_MIGRATION_PASSWORD=migpass123 -``` +## Existing project -### 4. Bootstrap and Migrate +### Adding ch-migrate to an existing database ```bash +uv add ch-migrate-cli +ch-migrate init ./migrations --name my_project +cd migrations # every command runs from the project directory +# Edit config.yaml and create .env.local ch-migrate bootstrap dev -ch-migrate new dev create_users_table -# Edit the migration... -ch-migrate up dev ``` ---- - -## Appendix B: Existing Project Integration - -### Scenario: Monorepo with Existing ClickHouse - -``` -my-monorepo/ -├── services/ -├── packages/ -└── migrations/ # <-- add here - ├── config.yaml - ├── .env.local - └── migrations/ -``` +`bootstrap` only adds to the migration role and creates the database only if it is +missing. Existing tables are left alone. Write new migrations with +`CREATE TABLE IF NOT EXISTS` and `ADD COLUMN IF NOT EXISTS`, so a migration that meets +an object that already exists still succeeds. See +[Re-runnable migrations](../README.md#re-runnable-migrations). + +### Upgrading from 0.8 + +A project without an `access.yaml` keeps 0.8's grants. `bootstrap` now names each grant +that fails and ends by checking the migration role's grants as the migration user. Any +command's error before a change now exits 2 instead of 1. Running `init` again adds an +`access.yaml`, which switches the next `bootstrap` to the `core` profile; delete the file +to keep 0.8's behavior. Details: [Upgrade from 0.x](../README.md#upgrade-from-0x). + +### Adopting access.yaml where users and roles already exist + +1. If your migrations create users or roles, or grant to other users, set + `migration_role.profile: legacy` in `access.yaml`. That keeps 0.8's grants. +2. Start each existing user or role from what the server holds: + `ch-migrate access show dev NAME > access.show.yaml` writes it in `access.yaml` form. + Copy what you keep into `access.yaml`. Never redirect into `access.yaml` itself: the + shell empties it first. +3. Review `ch-migrate access plan dev` before the first `access apply`. `apply` revokes, + from each user and role the file declares, every grant the file leaves out. Users and + roles the file doesn't declare are never touched. + +## Commands + +| Command | What it does | +|---------|--------------| +| `ch-migrate status dev` | Show which revisions are applied | +| `ch-migrate new dev [--table T \| --view V \| --dict D]` | Create a revision with its `.up.sql` and `.down.sql` | +| `ch-migrate up dev` | Apply pending migrations, waiting for the mutations and `ON CLUSTER` DDL they start | +| `ch-migrate down dev` | Roll back the last migration | +| `ch-migrate down dev -r ` | Roll back to a revision | +| `ch-migrate history dev` | Show migration history | +| `ch-migrate lint [dev]` | Lint upgrade statements; without an environment, offline | +| `ch-migrate snapshot dev` | Save the live schema as a snapshot | +| `ch-migrate diff dev` | Compare the live schema with the latest snapshot; exits 1 on drift | +| `ch-migrate access validate dev [--sql]` | Check `access.yaml` offline; `--sql` prints the SQL for a DBA to run | +| `ch-migrate access show dev [NAME...]` | Print what the server holds, in `access.yaml` form | +| `ch-migrate access plan dev` | List the changes `apply` would make; exits 0 in sync, 1 with changes pending | +| `ch-migrate access apply dev` | Make the server match `access.yaml`, as the admin | +| `ch-migrate access check dev` | Check, as the migration user, that it holds the migration role's grants | + +`bootstrap`, `access show`, `access plan` and `access apply` log in as `admin_user`. +`access check` is for servers where ch-migrate has no admin login. An error before any +change exits 2. -### 1. Initialize +## Troubleshooting ```bash -cd my-monorepo -ch-migrate init ./migrations --name my_project -``` - -### 2. Connect to Existing ClickHouse - -**migrations/config.yaml:** -```yaml -project: - name: my_project - -defaults: - port: 8443 - secure: true - admin_user: default - -environments: - dev: - host: my-dev-instance.clickhouse.cloud - database: existing_database - migration_user: migration_dev - - staging: - host: my-staging-instance.clickhouse.cloud - database: existing_database - migration_user: migration_staging - - production: - host: my-prod-instance.clickhouse.cloud - database: existing_database - migration_user: migration_prod -``` +# Can the migration user log in? +ch-migrate status dev -### 3. Create Baseline Migration +# Does the admin login work, and what would apply change? +ch-migrate access plan dev -If you have existing tables, create a baseline migration that documents the current state: +# Does the migration user hold its grants? +ch-migrate access check dev -```bash -ch-migrate new dev baseline_existing_schema -``` +# What SQL would bootstrap run? Passwords print as placeholders. +ch-migrate bootstrap dev --dry-run -Edit the migration to either: -- **Option A:** Include CREATE TABLE statements (will no-op if tables exist) -- **Option B:** Leave empty and just document existing schema - -```python -def upgrade() -> None: - # Existing tables as of 2024-01-08: - # - users (id, email, name, created_at) - # - events (id, user_id, event_type, timestamp) - # These were created manually before migrations were adopted. - pass - -def downgrade() -> None: - # Cannot downgrade - these tables existed before migrations - raise NotImplementedError("Cannot downgrade baseline migration") +# Query ClickHouse directly +curl "http://localhost:8123/?user=default&password=xxx" -d "SHOW DATABASES" ``` ---- +## Secrets -## Appendix C: Environment Configuration +Each secret comes from AWS SSM when `config.yaml` gives a path for it under the +environment's `ssm:`, and otherwise from an environment variable, which `.env.local` can +set. -### Local Development (.env.local) +| Variable | Needed for | +|----------|------------| +| `CH__MIGRATION_PASSWORD` | Every command that connects | +| `CH__ADMIN_PASSWORD` | `bootstrap`, `access show`, `access plan`, `access apply` | +| `CH__` | Each `{secret: NAME}` in `access.yaml`: `{secret: etl_password}` reads `CH_DEV_ETL_PASSWORD` | +| `CH__MCP_PASSWORD` | Only without an `access.yaml`, with `mcp_user_name` set | ```bash -# .env.local - gitignored, local secrets only +# .env.local: gitignored, local secrets only CH_DEV_ADMIN_PASSWORD=local-admin-pass CH_DEV_MIGRATION_PASSWORD=local-migration-pass -CH_DEV_MCP_PASSWORD=local-mcp-pass ``` -### Staging/Production (AWS SSM) - -**config.yaml:** ```yaml +# config.yaml: production secrets from SSM environments: production: host: prod.clickhouse.cloud @@ -253,116 +150,74 @@ environments: ssm: admin_password: /my_project/prod/admin_password migration_password: /my_project/prod/migration_password - mcp_password: /my_project/prod/mcp_password -``` - -SSM support (`boto3`) is included in the base install; AWS credentials come from your usual AWS profile or environment. - -**Set up SSM parameters:** -```bash -aws ssm put-parameter \ - --name "/my_project/prod/migration_password" \ - --value "secret" \ - --type SecureString + etl_password: /my_project/prod/etl_password # {secret: etl_password} ``` -### Priority Order - -1. SSM parameters (if `ssm:` paths configured in config.yaml) -2. Environment variables (`CH__*`) - used when no SSM paths -3. Error if required and not found +SSM support (`boto3`) is in the base install. AWS credentials come from your usual AWS +profile or environment. ---- +## A read-only user -## Appendix D: Rollback Patterns +For BI tools, dashboards and MCP servers. Declare it in `access.yaml`: -### ClickHouse DDL is Non-Transactional - -Unlike PostgreSQL, ClickHouse cannot roll back DDL. If a migration fails halfway: -- Some statements may have executed -- You'll need to manually fix or continue - -### Safe Rollback Pattern - -Always write thorough `downgrade()` functions: - -```python -def upgrade() -> None: - db = get_db() - op.execute(f""" - CREATE TABLE {db}.users ( - id UInt64, - email String, - created_at DateTime DEFAULT now() - ) ENGINE = MergeTree() ORDER BY id - """) +```yaml +roles: + readonly: + grants: + - SELECT, SHOW TABLES ON {db}.* -def downgrade() -> None: - db = get_db() - op.execute(f"DROP TABLE IF EXISTS {db}.users") +users: + mcp_reader: + password: {secret: mcp_reader_password} # CH_DEV_MCP_READER_PASSWORD + roles: [readonly] ``` -### Zero-Downtime Schema Changes - -Use `EXCHANGE TABLES` for safe migrations: - -```python -def upgrade() -> None: - db = get_db() - - # 1. Create new table with updated schema - op.execute(f""" - CREATE TABLE {db}.users_new ( - id UInt64, - email String, - phone String, -- new column - created_at DateTime DEFAULT now() - ) ENGINE = MergeTree() ORDER BY id - """) +Then run `ch-migrate access plan dev` and `ch-migrate access apply dev`. - # 2. Copy data with transformation - op.execute(f""" - INSERT INTO {db}.users_new - SELECT id, email, '' as phone, created_at - FROM {db}.users - """) +A project without an `access.yaml` can still set `mcp_user_name` in `config.yaml`, as in +0.8. `bootstrap` then creates `_readonly_role` and that user. - # 3. Atomic swap - op.execute(f"EXCHANGE TABLES {db}.users AND {db}.users_new") +## Local ClickHouse in Docker - # 4. Drop old - op.execute(f"DROP TABLE {db}.users_new") +```bash +docker run -d --name clickhouse -p 8123:8123 \ + -e CLICKHOUSE_PASSWORD=admin123 \ + -e CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1 \ + clickhouse/clickhouse-server:latest ``` ---- - -## Appendix E: Read-Only User Setup +`CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1` lets the `default` user create users and roles, +which `bootstrap` and `access apply` need. -### Enable MCP User - -**config.yaml:** ```yaml +# config.yaml +project: + name: my_project + defaults: - mcp_user_name: mcp_reader # uncomment to enable + port: 8123 + secure: false + admin_user: default environments: dev: - # ... other config + host: 127.0.0.1 + database: my_project_dev + migration_user: migration_dev ``` -**.env.local:** ```bash -CH_DEV_MCP_PASSWORD=readonly-pass +# .env.local +CH_DEV_ADMIN_PASSWORD=admin123 +CH_DEV_MIGRATION_PASSWORD=migpass123 ``` -### What Gets Created - -Bootstrap creates: -- `{project}_readonly_role` with SELECT + SHOW TABLES -- `mcp_reader` user with the readonly role +Then `ch-migrate bootstrap dev`, `ch-migrate new dev ...` and `ch-migrate up dev`. -### Use Cases +## More -- **BI Tools:** Connect Metabase/Superset with read-only access -- **MCP Servers:** Claude/AI tools can query without write access -- **Dashboards:** Grafana/monitoring with safe credentials +- [Python migrations](../README.md#python-migrations), for logic SQL files can't express +- [Exchange and dictionary patterns](../README.md#exchange-and-dictionary-patterns) +- [Irreversible migrations](../README.md#irreversible-migrations) +- [Access: users, roles and grants](../README.md#access-users-roles-and-grants) +- [Drift detection in CI](../README.md#drift-detection-in-ci) diff --git a/docs/design/2026-10-02-ch-migrate-1.0.md b/docs/design/2026-10-02-ch-migrate-1.0.md index 9e5cb67..a48a0dd 100644 --- a/docs/design/2026-10-02-ch-migrate-1.0.md +++ b/docs/design/2026-10-02-ch-migrate-1.0.md @@ -156,11 +156,11 @@ started. capability 4: every statement must be safe to repeat, or carry a written waiver. A migration noted as started but not recorded reruns on its own only if every statement passes the gate without a waiver; otherwise `up` stops and names the statements until - someone checks and passes `--rerun-interrupted REV` (Dan, 2026-10-27, DRY-1609). -- **Design change, 2026-10-27 (Dan):** the design approved on 2026-10-04 recorded which work + someone checks and passes `--rerun-interrupted REV` (2026-10-27). +- **Design change, 2026-10-27:** the design approved on 2026-10-04 recorded which work each statement started in a journal, so a rerun would never send a statement twice. It took about 1,300 lines, duplicated what capability 4 already guarantees, and left a killed or - rejected mutation unrecoverable without editing the journal by hand (DRY-1604). 0.7 waits by + rejected mutation unrecoverable without editing the journal by hand. 0.7 waits by observation instead; the [waiting design](2026-10-02-waiting.md) keeps the journal design and its experiments for the record. - A failing mutation does not end on its own: ClickHouse retries it and holds back every later @@ -321,8 +321,8 @@ is unaffected; Python 3.9 is not supported, so 0.6 requires 3.10. **A design note on waiting, before the 0.7 plan.** Answered in the [waiting design](2026-10-02-waiting.md). Accepted-but-unacknowledged mutation recovery -is demonstrated. Dan approved explicit failure and operator reconciliation when -missing or expired evidence prevents establishing the outcome, on 2026-10-04. +is demonstrated. Explicit failure and operator reconciliation, when missing or +expired evidence prevents establishing the outcome, were approved on 2026-10-04. 5. On a re-run, how does `up` recognise a mutation it started earlier, without mistaking someone else's mutation for its own? diff --git a/docs/design/2026-10-02-dialect-spike.md b/docs/design/2026-10-02-dialect-spike.md index f6c9dd3..740019b 100644 --- a/docs/design/2026-10-02-dialect-spike.md +++ b/docs/design/2026-10-02-dialect-spike.md @@ -1,6 +1,6 @@ # Spike: the official clickhouse-connect dialect (open questions 1–4) -**Date:** 2026-10-02 · **For:** capability 3 of `2026-10-02-ch-migrate-1.0.md` · **Ticket:** DRY-1391 +**Date:** 2026-10-02 · **For:** capability 3 of `2026-10-02-ch-migrate-1.0.md` **Setup:** ClickHouse 26.3.32.14 in throwaway local containers (one with Keeper). Legacy runs used our real `env.py`. Scripts, migrations and logs are in `spikes/2026-10-02-dialect/`. @@ -15,10 +15,9 @@ our real `env.py`. Scripts, migrations and logs are in `spikes/2026-10-02-dialec was also verified to keep a `SET` in effect. - **Independent of the dialect, today's version table can re-run a migration** (Q2). This must be fixed in 0.6. -- **Decision (Dan, 2026-10-02):** 0.6 adopts the official dialect and requires Python 3.10 or +- **Decision (2026-10-02):** 0.6 adopts the official dialect and requires Python 3.10 or later. This replaces the product definition's original rule, which made 3.9 a hard requirement - and would have forced the fallback. 0.5.x is the last line for 3.9. Implementation: DRY-1392 - (dialect) and DRY-1412 (version table). + and would have forced the fallback. 0.5.x is the last line for 3.9. ## Q1. Does a `SET` carry over to the next statement? @@ -187,7 +186,7 @@ directly (`bootstrap.py:329-363`) and never imports SQLAlchemy. - `session_timeout` passed through clickhouse-sqlalchemy's `ch_settings`. - Both claims marked *Not tested* in Q2. -## Clean-environment reproduction (DRY-1391 validation) +## Clean-environment reproduction Re-run on 2026-10-02 from the local `dy/ch-migrate-1.0` branch. This validates Q1 and Q4 without switching the package's production dialect. The probe copies diff --git a/docs/design/2026-10-02-rebuild-spike.md b/docs/design/2026-10-02-rebuild-spike.md index b835050..107d793 100644 --- a/docs/design/2026-10-02-rebuild-spike.md +++ b/docs/design/2026-10-02-rebuild-spike.md @@ -1,6 +1,6 @@ # Spike: rebuild_table mechanics (open questions 10–11) -**Date:** 2026-10-02 · **For:** capability 8 of `2026-10-02-ch-migrate-1.0.md` · **Ticket:** DRY-1406 +**Date:** 2026-10-02 · **For:** capability 8 of `2026-10-02-ch-migrate-1.0.md` **Setup:** ClickHouse 26.3.32.14 in a throwaway local container, with embedded Keeper for replicated runs. Every experiment's SQL and output is in `spikes/2026-10-02-rebuild/`. Files are named after the sections below: `a_*`, `b*_*`, `d*_*`, `f*_*`, and `e2e.py` with `run_e2e*.sh`. @@ -21,10 +21,10 @@ Four things change from the planned mechanism: **Materialized views follow the table name across `EXCHANGE`,** so dependent views need no re-pointing. -**Decision (Dan, 2026-10-02):** all four are adopted. The guarantee is now "no acknowledged row is +**Decision (2026-10-02):** all four are adopted. The guarantee is now "no acknowledged row is lost". Fire-and-forget async writers need an opt-in written in the migration file. Partition-key changes are refused in 1.0. Cloud is verified on a DRY-owned Cloud service at each acceptance -check (DRY-1413). Implementation: DRY-1407. +check. ## End-to-end runs diff --git a/docs/design/2026-10-02-waiting.md b/docs/design/2026-10-02-waiting.md index a3e2da6..2919054 100644 --- a/docs/design/2026-10-02-waiting.md +++ b/docs/design/2026-10-02-waiting.md @@ -1,6 +1,6 @@ # Waiting for mutations and distributed DDL -**Superseded for 0.7 (Dan, 2026-10-27).** 0.7 doesn't ship the journal design below. It +**Superseded for 0.7 (2026-10-27).** 0.7 doesn't ship the journal design below. It waits by observation: after each write, `up` polls `system.mutations` until the project database has none unfinished, and ClickHouse waits for `ON CLUSTER` DDL itself. A rerun waits for unfinished work, then runs the migration again, relying on the idempotency gate. @@ -8,7 +8,7 @@ Capability 5 in the [product definition](2026-10-02-ch-migrate-1.0.md) and the R "Migrations that wait" describe what ships. The rest of this note is the record of the journal design and its experiments. -**DRY-1398 · 2026-10-02 · Recovery policy approved by Dan on 2026-10-04.** +**2026-10-02 · Recovery policy approved on 2026-10-04.** A write-ahead intent plus a marker carried into ClickHouse's mutation record can recover an accepted `UPDATE` after the client dies without reading its response. @@ -24,14 +24,15 @@ can omit it. No command-normalization or time-window heuristic fixes that. **Approved recovery rule:** when an interrupted statement's outcome cannot be proven, exit nonzero, do not reissue it, do not mark the migration complete, and require operator reconciliation. Known unfinished work still reattaches -automatically. Dan approved this exception to -[capabilities 4 and 5](2026-10-02-ch-migrate-1.0.md) and explicitly resumed -local-only implementation on 2026-10-04. +automatically. This exception to +[capabilities 4 and 5](2026-10-02-ch-migrate-1.0.md) was approved, and local-only +implementation explicitly resumed, on 2026-10-04. Approval revalidation on 2026-10-04: all 16 local experiments passed; the separate three-trial kill/re-run pass passed. The local CI gate passed 641 tests on each of Python 3.10, 3.11, 3.12, 3.13 and 3.14. The implementation rows below remain the -acceptance contract for DRY-1399/1400, not claims that those features already exist. +acceptance contract for mutation and `ON CLUSTER` waiting, not claims that those +features already exist. ## Reproduce the evidence @@ -309,7 +310,7 @@ Rules: ## Q9. Cloud: reasoned, not tested -DRY-1413 has no `service ready` comment. No Cloud connection or credential lookup +No Cloud service was ready. No Cloud connection or credential lookup was made for this note. These conclusions come from official documentation, not the local replicated harness: @@ -366,7 +367,8 @@ settings that change materialization, including `materialize_ttl_after_modify`. ### Hook at the actual cursor boundary Use SQLAlchemy `before_cursor_execute` with `retval=True` and -`after_cursor_execute` on the migration connection, as established by DRY-1391. +`after_cursor_execute` on the migration connection, as established by the +[dialect spike](2026-10-02-dialect-spike.md). This covers `op.execute`, `op.get_bind()` and `run_sql`'s `exec_driver_sql` path. Do not use only `ChMigrateImpl._exec`. Guard journal, polling and progress queries against recursive instrumentation. Offline SQL generation does not connect or @@ -374,7 +376,7 @@ invent journal receipts. Poll on the same migration session, using bounded requests and an interval less than its idle timeout. This both preserves session `SET`s and keeps the session -alive. Propagate DRY-1392's expired-session failure; never silently recreate it. +alive. Propagate the dialect's expired-session failure; never silently recreate it. A separate monitoring client alone does not keep the migration session alive. Online `up` invokes Alembic in the CLI process, so SIGKILL cannot leave a child @@ -410,7 +412,7 @@ state into queued, unacknowledged data. ### The version table's delete -DRY-1412 inserts the new head before deleting the previous one. Its delete is a +The version table inserts the new head before deleting the previous one. Its delete is a real mutation and currently uses the official implementation's synchronous wait. The waiting implementation must put that delete through the same asynchronous polling/error surface, without weakening the insert-first safety invariant. @@ -446,31 +448,31 @@ These are required implementation checks, **not claimed implementation results** Unknown-outcome rows use the recovery rule approved on 2026-10-04. The experiment names make the subset already demonstrated reproducible. -| Row | Owner | Required observable result | +| Row | Area | Required observable result | |---|---|---| -| W01 | DRY-1399 | Every mutation-producing corpus statement waits; schema mutations and TTL are not missed; lightweight UPDATE is not falsely identified as a background mutation. | -| W02 | DRY-1399 | `throwIf` failure exits nonzero with reason, table, ID and operator KILL; no automatic KILL; pre-revision head unchanged. | -| W03 | DRY-1399 | SIGKILL while waiting; rerun attaches to the same ID and increments once. Run three independent trials. | -| W04 | DRY-1399 | Kill after accepted send but before reading receipt; recovery uses pre-send intent and marker; no second command. | -| W05 | DRY-1399 | Timeout reports outstanding IDs, parts and hosts; work remains on the server; rerun finishes without replay. | -| W06 | DRY-1399 | A paused second replica prevents success even after the first finishes; returning replica permits completion. | -| W07 | DRY-1399 | Missing required host/record is not success, including a query using skip-unavailable behavior. | -| W08 | DRY-1399 | Healthy foreign predecessor is reported and waited; failed predecessor is named; trailing foreign work is not adopted as ours. | -| W09 | DRY-1399 | Same SQL from another writer is not owned; table recreation and changed migration digest refuse before replay. | -| W10 | DRY-1399 | Expired/missing ownership evidence exits nonzero with diagnostics and operator-reconciliation guidance; never silently completes or resubmits the statement. | -| W11 | DRY-1399 | Polls longer than a short session timeout preserve a prior SET; an actually expired session fails loudly. | -| W12 | DRY-1399 | Python op.execute, op.get_bind().execute/exec_driver_sql and run_sql all use the hook; polling does not recurse. | -| W13 | DRY-1399 | Interrupted/failed version DELETE uses the same diagnostics, preserves insert-first safety, and never re-executes an applied revision. | -| W14 | DRY-1399 | TTY and CI progress identify real state; timeout budget is not reset per mutation; zero parts alone does not mean done. | -| W15 | DRY-1399 | Completed earlier statements are not repeated on resume; downgrade then upgrade does not reuse an old completed journal. | -| W16 | DRY-1400 | CREATE then ALTER ON CLUSTER finishes on all hosts before success and before version completion. | -| W17 | DRY-1400 | Stopped node remains pending; timeout names it; restart and rerun attach to the same queue entry. | -| W18 | DRY-1400 | One-host schema conflict exits nonzero with host/code/text even when queue status is Finished. | -| W19 | DRY-1400 | Accepted DDL with lost client receipt is found by journaled log_comment, not exact normalized query text. | -| W20 | DRY-1400 | Mutation-producing ON CLUSTER ALTER satisfies both the DDL and mutation barriers. | -| W21 | DRY-1400 | Missing/expired queue entry is not success or automatic resubmission; uses the agreed unknown-outcome rule. | -| W22 | DRY-1400 | Single-node/no-ON-CLUSTER statements do not query a fictitious distributed DDL queue. | -| W23 | DRY-1401 | Authorized Cloud acceptance proves SharedMergeTree mutation visibility, markers, journal persistence and same-session polling; no self-hosted replica assumptions. | +| W01 | Mutations | Every mutation-producing corpus statement waits; schema mutations and TTL are not missed; lightweight UPDATE is not falsely identified as a background mutation. | +| W02 | Mutations | `throwIf` failure exits nonzero with reason, table, ID and operator KILL; no automatic KILL; pre-revision head unchanged. | +| W03 | Mutations | SIGKILL while waiting; rerun attaches to the same ID and increments once. Run three independent trials. | +| W04 | Mutations | Kill after accepted send but before reading receipt; recovery uses pre-send intent and marker; no second command. | +| W05 | Mutations | Timeout reports outstanding IDs, parts and hosts; work remains on the server; rerun finishes without replay. | +| W06 | Mutations | A paused second replica prevents success even after the first finishes; returning replica permits completion. | +| W07 | Mutations | Missing required host/record is not success, including a query using skip-unavailable behavior. | +| W08 | Mutations | Healthy foreign predecessor is reported and waited; failed predecessor is named; trailing foreign work is not adopted as ours. | +| W09 | Mutations | Same SQL from another writer is not owned; table recreation and changed migration digest refuse before replay. | +| W10 | Mutations | Expired/missing ownership evidence exits nonzero with diagnostics and operator-reconciliation guidance; never silently completes or resubmits the statement. | +| W11 | Mutations | Polls longer than a short session timeout preserve a prior SET; an actually expired session fails loudly. | +| W12 | Mutations | Python op.execute, op.get_bind().execute/exec_driver_sql and run_sql all use the hook; polling does not recurse. | +| W13 | Mutations | Interrupted/failed version DELETE uses the same diagnostics, preserves insert-first safety, and never re-executes an applied revision. | +| W14 | Mutations | TTY and CI progress identify real state; timeout budget is not reset per mutation; zero parts alone does not mean done. | +| W15 | Mutations | Completed earlier statements are not repeated on resume; downgrade then upgrade does not reuse an old completed journal. | +| W16 | `ON CLUSTER` | CREATE then ALTER ON CLUSTER finishes on all hosts before success and before version completion. | +| W17 | `ON CLUSTER` | Stopped node remains pending; timeout names it; restart and rerun attach to the same queue entry. | +| W18 | `ON CLUSTER` | One-host schema conflict exits nonzero with host/code/text even when queue status is Finished. | +| W19 | `ON CLUSTER` | Accepted DDL with lost client receipt is found by journaled log_comment, not exact normalized query text. | +| W20 | `ON CLUSTER` | Mutation-producing ON CLUSTER ALTER satisfies both the DDL and mutation barriers. | +| W21 | `ON CLUSTER` | Missing/expired queue entry is not success or automatic resubmission; uses the agreed unknown-outcome rule. | +| W22 | `ON CLUSTER` | Single-node/no-ON-CLUSTER statements do not query a fictitious distributed DDL queue. | +| W23 | Cloud | Authorized Cloud acceptance proves SharedMergeTree mutation visibility, markers, journal persistence and same-session polling; no self-hosted replica assumptions. | ## Sources and limits diff --git a/docs/design/2026-11-11-access-spike.md b/docs/design/2026-11-11-access-spike.md new file mode 100644 index 0000000..2aa935c --- /dev/null +++ b/docs/design/2026-11-11-access-spike.md @@ -0,0 +1,507 @@ +# Spike: how ClickHouse stores and checks grants (U1–U10) + +**Date:** 2026-11-11 · **For:** Part 3 of `2026-11-11-declarative-access.md` (the design note) +**Setup:** Docker only. The `26.3`, `25.8` and `24.8` image tags floated to 26.3.62.3, 25.8.33.6 +and 24.8.14.39. Cluster answers use the two-node fixture in `tests/integration/conftest.py`, +once with users and roles on each node's disk (`clickhouse_cluster`) and once with them in +Keeper (`clickhouse_cluster_keeper`). + +Every answer below names the test in `tests/integration/test_access_spike.py` that keeps +asserting it. `tests/integration/grant_rights.py` holds the comparison those tests use. It is +test code; section "The comparison" describes it for T4 to rebuild in the product. + +## Summary + +- **Narrowing a grant's scope can't follow "grant before revoke" (U1).** Take a role that holds + `SELECT ON db.*` while the YAML asks for `SELECT ON db.events`. Granting `db.events` first + writes nothing, because `db.*` absorbs it, and revoking `db.*` then removes both. Two orders + converge: + - revoke, then grant, with a moment of no access in between; + - one `GRANT TO x WITH REPLACE OPTION`, which is atomic and keeps + role memberships. It works only if the admin holds every right the grantee has now, + with grant option. If it doesn't, the statement fails and nothing changes. + + This bore on Decision 3 ("It grants before it revokes") and on 2.5's apply order. It + was decided that `apply` narrows a scope with one `WITH REPLACE OPTION` of the whole + declared set. + If the admin lacks a right the grantee holds, nothing changes and `apply` says why, and it + is never used on the migration role (2026-11-11; Decision 3). Change 5 records it. +- **A read-only comparison works (U1).** Expanding both sides to one right per privilege + flag, scope and grant option, using the server's own `system.privileges`, reproduces what + `system.grants` holds. It held for every privilege on `*.*`, `db.*` and `db.t` on 26.3, + and for both profiles on all three images. There is one exception: on 25.8 and 26.3, + ` ON *.*` is stored as `READ, WRITE ON `. +- **No other answer bears on a Part 1 decision.** Five answers confirm Part 2 as written: U2, + U3, U4, U6 and U10. U1, U5, U7, U8 and U9 add the named changes listed under "Changes to + the design note". +- **An `ON CLUSTER` error can lose its code (U9).** Without the setting + `wait_end_of_query=1`, a host that fails after another host has answered reaches the client + as a broken HTTP response with no error code. `up` already sends the setting; T5's `apply` + must too (change 6). +- **On a self-hosted cluster, `up` needs four of the best-effort grants (U7):** `CLUSTER`, + `READ ON REMOTE`, `SYSTEM SYNC REPLICA` and `SELECT ON system.replicas`. A single node needs + none of them. The design note already defers "cluster grants that become required only when + a cluster applies" (2.9); this names them. +- **24.8 lacks `CHECK GRANT` and `READ ON ` (U5, U8).** 0.8's own `bootstrap` stops + there at `READ ON REMOTE`, before it creates any user. The live `access` commands need + 25.8 or later, and exit 2 on an older server (2026-11-11; Decision 11). + +## The comparison + +T4's live reader and planner should do this. + +1. **Read the tree.** `SELECT privilege, aliases, level, parent_group FROM system.privileges` on + the server being compared. Don't ship a list for `plan`: the three images have different + privileges and levels (U8). `validate`, which has no server, checks names against a + bundled list taken from 26.3's `system.privileges`, and an unknown name is a warning + (2026-11-11). +2. **Flags.** A privilege whose `level` is not NULL carries a flag of its own. A privilege + with a NULL level is a group, with no flag of its own. A privilege means its own flag plus + the flags of all its descendants, through `parent_group`. Some privileges are both: for + example, `CREATE ARBITRARY TEMPORARY TABLE` has a level and a child. +3. **Scope filter.** Keep only the flags that the target's scope allows: + - `*.*`: every level. + - `db.*`: `DATABASE`, `TABLE`, `DICTIONARY`, `VIEW`, `COLUMN`. + - `db.table`: `TABLE`, `DICTIONARY`, `VIEW`, `COLUMN`. + - a source (`READ ON REMOTE`): `SOURCE`. + + So `CREATE ON db.*` means `CREATE DATABASE`, `CREATE TABLE`, `CREATE VIEW` and + `CREATE DICTIONARY`. `ALTER ON db.table` drops `ALTER DATABASE`. The server stores exactly + those rows, and it rejects a grant whose filtered set is empty (`INVALID_GRANT` or + `SYNTAX_ERROR`). +4. **Rights.** A right is `(flag, scope, grant option)`. A scope is the database, the table, + the column and `access_object` from `system.grants`. NULL means "every", and + `access_object` holds the source for `READ` and `WRITE`. A column scope is narrower than + its table, so a live `SELECT(id) ON db.events` doesn't satisfy a desired table grant, and + granting the table grant absorbs it. v1 declares no column grants. + - Desired rights come from each grant in `access.yaml` and the profile. + - Live rights come from each `system.grants` row of the user or role. + - A row with `is_partial_revoke = 1` is a revoke. With `grant_option = 1` it revokes only + the grant option. +5. **Compare by coverage, both ways.** Right A covers right B when they have the same flag, A's + scope contains B's, and A has grant option whenever B does. + - **Missing:** desired rights no live right covers. + - **Extra:** live rights no desired right covers. + - **Partial revokes:** every revoke row. A desired set never has one, so any revoke row + on a declared user or role is drift. + + Coverage makes folding cancel out: + - `SELECT ON system.tables` is covered by `SELECT ON system.*`, which holds no row for it; + - `SELECT` is covered by `SELECT ... WITH GRANT OPTION`; + - `DELETE`, stored as `ALTER DELETE`, is covered by `ALTER`. +6. **Aliases.** Look a name up among both `privilege` and `aliases`, ignoring case and extra + spaces. `DELETE` becomes `ALTER DELETE`, and `SYNC REPLICA` becomes `SYSTEM SYNC REPLICA`. +7. **Old source spellings.** On servers that have a `SOURCE`-level `READ` (25.8 and 26.3), + `REMOTE ON *.*`, `S3 ON *.*` and the other sources are stored as `READ` and `WRITE` on that + source, and `SOURCES ON *.*` as `READ` and `WRITE` on every source. The tree can't say which + privileges are sources, so a desired `REMOTE ON *.*` can't be expanded to match. + `validate` rejects that spelling, and its error names the new one, `READ, WRITE ON REMOTE` + (2026-11-11; change 1). On those + servers the reader never meets the old spelling, because the server has already + rewritten it. On 24.8, `REMOTE` is an ordinary global privilege and expands like + any other. +8. **Changes.** + - Grant each missing right. + - Revoke each extra flag on its own scope. `REVOKE` accepts a list of flags, and the server + stores what is left of a group as its children. Never revoke a group that the desired + set only partly drops. + - An extra that differs from a desired right only by grant option takes + `REVOKE GRANT OPTION FOR`. + - Re-grant a declared grant to clear a partial revoke (U2). + - **Narrowing a scope** (`db.*` to `db.events`) can't grant first: see the summary. + `apply` replaces the whole declared set with `WITH REPLACE OPTION` (2026-11-11). + +**How 0.8's statements map to stored rows.** This covers the legacy profile and T1's fixture. +`test_u1_profiles_match_one_grant_at_a_time_and_together` replays each statement of 0.8's +`build_bootstrap_sql`, one at a time and then all together, and step 5 finds no difference. +- `DELETE ON {db}.*` leaves no row. It is `ALTER DELETE`, which `ALTER` covers. +- `ACCESS MANAGEMENT ON {db}.*` leaves no row of its own. On a database it means the four + row-policy flags, which 0.8 also grants by name. They are stored once. +- `SELECT ON system.grants`, `.databases`, `.tables` and `.mutations`, and the best-effort + `.replicas` and `.parts`, leave no rows. `SELECT ON system.* WITH GRANT OPTION` covers + them. +- `CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*)` and the other `*.*` grants + leave one row per privilege. +- `CURRENT GRANTS(READ ON REMOTE)` leaves `READ` with `access_object = 'REMOTE'`. `SHOW GRANTS` + prints it as `GRANT REMOTE ON *.*`. + +## U1. Read-only comparison + +**Answer: yes.** The comparison above reproduces `system.grants` after every grant tried: +- folded privileges; +- a parent stored as its children; +- a narrower grant absorbed by a broader one; +- grant option absorbing the plain grant; +- aliases. + +**Narrowing a scope** is the exception to "grant before revoke"; the summary has the details. +Both converging orders are under test, and so is the admin limit on `WITH REPLACE OPTION`. +`apply` uses `WITH REPLACE OPTION` (2026-11-11). +`WITH REPLACE OPTION` and several ` ON ` clauses in one `GRANT` also +worked by hand on 24.8 and 25.8. + +On 26.3 it held for all 427 accepted grants of every privilege on `*.*`, `db.*` and `db.t`, +apart from the 18 old source spellings in step 7. Each rejected grant either expands to +nothing, or asks for rights that the admin's own rows don't cover with grant option. The +default admin can't pass on the named-collection privileges. Narrowing `ALTER` to +`ALTER UPDATE` works by revoking the other `ALTER` leaves. Granting `ALTER UPDATE` and then +revoking `ALTER` leaves nothing. + +`SHOW GRANTS` text is not a reliable record. `READ ON REMOTE` reads back as +`GRANT REMOTE ON *.*`, and `READ ON *.*` as `GRANT SOURCES ON *.*`. + +**Tests:** +- `test_u1_every_privilege_on_every_target`; +- `test_u1_profiles_match_one_grant_at_a_time_and_together`; +- `test_u1_folded_grants_still_match`, eight cases; +- `test_u1_show_grants_text_differs_from_what_is_stored`; +- `test_u1_narrowing_revokes_only_the_difference`; +- `test_u1_grant_option_is_part_of_each_right`; +- `test_u1_narrowing_a_scope_cannot_grant_first`; +- `test_u1_replace_needs_every_current_right_with_grant_option`; +- `test_u1_column_grant_is_narrower_than_a_table_grant`. + +A hand-run of the same sweep on the other images found: +- **25.8:** the same 18 exceptions as 26.3. +- **24.8:** no stored-row exceptions. Nine privileges were syntax errors on `*.*` although + they expand to something: the five named-collection ones, `SHOW NAMED COLLECTIONS SECRETS`, + `SHOW NAMED COLLECTIONS`, `SET DEFINER` and `TABLE ENGINE`. 24.8 takes their targets in + another form, and v1 grants none of them. + +On those images only the profiles are under test, in +`test_u8_leaf_expansion_matches_both_profiles_on_this_image`. + +**Means for T4 and T5:** confirms 2.7's first candidate, leaf expansion. The scratch-role and +`CHECK GRANT` candidates are not needed. Changes 1, 2 and 5 below. + +## U2. Partial revokes + +**Answer:** +- `REVOKE` on a narrower scope than a grant writes a row with `is_partial_revoke = 1`. For + example, `SELECT ON db.*` minus `db.events`. +- `REVOKE GRANT OPTION FOR` writes a row with `is_partial_revoke = 1` and `grant_option = 1`. +- Revoking a child on the same scope writes no revoke row. The server stores the group as + its remaining children instead, for example `ALTER` minus `ALTER DELETE`. +- Granting the broader grant again removes the revoke row. + +**Tests:** +- `test_u2_partial_revoke_is_a_row_and_granting_again_clears_it`; +- `test_u2_revoking_a_child_at_the_same_scope_leaves_no_partial_revoke`; +- `test_u2_revoking_only_the_grant_option_is_a_partial_revoke_row`. + +**Means for T4 and T5:** confirms Part 2. `plan` reports a revoke row on a declared user or role +as drift, a `+` line that re-grants the declared grant. `apply` fixes it by granting again. + +## U3. Objects that don't exist yet + +**Answer: ClickHouse accepts and stores grants on databases and tables that don't exist.** +- A user holding `CREATE TABLE, SELECT, INSERT` on a database that doesn't exist yet can use + it once someone creates the database. +- Dropping the database leaves the grant rows in place. +- `CHECK GRANT` answers 1 for a granted object that doesn't exist (U5). + +**Test:** `test_u3_grants_on_missing_objects_are_kept_and_work_later`. + +**Means for T5 and T6:** confirms Part 2. `access apply` can run before `up`, and on 25.8 and +later `check` works on a fresh database. + +## U4. Passwords + +**Answer: nothing the admin reads by default shows a password or its hash,** for the default +method, `sha256_password`, `double_sha1_password` and `bcrypt_password`. The test creates each +user with a literal password, as `bootstrap` does, and checks: +- `SHOW CREATE USER`, which prints only the method, even with + `format_display_secrets_in_show_and_select = 1`. The server setting that would allow it, + `display_secrets_in_show_and_select`, is 0 in the image. +- `SHOW ACCESS`; +- every column of `system.users`, where `auth_params` is `{}`; +- `system.query_log`, which drops the `BY '...'` clause from the logged query. + +None of them holds the password, its SHA-256 or double SHA-1 in hex, or a bcrypt hash. + +**Test:** `test_u4_nothing_the_admin_reads_shows_a_password_or_hash`, four methods. + +**Means for T4 and T5:** confirms 2.5. `plan` never compares passwords. Passwords are set at +creation, or with `--reset-passwords`. + +## U5. `CHECK GRANT` + +**Answer:** + +| Image | `CHECK GRANT` | A partly held group | An object that doesn't exist | `WITH GRANT OPTION` | +| --- | --- | --- | --- | --- | +| 24.8 | `SYNTAX_ERROR`; it parses as `CHECK TABLE` | — | — | — | +| 25.8 | 1 or 0 | 0, for `ALTER` with only `ALTER UPDATE` held | 1 when granted | `SYNTAX_ERROR` | +| 26.3 | 1 or 0 | 0 | 1 when granted | `SYNTAX_ERROR` | + +On 24.8 the migration user can still read its own grants and its roles' grants with +`SHOW GRANTS` and `SHOW GRANTS FOR `. It can't read `system.grants`. + +**Test:** `test_u5_check_grant_on_this_image`. It runs on all three images and asserts the +24.8 error instead of skipping. + +**Means for T6:** confirms 2.5 on 25.8 and later: `check` runs one `CHECK GRANT` per required +grant, as written, so a partly held group counts as missing. Core has no grant option, so +`CHECK GRANT`'s blindness to it doesn't matter. On 24.8, `check` exits 2 and names the +version, like every live `access` command (2026-11-11; change 3). + +## U6. The smallest admin + +**Answer:** on single-node Docker, a core-only bootstrap needs exactly these admin grants: +- `CREATE DATABASE ON {db}.*`; +- `CREATE ROLE ON *.*`; +- `CREATE USER ON *.*`; +- `ROLE ADMIN ON *.*`; +- core's required grants `WITH GRANT OPTION`, except the three `SHOW` grants. + +Notes on that set: +- **No `SHOW` grants.** ClickHouse implies `SHOW TABLES`, `SHOW COLUMNS` and `SHOW DICTIONARIES`, + with grant option, from the admin's other rights on the database. +- **`ROLE ADMIN` is needed,** although it is broad. Creating a role doesn't give its creator the + admin option, so without `ROLE ADMIN` the admin can't grant the new role to the migration user. + It also lets the admin grant any role to anyone. T7's docs say so (2026-11-11). +- **`CREATE DATABASE` is needed even when the database exists.** `CREATE DATABASE IF NOT EXISTS` + checks the grant before it checks whether the database exists. + +That admin lands every required grant and no best-effort grant. A `CURRENT GRANTS` that lands +nothing raises no error. T1's limited admin can give every core grant except three +best-effort ones: `CLUSTER`, `READ ON REMOTE` and `CREATE TEMPORARY TABLE ON *.*`. + +**Tests:** +- `test_u6_smallest_admin_runs_a_core_bootstrap`; +- `test_u6_each_smallest_admin_grant_is_needed`: 11 cases, each leaving one grant out; +- `test_u6_create_database_if_not_exists_needs_the_grant_when_it_exists`; +- `test_u6_the_t1_limited_admin_cannot_give_three_best_effort_grants`. + +The core bootstrap is written out by hand in the test, because there is no product code for +it yet. + +**Means for T6:** confirms 2.4's split between required and best-effort. T6's limited-admin +tests can use this smaller set. T1's `LIMITED_ADMIN_GRANTS` stays as it is, because it pins +0.8's behavior. A `CURRENT GRANTS` that lands nothing must be detected by reading back, since +the server gives no signal (Decision 6). + +## U7. What ch-migrate needs + +**Answer on a single node:** a migration user holding only core's required grants runs: +- `new`; +- `up`, with a migration that creates a table, view and dictionary, inserts, adds a column, + waits on an `ALTER UPDATE`, deletes and optimizes; +- `status`, `history`, `lint`, `snapshot`, `diff` and `new --table`; +- `down`, which truncates and drops. + +`rebase` and `deps` weren't run. + +Without two of the required grants a path fails: +- `SELECT ON system.mutations`: `up` fails with `ACCESS_DENIED`. +- `SELECT ON system.dictionaries`: `snapshot` fails with `ACCESS_DENIED`. + +`SELECT ON system.databases` and `system.tables` are granted implicitly on self-hosted servers, +so `up` and `down` run without them. + +**Answer on the local-storage cluster, with `cluster` set:** beyond core required, `up` needs: +- `CLUSTER`, for `ON CLUSTER` DDL; +- `READ ON REMOTE`, for the `clusterAllReplicas` preflight; +- `SYSTEM SYNC REPLICA`, for the lightweight sync of ch-migrate's replicated tables; +- `SELECT ON system.replicas`, while a mutation on a replicated table is pending. + +Without each one, `up` fails with `ACCESS_DENIED` naming it. Without `SELECT ON system.parts`, +the waiter still waits. Without `CREATE TEMPORARY TABLE`, `up` and `down` run. The fixture's +database is Atomic, so `SYSTEM SYNC DATABASE REPLICA`, which only a Replicated database uses, +was not exercised. + +**Tests:** +- `test_u7_core_required_alone_runs_these_paths`; +- `test_u7_these_system_grants_are_needed`; +- `test_u7_system_databases_and_tables_are_readable_without_a_grant`; +- `test_u7_cluster_up_needs_these_best_effort_grants`; +- `test_u7_cluster_up_runs_without_create_temporary_table`; +- `test_u7_cluster_waiting_on_a_held_mutation`. + +The cluster answer depends on the fixture's `remote_servers`, which names a fixed `default` +login for each replica. The spike didn't try other cluster credentials. + +**Means for T6:** +- On a single node, U7 confirms 2.4. Keep `system.databases` and `system.tables` required: + Cloud may not grant them implicitly, and T8 checks that. +- On a self-hosted cluster, it is change 4 below. The four grants stay best-effort, and + `check` only warns when one is missing (2026-11-11). + +## U8. `system.privileges` + +**Answer:** all three images have `system.privileges` with the same four columns: `privilege`, +`aliases`, `level` and `parent_group`. Its contents differ: + +| | 24.8.14.39 | 25.8.33.6 | 26.3.62.3 | +| --- | --- | --- | --- | +| Privileges | 189 | 211 | 230 | +| `SOURCE` and `DEFINER` levels, `READ` and `WRITE` | no | yes | yes | +| `REMOTE` and the other sources | under the `SOURCES` group | under `ALL` | under `ALL` | +| `CREATE USER` level | `GLOBAL` | `USER_NAME` | `USER_NAME` | +| `system.grants.access_object` | no | yes | yes | +| `GRANT READ ON REMOTE` | `SYNTAX_ERROR` | stored as `READ` / `REMOTE` | the same | +| 0.8 `bootstrap` | exits 1 at `READ ON REMOTE`, no user created | exits 0 | exits 0 | + +The counts are what the floating tags held on 2026-11-11. The tests don't assert them. + +**Tests:** +- `test_u8_system_privileges_shape_on_this_image`; +- `test_u8_leaf_expansion_matches_both_profiles_on_this_image`: both profiles compare clean on + each image, without `READ ON REMOTE` on 24.8; +- `test_u8_legacy_bootstrap_on_this_image`. + +**Means for T3, T4 and T6:** +- The planner reads the tree from the server (step 1 above), and the reader tolerates a missing + `access_object` column. +- The live `access` commands need 25.8 or later, and exit 2 on 24.8 (2026-11-11). + Legacy mode's `READ ON REMOTE` is best-effort under 2.4's rules. Whether `bootstrap` warns + about it on 24.8 or refuses that server is open question 7. +- `access validate` runs with no server, so it can't read the tree. It checks names against a + bundled list taken from 26.3's `system.privileges`, and an unknown name is a warning + (2026-11-11). + +## U9. Where users and roles are stored + +**Answer:** +- **ch-migrate can tell from the server alone.** `system.user_directories` lists the storages + by `precedence`. `users_xml` is read-only, so `CREATE` writes to the first other one: + - `local_directory` with the image's default config; + - `replicated` when `user_directories` names Keeper. + + `system.roles.storage` and `system.users.storage` give the same answer for one entity. +- **Local storage:** a `CREATE ROLE` or a `GRANT` without `ON CLUSTER` reaches only the node + that ran it. With `ON CLUSTER`, both reach both nodes. +- **Replicated storage:** a `CREATE ROLE` on node 1 reaches node 2 without `ON CLUSTER`, and so + does a `GRANT` (U10). With `ON CLUSTER`, the create fails with `ACCESS_ENTITY_ALREADY_EXISTS`, + because the second node finds the role the first already wrote. + +**An `ON CLUSTER` error can arrive without its code.** An earlier version of +`test_u9_replicated_storage_is_detected_and_reaches_every_node` failed once in three runs of +the cluster suite. The create's error reached the client as a broken HTTP response (urllib3 +`IncompleteRead`), so the test's check for "already exists" found no server error. The cause: +- An `ON CLUSTER` statement returns one status row per host, as each host finishes. + clickhouse-connect's `command` doesn't ask for `wait_end_of_query`, so the server streams + those rows. +- If a host's error comes before the server has sent anything, the response is an HTTP 500 + with `X-ClickHouse-Exception-Code`. +- If the server has already sent HTTP 200 and the first rows, it can't change the status. It + appends the error in an `__exception__` block, marked with the `X-ClickHouse-Exception-Tag` + header's value, and closes the connection without ending the chunked body. `command` reads + the whole body, so clickhouse-connect raises `OperationalError` with no code. +- `OperationalError` is a `DatabaseError`. So `pytest.raises(DatabaseError)` passed, and only + the message check failed. +- With `wait_end_of_query=1` the server buffers the response, and the error is always an HTTP + 500 with its code. + +By hand on 26.3, with clickhouse-connect 1.10.0, 40 creates of a role that already existed: +- without the setting, 39 answered HTTP 500 with code 493 and 1 broke as above; +- with it, all 40 answered HTTP 500 with code 493. + +The test now sends the setting and asserts code 493, `ACCESS_ENTITY_ALREADY_EXISTS`. A second +test forces the race: node 2 starts three seconds late, so node 1's row is always sent +first. By hand, that broke 26 of 26 creates without the setting and none of 14 with it. + +**Tests:** +- `test_u9_local_storage_is_detected_and_needs_on_cluster`; +- `test_u9_replicated_storage_is_detected_and_reaches_every_node`; +- `test_u9_on_cluster_error_after_a_host_answered_needs_wait_end_of_query`, with and without + the setting; +- `test_u10_replicated_grant_reaches_the_other_node_within_the_retry_limit`, for the grant. + +**Means for T4 and T5:** confirms 2.5's `ON CLUSTER` rule. With replicated storage, `ON CLUSTER` +is not just unneeded: it fails. Detection reads `system.user_directories`, so the admin needs +`SELECT` on it. T1's limited admin has it through `system.*`. On Cloud the answer is unknown +until T8. + +It also adds change 6. `up` already sends `wait_end_of_query=1`, but only on the migration +connection, in `ch_migrate/waiting/waiter.py`. `apply` runs its statements on the admin's +connection, which doesn't get that setting. With local storage and `cluster` set, every +create, grant, revoke and drop runs `ON CLUSTER`. So T5 sends the setting with each of them, +or a failing host's error can't be named, as 2.5's exit 1 requires. + +## U10. Reads after writes + +**Answer:** with Keeper storage on the Docker cluster, a `GRANT` on node 1 showed in node 2's +`system.grants` within 4 ms. Three runs of 20 grants each gave a median of 1–2 ms and a maximum +of 3–4 ms. The time includes the polling round trip. + +**Test:** `test_u10_replicated_grant_reaches_the_other_node_within_the_retry_limit`. It prints +the times and asserts only that each is under 30 s. + +**Means for T4:** confirms 2.5's 30 s default for self-hosted Keeper storage. The retry's first +wait can be short. T8 measures Cloud. + +## Changes to the design note + +Each is applied in `2026-11-11-declarative-access.md`, marked "(T2, Un)". None rewrites a +Part 1 decision. Change 5 bore on Decision 3, which has since been decided there. Where a +change left a choice open, the note now carries the decision, marked "(2026-11-11)". + +1. **2.3, grant targets:** a fourth form, ``, for `READ` and `WRITE`, as in + `READ ON REMOTE`. Core already uses it (2.4). 25.8 and later store the old + ` ON *.*` spelling as `READ` and `WRITE`, while 24.8 parses only the old spelling. + `validate` rejects the old spelling and names the new one (2026-11-11) (U1, U8). +2. **2.7:** leaf expansion is the mechanism, summarized there. The candidates list is gone + (U1, U2). +3. **2.5, `check`:** a partly held group counts as missing, an object that doesn't exist yet + doesn't, and 24.8 has no `CHECK GRANT` (U3, U5). On a server older than 25.8, `check` + exits 2 and names its version (2026-11-11). +4. **2.4 and 2.9, cluster grants:** names the four best-effort grants a self-hosted cluster + needs (U7). +5. **2.5, `apply` order, and 2.7:** narrowing a grant's scope can't grant first (U1). `apply` + uses one `WITH REPLACE OPTION` of the whole declared set (2026-11-11). +6. **2.5, `ON CLUSTER`:** every `ON CLUSTER` statement is sent with `wait_end_of_query=1`, so + a host's error keeps its code (U9). + +The decisions also added two items to 2.5 that no answer changed: the 25.8 version floor +for the live commands, and `validate`'s bundled list of privilege names. + +Two notes record answers that confirm Part 2: +- **2.4:** `system.databases` and `system.tables` are implicit on self-hosted servers, and stay + required for Cloud (U7). +- **2.5, `ON CLUSTER`:** with replicated storage it fails, and the storage is read from + `system.user_directories` (U9). + +## The spike's questions, decided + +T2 left six questions open. They were decided on 2026-11-11, in Decisions 3 and 11 of the +design note. + +1. **Scope narrowing in `apply` (T5).** One atomic `GRANT … WITH REPLACE OPTION` of the user's + or role's whole declared set, so there is no gap. If the admin lacks a right the grantee + holds, nothing changes and `apply` says why. It is never used on the migration role + (2026-11-11). +2. **Offline canonical names (T3).** `validate` checks privilege names against a bundled list + taken from 26.3's `system.privileges`. An unknown name is a warning; `plan` checks names + against the live server (2026-11-11). +3. **`check` on 24.8 (T6).** The live `access` commands need 25.8 or later. On an older server + they exit 2 and name its version, so `check` needs no fallback (2026-11-11). +4. **Cluster grants (T6).** U7's four grants stay best-effort, and `check` only warns when one + is missing (2026-11-11). +5. **`ROLE ADMIN` (a T7 docs item).** The docs say that the smallest admin's `ROLE ADMIN` can + grant any role to anyone (2026-11-11). +6. **The old source spelling (T3).** `validate` rejects `REMOTE ON *.*` and the other old + spellings, and its error names the new one, such as `READ, WRITE ON REMOTE` + (2026-11-11). Recognizing the old spelling still needs the source names, which + `system.privileges` doesn't mark (step 7 of the comparison). + +## Open questions + +7. **`bootstrap` on a server older than 25.8 (T6).** Decision 11 covers the live `access` + commands, and `bootstrap` ends by running `check`, which exits 2 there. Should `bootstrap` + refuse such a server before its first write? Or should it apply what it can, warn about + `READ ON REMOTE` under 2.4's best-effort rule, and then report `check`'s exit 2? + + **Superseded 2026-11-16:** every `bootstrap` now exits 2 before its first + write on a server older than 25.8, legacy mode included. The two tests named below were + replaced by `test_bootstrap_refuses_24_8_before_any_write`. + + **Decided for T6** (a default, open to review): + - With an `access.yaml`, `bootstrap` exits 2 before its first write and names the + version. + - Without one, it follows Decision 6: it attempts every grant, warns about + `READ ON REMOTE`, and reports the failures together. + - It skips the read-back and `check` with a warning, because both need 25.8. + - Tests: `test_bootstrap_with_access_yaml_refuses_24_8_before_any_write` and + `test_legacy_bootstrap_on_24_8_attempts_every_grant_and_reports_failures_together`, in + `tests/integration/test_access_bootstrap.py`. Both run on their own 24.8 container. diff --git a/docs/design/2026-11-11-declarative-access.md b/docs/design/2026-11-11-declarative-access.md new file mode 100644 index 0000000..786863b --- /dev/null +++ b/docs/design/2026-11-11-declarative-access.md @@ -0,0 +1,657 @@ +# Declarative access for ch-migrate, decoupled from bootstrap + +**2026-11-11 · Decisions made on 2026-11-11. Nothing is built yet.** + +This note is the design of record for declarative access from T2 on. Code facts in it were +read on `main` at `57ffb8d` (0.8.0) on 2026-11-11. Findings dated 2026-10-29 come from an +earlier proposal for bootstrap permission profiles; where the two differ, this note +wins. + +T2's answers to Part 3 are in `2026-11-11-access-spike.md`. The sections they changed say so +with "(T2, Un)". The decisions on the questions T2 left open are marked +"(2026-11-11)". + +## Part 1. Decisions (2026-11-11) + +1. **A separate command.** `ch-migrate access validate|show|plan|apply|check ENV`. `bootstrap` creates + the database and the migration identity, then uses the same engine for the migration + role's grants. +2. **Declarative YAML.** `access.yaml` declares users, roles, role memberships (with default + roles) and grants (with grant option). `absent: true` drops a user or role. + - This replaces the earlier proposal's add-on and SQL-grant-file layers. + - It reverses the 2026-10-29 proposal's rejection of a YAML grant list. + - The reason: managing users, roles and grants in migrations is tedious and a poor + experience. +3. **Converge what's declared.** + - For each user and role the YAML names, `apply` makes its grants and memberships match + the YAML exactly. + - No declared user or role is ever left without a grant it keeps (2026-11-11, after + T2's U1). `apply` grants before it revokes. A change that narrows a grant's scope, such + as `db.*` to `db.events`, can't grant first, because the server folds the narrower + grant into the broader one. So it is one atomic `GRANT … WITH REPLACE OPTION` of that + user's or role's whole declared set. If the admin lacks a right the grantee holds, + nothing changes and `apply` says why. It is never used on the migration role. + - Users and roles the YAML doesn't name are never touched. + - A user or role is dropped only when it's declared `absent: true`. + - `plan` shows every revoke and drop before `apply` runs them. +4. **The admin applies.** `access apply` runs as `admin_user`. In new projects the migration + role has no user or role management, so it can't grant itself more. +5. **New projects get core only.** `init` writes an `access.yaml`. The migration role holds + only the core profile. +6. **Existing projects keep their grants and get clearer reports.** A project with no + `access.yaml` gets the same grants from `bootstrap` as 0.8 gives. What changes: + - the role and user are created before any grant; + - every grant is attempted, and the failures are reported together; + - a `CURRENT GRANTS` that lands nothing becomes a warning instead of passing silently. + + Config, secret and connection errors still fail as they do today. Apart from those, the + exit code is non-zero only when a plain `GRANT` fails. +7. **v1 scope.** Users, roles, memberships and grants. Row policies, user settings (such as + `readonly = 2`) and quotas come later. +8. **Vehicle: ch-migrate 0.9.0** (2026-11-11). + - It's built on local branches off `main` (0.8.0), one per ticket. Nothing is pushed until + the whole feature is done and has had a final review for private details. + - It's released from `main` after T8. + - This replaces the 2026-10-13 plan, which used 0.9.0 for the 1.0 feature set. That + release was never tagged, and nothing from `dy/ch-migrate-1.0` is released as 0.9.0. + +9. **Build our own narrow solution, with no Terraform requirement** (later the same + day, after the research below). Porting our approach to the official provider as an + open-source contribution is a separate, later decision. +10. **Command names**: `access validate` checks the local file offline. `access show` + connects and reads what the server holds. +11. **After T2's spike** (defaults accepted 2026-11-11): + - The live `access` commands need ClickHouse 25.8 or later. On an older server they exit 2 + and name its version. 0.8's own `bootstrap` already fails on 24.8. Since 2026-11-16, + `bootstrap` needs 25.8 too, legacy mode included. + - `validate` rejects the old source spelling, such as `REMOTE ON *.*`, and its error + names the new one, `READ, WRITE ON REMOTE`. + - `validate` checks privilege names offline against a bundled list taken from 26.3's + `system.privileges`. An unknown name is a warning; `plan` checks names against the + live server. + - The four grants a self-hosted cluster needs for `up` stay best-effort, and `check` only + warns when one is missing (2.9). + - The docs say that the smallest admin's `ROLE ADMIN` can grant any role to anyone. +12. **After T5's blocker** (2026-11-12): + - **Best-effort grants on a self-hosted cluster with local storage.** ClickHouse refuses + `CURRENT GRANTS` with `ON CLUSTER`. Where storage is local and `cluster` is set, `apply`, and + `bootstrap` with an `access.yaml`, send each best-effort privilege as its own plain + `GRANT ON CLUSTER`. A full + admin lands them all on every node; a partial admin lands the ones it holds, and each + refused one is a warning. Everywhere else, best-effort grants stay `CURRENT GRANTS`. + - **Source grants compare as one unit.** With `access_control_improvements.enable_read_write_grants` + off (ClickHouse's default, and not visible from SQL), `READ ON S3` is all-or-nothing and + reads back as `READ` and `WRITE` after a restart. So `plan` and `apply` treat `READ` and + `WRITE` on the same source as one grant: declaring either covers both, and nothing revokes + the other direction. `validate` warns that a one-direction source grant holds only with + that setting on. A hand-added `WRITE` where `READ` is declared goes unnoticed. +13. **Legacy `bootstrap` stays 0.8 on a cluster** (2026-11-12). With no `access.yaml`, + `bootstrap` never uses `ON CLUSTER`, even with `cluster` set, and sends best-effort grants + as `CURRENT GRANTS` on the node it is connected to, exactly as 0.8 does: each node of a + local-storage cluster is bootstrapped on its own, as today. This keeps Decision 6's + promise. `bootstrap` with an `access.yaml`, and `access apply`, follow 2.5 and Decision 12. +14. **One node is read, even on a local-storage cluster** (2026-11-12). + `plan` and `apply` read only the node they connect to. If an `ON CLUSTER` change + lands on one node and fails on another, that `apply` exits 1 naming the error, but the + next run against the first node sees nothing to do. v1 documents it: on a local-storage + cluster, `plan` and `apply` name the node they read, and the README says to run `plan` + against each node after a failed `ON CLUSTER` apply. Reading every node is a follow-up. +15. **Local and Cloud work equally well** (2026-11-12, T8). + - **Every replica is read at once.** Where users and roles are replicated and the + replicas can be read, each read takes every replica through `clusterAllReplicas`, so a + row missing on every replica is absent with no wait. Replicas that disagree are read + again until they agree, within `access_read_timeout`; if they never do, the connected + node's own read counts, and one line names them. Where they can't be read, the + connected node is read and read again as before, and one line says why (2.5). + Local-storage clusters don't change (Decision 14). + - **Which cluster** (2026-11-12, approving T8's rule). `cluster` from + `config.yaml` always wins. Otherwise, of the clusters that hold this node and list + another host, those that list the same `(host, port)` set count as one, and the first + by name is read through; any other case falls back. Why: Cloud with no `cluster` set + must take the replica read, and its `default` and `all_groups.default` are aliases of + the same two hosts. "More than one cluster" was meant to catch clusters that disagree, + not aliases. A stock image's `default` lists only localhost, so it is never a + candidate: read through, it would agree with itself. The cost: a replicated server + with one replica falls back on every command until `cluster` is set. + - **`CLUSTER` granted to every login is held.** ClickHouse Cloud grants `CLUSTER` to + every login. There the best-effort `CLUSTER ON *.*` is already satisfied: no warning, + and no try on every `apply`. Legacy `bootstrap` still sends 0.8's statements + (Decision 13); only what it reports changes. + - **A create's storage** is the first directory that can take one. Cloud lists `jwt` + before `replicated`, and a create never goes to `jwt`, `ldap` or `users.xml`. + +**Existing tools checked (2026-11-11), and why we don't use them:** +- **ClickHouse's official Terraform provider, `clickhousedbops`.** Ownership is confirmed: + - its repo is in the `ClickHouse` GitHub org, whose domain is verified as `clickhouse.com`; + - it is a partner-tier provider on the Terraform Registry; + - clickhouse.com announced it in a 2025-06-20 blog post; + - its maintainers are public members of the `ClickHouse` org. + + It covers users, roles, grants, row policies and settings profiles, on Cloud and + self-hosted. We don't use it for four reasons: + - **It needs Terraform.** + - **It can't own a user's or role's whole grant set.** Each grant is a separate resource, + so a grant added by hand goes unseen. The provider's own proposal for this, ClickHouse/terraform-provider-clickhousedbops#211, has been + open since 2026-06 with no response. + - **Partial revokes aren't supported** (ClickHouse/terraform-provider-clickhousedbops#244). + - **A refresh can silently forget resources** on multi-replica Cloud. When a read briefly + finds nothing, the provider drops the resource from state with no retry. That bug, ClickHouse/terraform-provider-clickhousedbops#157, + has been open since 2026-02. + + Its code is still a useful map of the traps; T2 and section 2.7 borrow from it. +- **Atlas** manages ClickHouse users, roles and grants as code, but only in its paid Pro tier. +- **`users.xml`** declares users and grants in server config. Cloud doesn't allow it, and + ClickHouse recommends SQL-driven access control instead. + +**Defaults this note sets.** Any of them can be overridden at review: +- the file's name and place; +- the additive rule for the migration identity (2.2); +- the core profile carries no grant option (2.4); +- legacy mode is chosen because `access.yaml` is missing, not by a config flag (2.4); +- passwords are set only when a user is created; +- a declared user with no `password` is never created: `--sql` leaves it out and names it in + its header as one that must already exist, and `apply` exits 2 before any change. On 26.3 a + `CREATE USER` with no `IDENTIFIED` clause is a `no_password` login anyone can use + (2026-11-11, checked on Docker after T3); +- `--sql` prints each password placeholder unquoted, `IDENTIFIED BY `, so SQL run + unedited fails to parse instead of setting the placeholder text as a password; +- reads after writes (2.5) are retried only where a replica can be behind. Users and roles + stored on each node's own disk (`local_directory`) are read once; `replicated`, unknown or + unreadable storage is read again for up to `access_read_timeout` (2026-11-11, + from T4). Where `replicated` storage's replicas can be read at once, only replicas that + disagree are read again (Decision 15); +- `~` in `plan` marks every declared user or role that already exists and has a change + pending. ch-migrate keeps no state, so adoption and drift look the same (from T4); +- `apply` tries every best-effort grant that isn't fully held, on every run, with + `GRANT CURRENT GRANTS(...)`. That isn't a counted change, and whatever is still missing + afterwards is a warning. So `plan` can report in sync while it warns about best-effort grants + (from T4). Where `CURRENT GRANTS` can't run `ON CLUSTER`, Decision 12 applies; +- no renames; +- `access.yaml` wins over migrations. +- **Row policies.** v1 has no row policies, so a new core-only project has nowhere to create + them except a migration, and that needs `migration_role.grants` to add the row-policy + rights. Row policies are the first follow-up. + +## Part 2. Design + +The work is split into eight tickets, T1–T8: +- T1: the test harness; +- T2: a spike on ClickHouse's grant behavior; +- T3: `validate`; +- T4: `show` and `plan`; +- T5: `apply`; +- T6: `bootstrap` and `check`; +- T7: docs; +- T8: acceptance on ClickHouse Cloud. + +### 2.1 Three identities + +| Identity | Managed by | Declared in | +| --- | --- | --- | +| Admin (`admin_user`) | The operator | `config.yaml`. Never in `access.yaml`; ch-migrate never modifies it. | +| Migration role and migration user | `bootstrap` and `access apply`, additively | The built-in profile, plus `migration_role.grants` in `access.yaml` | +| Every other user and role | `access apply`, converged | `access.yaml` | + +### 2.2 The migration identity is additive + +- `bootstrap` and `access apply` add any missing profile grants to the migration role. They + never revoke from it. +- `access plan` lists the role's grants beyond its profile as extras. A person revokes those + by hand. +- **Why additive:** + - Two project directories can share one migration role (2.8). If each directory converged + the role, each would revoke the other's database grants. + - An existing project that adopts `access.yaml` keeps the 0.8 grants its old migrations + rely on. +- `access.yaml` can't declare the migration role or user under `roles:` or `users:`. That's a + validation error. It adds grants through `migration_role.grants`. + +### 2.3 `access.yaml` + +It sits at the project root, next to `config.yaml`. + +```yaml +# Desired users, roles and grants. `ch-migrate access plan ENV` shows how the server differs. +migration_role: + profile: core # core (default) | legacy: 0.8's grants, for migrations that create users + grants: + - CREATE FUNCTION, DROP FUNCTION ON *.* + +roles: + analyst: + grants: + - SELECT, SHOW TABLES ON {db}.* + loader: + grants: + - INSERT, SELECT ON {db}.events + reporting: + roles: [analyst] # a role can hold roles + +users: + dashboards: + password: {secret: dashboards_password} # ssm path at environments..ssm.dashboards_password, else CH__DASHBOARDS_PASSWORD + roles: [reporting] + etl: + password: {secret: etl_password} + roles: [loader] + default_roles: [loader] + grants: + - SELECT ON {db}.regions + +environments: + production: + users: + etl: {absent: true} +``` + +- **Grants** use ClickHouse's own words: ` ON [WITH GRANT OPTION]`. + - A target is `*.*`, `.*` or `.
`. Column grants aren't in v1. + - `READ` and `WRITE` take a source as their target, as in `READ ON REMOTE` (T2, U1 and U8). + 25.8 and later store the old spelling, `REMOTE ON *.*`, as `READ` and `WRITE` on that + source. `validate` rejects the old spelling, and its error names the new one, + `READ, WRITE ON REMOTE` (2026-11-11). On 24.8 only the old spelling parses, and + `READ ON ` fails with `SYNTAX_ERROR`; the live `access` commands don't run there + (2.5). + - `READ` and `WRITE` on one source, or on `*.*`, compare as one grant (Decision 12). With + `access_control_improvements.enable_read_write_grants` off, the server holds both. So + `validate` warns about a user's or role's grant that names one direction alone; the + built-in profiles aren't checked, because they aren't the user's to change. + - An entry can also be `{grant: "...", best_effort: true}`. Best-effort means the admin gives + what it can and ch-migrate warns about the rest. It replaces today's `CURRENT GRANTS`. +- **Placeholders** are `{db}`, `{project}`, `{env}` and `{migration_role}`. They are rendered by + `sql.render_placeholders`, and every rendered name must pass `validate_identifier`. +- **Secrets.** `{secret: NAME}` resolves the same way the migration password does. + - If `config.yaml` sets an SSM path at `environments..ssm.NAME`, that path is read, and + the environment variable is never checked. + - Otherwise the environment variable `CH__` is read. + - The caller looks up the path and passes it to `get_secret(env, NAME, ssm_path=...)`, as + `config.py` and `bootstrap.py` already do. `get_secret` doesn't read `config.yaml` itself. + - `validate`, `show` and `plan` never resolve a declared user's secret. +- **Memberships.** + - `roles:` on a user or a role grants it those roles. + - `default_roles:` picks a subset. Without it, every membership is a default role. + - A membership can name a role the YAML doesn't declare, if that role exists on the server. + If it doesn't exist, `plan` names it and exits 2. +- **Environments.** `environments.` deep-merges over the base. Mappings merge and lists + replace. +- **`absent: true`** drops the user or role. Set in an environment block, it drops it in that + environment only. +- **Validation.** Unknown keys are errors. Each error names the file, the key path and the + reason. + +### 2.4 Built-in profiles + +The profiles ship as packaged YAML in `ch_migrate/access/profiles/`. Keeping them out of +Python strings also keeps the python-style gate quiet. + +- **`core`** is what the migration role needs in a new project. T2 (U6, U7) confirmed this + split on a single node: core required alone runs every ch-migrate path the spike tried, and + the smallest admin gives every required grant. On a self-hosted cluster, four of the best-effort grants + are needed (see 2.9). The profile: + - **Required, on `{db}.*`, without grant option:** + - `CREATE TABLE`, `DROP TABLE`, `UNDROP TABLE`, `ALTER`; + - `CREATE VIEW`, `DROP VIEW`, `CREATE DICTIONARY`, `DROP DICTIONARY`; + - `SELECT`, `INSERT`, `DELETE`, `TRUNCATE`, `OPTIMIZE`; + - `SHOW TABLES`, `SHOW COLUMNS`, `SHOW DICTIONARIES`. + - **Required:** `SELECT` on `system.databases`, `system.tables`, `system.mutations` and + `system.dictionaries`. + - `introspect.py` and `scaffold.py` read `system.dictionaries`. + - Today only the `system.*` blanket covers it. + - Self-hosted servers grant `system.databases` and `system.tables` implicitly. They stay + required for Cloud, which T8 checks. + - **Best-effort:** + - `SELECT` on `system.parts` and `system.replicas`; + - `SYSTEM SYNC REPLICA` and `SYSTEM SYNC DATABASE REPLICA` on `{db}.*`; + - `CLUSTER`, `READ ON REMOTE`, and `CREATE TEMPORARY TABLE ON *.*`. + - **No grant option anywhere.** In a new project, rights for other roles come from + `access.yaml`, which the admin applies. +- **`legacy`** is 0.8's migration role exactly. It is a standalone copy of the grant + statements in 0.8's `build_bootstrap_sql`, not "core plus extras". Core differs from 0.8 in + ways an extras list wouldn't undo: + - core adds `SELECT ON system.dictionaries`, which 0.8 never grants; + - core drops grant option; + - core makes `CREATE TEMPORARY TABLE` best-effort. + + T1's characterization fixture defines this profile. For orientation only, 0.8 grants core's + database rights `WITH GRANT OPTION`, plus the following: + - on `*.*`: + - `CREATE FUNCTION`, `DROP FUNCTION`; + - `CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER)`; + - `CREATE ROLE`, `ALTER ROLE`, `DROP ROLE` and `ROLE ADMIN`; + - `CREATE TEMPORARY TABLE`, as a plain grant with grant option; + - `ACCESS MANAGEMENT` and the row-policy rights on `{db}.*`; + - `CURRENT GRANTS(SELECT ON system.*)` and `SELECT ON system.grants`. +- **Best-effort grants** follow three rules: + 1. `validate --sql`, `apply` and `bootstrap` emit them as `GRANT CURRENT GRANTS(...)`. Where the admin + holds part of a privilege, that still lands the part. A plain `GRANT` would land nothing. + ClickHouse refuses `CURRENT GRANTS` with `ON CLUSTER`, so where statements run `ON CLUSTER` + each privilege is its own plain `GRANT ON CLUSTER`, and a refused one is a warning + (Decision 12). + 2. A best-effort grant that is missing or only partly held is a warning in `plan`, `apply`, + `check` and `bootstrap`, and never changes the exit code. Otherwise `plan` could never + reach 0 where the admin can't give it, such as on ClickHouse Cloud. A right the server + grants every login is held without a grant: on Cloud, and wherever + `on_cluster_queries_require_cluster_grant` is off, that is `CLUSTER ON *.*`. The + admin's `CHECK GRANT CLUSTER ON *.*` answers 1 there while neither its own grants nor + its enabled roles' hold `CLUSTER`, which is how `plan` tells (Decision 15). `check` + already agrees, since `CHECK GRANT` answers 1 for the migration user too. + 3. Only a missing required grant makes `plan` or `check` exit 1. +- **Legacy mode** applies to a project with no `access.yaml`. + - `bootstrap` applies the `legacy` profile. + - `mcp_user_name` and `dict_reader_name` produce the same read-only and dictionary roles and + users that 0.8 creates. These stay additive: 0.8 never converged them. + - `access apply` in legacy mode only adds missing `legacy` grants to the migration role. + +### 2.5 Commands + +| Command | Logs in as | Secrets it needs | Writes | Exit codes | +| --- | --- | --- | --- | --- | +| `access validate ENV` | Nobody | None | Nothing | 0 valid, 2 invalid | +| `access show ENV [NAME...]` | Admin | Admin's | Nothing | 0. 2 on an error. | +| `access plan ENV` | Admin | Admin's | Nothing | 0 in sync, 1 changes pending, 2 error | +| `access apply ENV [--reset-passwords]` | Admin | Admin's, plus those of users it creates | Yes | 0 converged (best-effort shortfalls warn), 1 not converged: a change failed or was skipped (each one named), or something still differs, 2 error before any change | +| `access check ENV` | Migration user | Migration user's | Nothing | 0 every required grant held, 1 missing (each one named), 2 error | +| `bootstrap ENV [--dry-run]` | Admin, then the migration user for the check | Admin's and the migration user's. None with `--dry-run`. | Yes | Same as `apply` | + +- **Server version.** The live commands, `show`, `plan`, `apply` and `check`, need ClickHouse + 25.8 or later. On an older server they exit 2 and name its version (2026-11-11). 24.8 + has no `CHECK GRANT` and no `READ ON ` (T2, U5 and U8). +- **`validate`** checks `access.yaml` and the built-in profiles, and reports every error with + the file, the key path and the reason. + - With `--sql`, it also prints the SQL a DBA can review and run: `CREATE ROLE IF NOT EXISTS`, + `CREATE USER IF NOT EXISTS` and the `GRANT` statements. Each password is replaced by a + placeholder that names its secret. + - A declared user with no `password` is never created: `--sql` leaves it out and names it + in its header as one that must already exist, and `apply` exits 2 before any change. On + 26.3 a `CREATE USER` with no `IDENTIFIED` clause is a `no_password` login anyone can use. + - `--sql` prints each password placeholder unquoted, `IDENTIFIED BY `, so SQL + run unedited fails to parse instead of setting the placeholder text as a password. + - It needs no server and no secrets. It reads `config.yaml` through a new loader that + resolves no secrets. + - It checks privilege names against a bundled list taken from 26.3's `system.privileges`. + An unknown name is a warning; `plan` checks names against the live server + (2026-11-11). + - `get_env_config` keeps its shape, because client code imports it. +- **`show`** connects as the admin and prints what the server holds, in `access.yaml` form. + - It covers the declared users and roles, or the names given on the command line. + - It never shows passwords. + - Pointed at existing users, its output is the starting point for adopting them, so it + replaces the "export" follow-up. +- **`plan`** prints one line per change, with `ui` markers: + - `+` create or grant; + - `-` revoke or drop; + - `~` adopt: the entity exists and is now managed; + - `!` an extra grant on the migration role. These don't change the exit code. + + `--json` is a follow-up. +- **`apply`** runs its changes in this order: + 1. create roles; + 2. create users; + 3. memberships; + 4. grants, then the replaces that narrow a scope (below); + 5. default roles; + 6. revokes; + 7. drops. + + It continues past a failed statement, then plans again and reports whatever still differs. + - **Narrowing a scope can't grant first** (T2, U1). For `SELECT ON db.*` to + `SELECT ON db.events`, the new grant is absorbed and writes nothing, so revoking `db.*` + afterwards removes both. So `apply` runs one atomic `GRANT … WITH REPLACE OPTION` of + that user's or role's whole declared set (2026-11-11; Decision 3). + - There is no gap without access, and role memberships are kept. + - It needs the admin to hold every right the grantee has now, with grant option. If the + admin lacks one, the statement fails, nothing changes, and `apply` says why. + - It is never used on the migration role, which is additive (2.2). + - **Secrets first.** Before its first write, `apply` resolves every secret it will need, + SSM lookups included. A missing secret exits 2 with nothing changed. + - **No revoke without its replacement.** Revokes run only if every earlier create, + membership, grant, replace and default-role change succeeded, for any user or role. If + one failed, every revoke is skipped and reported, so old access survives. The skip names + the user's or role's own failure, or a role's it holds, when there is one; otherwise the + failure elsewhere. A failure anywhere counts because a role's holders may rely on a + sibling role whose change failed: a user holding `A` and `B`, with access moving from `A` + to `B`, keeps `A` when the grant to `B` fails. + - Example: a user moves from role A to role B, and granting B fails. `apply` keeps A. + - A failed change to a role counts as failed for every declared user or role that holds + it, directly or through declared roles. Example: the user is granted B, but B's own + grant fails: the user keeps A. + - A replace (`WITH REPLACE OPTION`) is gated like a revoke: it is skipped if any earlier + change failed. It keeps whatever is + held inside a declared best-effort grant's scope. + - A default-role change is gated the same way, so a role the user keeps stays active at + login. + - Replaces run dependencies first: a role's replace runs before the replace of any user + or role that holds it, directly or through declared roles, whatever access.yaml's + order, so the gate sees how it went. + - A replace that can't keep exactly what is held of a declared best-effort grant isn't + sent: it is skipped and named, the user or role keeps what it holds, and `apply` exits + 1, since the replace is still pending. That is a revoke inside the grant's scope, such + as `SELECT ON system.*` held less `system.users`, or a revoke of only the grant option + there where the declared grant carries one: one `WITH REPLACE OPTION` statement can't + write "all but". Every revoke, replace and default-role change after it is skipped as + after a failure. + - Drops run only if no earlier change failed and every replace was sent. Otherwise each + drop is skipped and named: a revoke held back may leave a user or role relying on a + role about to be dropped. + - A password is a bound parameter sent in the request body (`raw_query`, form-encoded), + never in the statement or the URL, where a proxy's log or a connection error could show + it. Every error ch-migrate prints hides each secret it has read, raw and URL-encoded. + - Passwords are set only when a user is created. `--reset-passwords` sets them again for the + declared users, including one this run creates, right after its create: if someone else + makes the user between the read and `CREATE USER IF NOT EXISTS`, the create keeps their + password. A failed reset holds back every revoke, replace and + default-role change, as any failure does, and every later change to that user: its + password may not be the declared one. A failed create does the same: an admin without + `CREATE USER` fails it even when someone else has made the user. + - It refuses to declare or modify `admin_user`, or the login it is connected as. +- **Reads after writes, for `apply`, `plan`, `show` and `bootstrap`.** + - On multi-replica Cloud, a grant just made may not show up yet on a read routed to the + other replica. A missing row never leads straight to a create or a revoke. + - This is the gap behind the official provider's bug ClickHouse/terraform-provider-clickhousedbops#157. + - **Every replica at once** (Decision 15). Where users and roles are replicated, each read + takes every replica in one query per table, through `clusterAllReplicas`, with each row + tagged by its replica's `hostName()`, and with `skip_unavailable_shards = 0`, so a + replica that can't be reached fails the read instead of reading as empty. + - The cluster is `cluster` from `config.yaml` whenever it is set. Otherwise it is the + cluster in `system.clusters` that holds this node and at least one other host; + clusters that list the same `(host, port)` set count as one (Decision 15). Cloud lists + `default` and `all_groups.default` with the same hosts, and a stock image lists a + `default` of localhost alone, which isn't one. + - The read is settled when every replica returns the same rows for the names read, so a + row missing on every replica is absent at once. That is safe right after a write: + over 30 rounds each of `CREATE ROLE`, `GRANT`, `REVOKE` and `DROP ROLE`, every replica + showed the write on the very next read, 2 of 2 on Cloud 26.6 and 2 of 2 on the local + Keeper cluster (T8). An earlier probe saw replica lag of 0.070 s at + most, about 0.04 s at p50. + - Replicas that disagree are read again with backoff, within the time limit below, and + each such read also reads the node connected to. If they still disagree at the + deadline, as a cluster that takes in a node outside the replicated storage always + would, no row counts as present or absent from them: the connected node's own read + counts, as at the deadline of the fallback below, and one line names the replicas + (2026-11-12). + - `clusterAllReplicas` needs `READ ON REMOTE`, on 25.8, 26.3 and Cloud 26.6, plus + `SELECT` on each table it reads, which the read needs anyway; on Cloud a login without + that `SELECT` is told it lacks `SHOW COLUMNS` on the table. `CREATE TEMPORARY TABLE` + isn't needed. Finding the cluster also reads `system.clusters`. A login without these + takes the fallback below; it never fails. + - **Falling back.** When the replicas can't be read that way (no one cluster found, a + login without `READ ON REMOTE`, a replica that can't be reached), the command reads the + node it is connected to. A read that finds nothing is retried with backoff, up to a time + limit (default 30 s, configurable), before it counts as "absent". A lone replicated node + keeps this wait: it cannot be distinguished from a node whose peers aren't listed in a + cluster. The way to read is chosen at the first read and kept for the command. + - The wait notice and fallback reason print only when the command actually waits. The + fallback reason prints once per command, even if `apply` waits only after its writes. +- **`ON CLUSTER`.** On a self-hosted cluster, users and roles live either in replicated + storage (Keeper) or locally on each node. + - ch-migrate reads which one from the server. + - With local storage and `cluster` set in `config.yaml`, every create, grant, revoke and drop + runs `ON CLUSTER`. A best-effort grant goes one privilege per `GRANT ON CLUSTER`, because + `CURRENT GRANTS` can't run there (Decision 12). + - The cluster's name is written backquoted, so a name such as `c-1` parses (checked on + 25.8 and 26.3). + - With replicated storage, or on Cloud, it doesn't. With replicated storage, `ON CLUSTER` + fails with `ACCESS_ENTITY_ALREADY_EXISTS` (T2, U9). + - `bootstrap` with no `access.yaml` never does, even with `cluster` set: it runs on the node + it is connected to, as 0.8 does, and each node is bootstrapped on its own (Decision 13). + - `plan`, `apply` and `bootstrap` with an `access.yaml` read only the node they are + connected to (Decision 14). With local storage and `cluster` set, each prints one line + naming that node, by the server's `hostName()`, or by the configured host and port when + that can't be read. The line says to run `plan` against each node after a failed + `ON CLUSTER` apply. Nothing prints on Keeper storage, on a single node, or for legacy + `bootstrap` (T6). + - The first storage in `system.user_directories`, by `precedence`, that a create can go + to is where it goes: `local_directory`, `replicated` or `memory` (T2, U9). `users_xml`, + `ldap` and Cloud's `jwt` only read; Cloud lists `jwt` before `replicated` (T8). + - Every `ON CLUSTER` statement is sent with the setting `wait_end_of_query=1`, as `up`'s + waiter already does. Without it, a host that fails after another has answered can't + turn the response into an error: the server has already sent HTTP 200 and the first + rows, so it cuts the response, and the client gets no error code (T2, U9). +- **`check`** runs `CHECK GRANT`, as the migration user, for each required grant of the + migration role (its profile plus `migration_role.grants`). It is for DBA-managed servers + where ch-migrate has no admin login. + - A group that is only partly held answers 0, so it counts as missing. A grant on an object + that doesn't exist yet answers 1 (T2, U3 and U5). + - `CHECK GRANT` on a group checks every flag in it, even those its target can't hold. + `ACCESS MANAGEMENT ON db.*` answers 0 on 25.8 and 26.3 right after 0.8's `bootstrap` + grants it, because the group's user and role rights apply only on `*.*`. So `check` sends + each grant as the flags it means on its target (2.7), read from the server's own + `system.privileges`, which the migration user can read. Every grant of both profiles + then answers 1 after a full admin's `bootstrap` (T6). + - `CHECK GRANT` takes no `WITH GRANT OPTION`, so `check` checks privileges only. + - 24.8 has no `CHECK GRANT`; it reads the statement as `CHECK TABLE` and fails with + `SYNTAX_ERROR` (T2, U5). So `check`, like every live `access` command, exits 2 on a + server older than 25.8 and names its version (2026-11-11). +- **`bootstrap`** does the following, in order: + 1. `CREATE DATABASE IF NOT EXISTS`; + 2. creates the migration role and user if they're missing, with the password set at + creation; + 3. adds the migration role's profile grants; + 4. in legacy mode, creates the read-only and dictionary roles and users; + 5. runs `check`. + + It doesn't apply the rest of `access.yaml`. A fresh environment runs `bootstrap`, then `up`, + then `access apply`. + +### 2.6 Living alongside migrations + +- **New projects.** The migration role has no user or role management, so a migration can't + create users or roles. They go in `access.yaml`. +- **Projects whose migrations create users or roles** keep working: + - In legacy mode, nothing changes. + - A project that adopts `access.yaml` sets `migration_role.profile: legacy` to keep those + rights on fresh environments. +- **When a migration and `access.yaml` both touch a declared user or role, `access.yaml` wins at + the next `apply`.** Deploys run `up`, then `access apply`. `access plan` in CI shows any drift + a migration introduced. +- **Adoption.** Declaring a user or role that already exists adopts it. `plan` shows `~ adopt`, + then the grant and membership differences. Its password isn't touched unless you pass + `--reset-passwords`. +- **Renames aren't supported.** Declare the old name `absent: true` and add the new one. + +### 2.7 Comparing desired and live grants + +`plan` must compare without writing. The constraints, partly learned from the official +provider's code: +- **A text diff of `SHOW GRANTS` doesn't work.** ClickHouse folds and expands privileges + (2026-10-29 finding). +- **A parent privilege may be stored as its children.** `CREATE` or `ACCESS MANAGEMENT` can + appear in `system.grants` as one row per child privilege. +- **A narrower grant can be absorbed by a broader one,** and then ClickHouse writes no row for + it. +- **Prefix grants** (`db.t*`) are stored without the `*` before ClickHouse 26.7. v1 doesn't + allow prefix targets. +- **Only canonical names round-trip.** The loader rewrites aliases to canonical privilege + names, using `system.privileges`, before comparing. +- **Narrowing a grant must revoke only the difference.** `REVOKE ALTER` also removes + `ALTER UPDATE`, so going from `ALTER` to `ALTER UPDATE` can't be "grant the new, revoke the + old". + +**The mechanism is leaf expansion** (T2, U1 and U2). It is read-only and needs no +version-specific list. The spike record's "The comparison" section has the steps: +- Read `system.privileges` from the server being compared. The three tested images differ. +- A privilege with a `level` carries its own flag; one without is a group. A privilege means + its own flag plus its descendants' flags, kept only where the target's scope allows that + level. +- Expand desired grants and `system.grants` rows to rights: one per flag, scope and grant + option. A row with `is_partial_revoke = 1` is a revoke. +- Compare by coverage both ways. A right is missing when no live right covers it, and extra + when no desired right covers it. A revoke row on a declared user or role is drift; granting + the declared grant again clears it. +- Narrow a privilege by revoking the extra flags on their own scope. Drop only a grant option + with `REVOKE GRANT OPTION FOR`. Narrowing a scope is different; see `apply` in 2.5. +- A declared `READ` or `WRITE` on a source, or on `*.*`, covers the other direction on the + same scope, so that one is never extra (Decision 12). The declared direction must still be + held: a role that declares `READ` and holds only `WRITE` is granted `READ`. +- A column grant on a live user or role is narrower than its table. v1 declares none, so a + desired table grant shows it as missing, and granting the table absorbs the column row. + +T2 also weighed a scratch role and `CHECK GRANT`. A scratch role writes, so `plan` can't use +it. `CHECK GRANT` sees only the current user and no grant option, so only `check` uses it. + +### 2.8 A second database + +- **This already works on 0.7.0** (verified in Docker 26.3 on 2026-10-29): + - Two project directories each get their own database and version table. + - They share the migration role when both use the same `project.name` and `migration_user`. +- **v1 adds an optional `migration_role:` key in `config.yaml`.** The second directory names + the role it shares instead of relying on a matching project name. +- **Under the additive rule (2.2):** + - Each directory's `bootstrap` adds core on its own database. Neither revokes the other's + grants. + - On a server where only the first directory was bootstrapped, the role has no rights on + the second database, so a stray migration there fails with `ACCESS_DENIED`. + +### 2.9 Not in v1 + +- row policies, user settings and settings profiles, quotas, and host restrictions; +- column-level grants; +- `--json`; +- prefix grant targets (`db.t*`); +- revoking from the migration role; +- renames; +- a lint rule for user and role statements in migrations; +- cluster grants that become required only when a cluster applies. On a self-hosted cluster, + `up` needs `CLUSTER`, `READ ON REMOTE`, `SYSTEM SYNC REPLICA` and, while a mutation on a + replicated table is pending, `SELECT ON system.replicas` (T2, U7). Core keeps them + best-effort, and `check` only warns when one is missing (2026-11-11); +- a read-only login for `plan`. It needs the admin's for now; +- reading every node of a local-storage cluster, so that an `ON CLUSTER` change that failed on + one node is seen and made on the next run (Decision 14). + +## Part 3. Unknowns T2 settles + +Each answer becomes a test in `tests/integration/test_access_spike.py` that keeps asserting +it, plus a line in `docs/design/2026-11-11-access-spike.md` that names the test. + +- **U1. Read-only comparison.** Does leaf expansion from `system.privileges` reproduce what + `system.grants` holds after each `GRANT` in both profiles? It must handle: + - folded privileges (`DELETE`, `ACCESS MANAGEMENT`); + - a parent stored as its children; + - a narrower grant absorbed by a broader one, which leaves no row; + - narrowing; + - aliases rewritten to canonical names. + + If no read-only mechanism works, stop and decide again. +- **U2. Partial revokes.** How do they appear in `system.grants`, and does granting again + clear them? +- **U3. Objects that don't exist yet.** Does ClickHouse accept grants on tables and databases + that don't exist? The answer decides whether `access apply` can run before `up`. +- **U4. Passwords.** Confirm that nothing the admin can read by default shows a password or + its hash. Then `plan` never compares passwords. +- **U5. `CHECK GRANT`.** Which of images 24.8, 25.8 and 26.3 support it, and what does it + return for a partly granted privilege? +- **U6. The smallest admin.** What is the smallest admin grant set that can run a core-only + `bootstrap` on single-node Docker? Which core grants can that admin not give? +- **U7. What ch-migrate needs.** Which core grants does each ch-migrate path need, on a single + node and on the replicated cluster fixture? The answer moves grants between required and + best-effort. +- **U8. `system.privileges`.** Is it there, and in what shape, on the same images as U5? +- **U9. Where users and roles are stored.** On the cluster fixture, run the cluster once with + local access storage and once with replicated (Keeper) storage. Answer two questions: + - Can ch-migrate tell which mode the server uses, from the server alone? + - With local storage, does a create or grant without `ON CLUSTER` reach only one node, while + one with `ON CLUSTER` reaches every node? +- **U10. Reads after writes.** With replicated storage on the cluster fixture, how long after + a `GRANT` on one node until another node's `system.grants` shows it? This sets the retry + default. T8 measures the same on Cloud. diff --git a/docs/plans/2026-03-05_architectural_review_DRY-13.md b/docs/plans/2026-03-05_architectural_review.md similarity index 96% rename from docs/plans/2026-03-05_architectural_review_DRY-13.md rename to docs/plans/2026-03-05_architectural_review.md index b6cd6be..ebe4492 100644 --- a/docs/plans/2026-03-05_architectural_review_DRY-13.md +++ b/docs/plans/2026-03-05_architectural_review.md @@ -2,8 +2,7 @@ **Reviewer:** Principal Architect **Date:** 2026-03-05 -**Design under review:** DRY-11 feature proposals (12 proposed features for ch-migrate) -**Related issues:** [DRY-11](/issues/DRY-11) (feature proposals), [DRY-12](/issues/DRY-12) (design), [DRY-13](/issues/DRY-13) (this review) +**Design under review:** feature proposals (12 proposed features for ch-migrate) --- @@ -206,9 +205,7 @@ The one pattern break is the introspection module, which introduces live DB intr 3. **The priority split into tiers is sensible.** Tier 1 features are genuinely high-impact. Tier 3 features are correctly deferred. -4. **The "lead magnet for consulting agency" framing** is a good product lens. Features 1 (diff), 3 (lint), and 8 (PG helper) have the strongest lead magnet potential. - -5. **The proposal acknowledges that declarative mode is too large** for the current phase. Good restraint. +4. **The proposal acknowledges that declarative mode is too large** for the current phase. Good restraint. --- diff --git a/examples/basic/README.md b/examples/basic/README.md index d102929..df604f5 100644 --- a/examples/basic/README.md +++ b/examples/basic/README.md @@ -52,8 +52,17 @@ A minimal example showing ch-migrate-cli in action. ch-migrate up dev ``` +7. Create the users and roles that `access.yaml` declares. `apply` sets the passwords of + the users it creates, so first add `CH_DEV_DASHBOARDS_PASSWORD` and + `CH_DEV_ETL_PASSWORD` to `.env.local`, or their SSM paths to `config.yaml`: + ```bash + ch-migrate access plan dev + ch-migrate access apply dev + ``` + ## Files - `config.yaml` - ClickHouse connection settings (edit hosts) +- `access.yaml` - Users, roles and grants, declared - `.env.local.example` - Template for secrets - `migrations/sql/history/tables/users/001_example.sql` - Example table schema diff --git a/examples/basic/access.yaml b/examples/basic/access.yaml new file mode 100644 index 0000000..85727e7 --- /dev/null +++ b/examples/basic/access.yaml @@ -0,0 +1,42 @@ +# Users, roles and grants for the basic example, declared. +# ch-migrate access validate dev checks this file, offline +# ch-migrate access plan dev shows how the server differs from it +# ch-migrate access apply dev makes the server match, logged in as admin_user +# +# The migration role holds the `core` profile: what migrations need on the project's +# database, with no user or role management. `ch-migrate bootstrap dev` gives it. +migration_role: + profile: core + # Grants the migration role needs beyond core, such as for functions: + # grants: + # - CREATE FUNCTION, DROP FUNCTION ON *.* + +# `access apply` creates these and keeps their grants and roles exactly as declared. +# Users and roles not named here are never touched. {db} is the environment's database. +roles: + analyst: + grants: + - SELECT, SHOW TABLES ON {db}.* + loader: + grants: + - INSERT, SELECT ON {db}.users + reporting: + roles: [analyst] # a role can hold roles + +users: + dashboards: + # Read from environments.dev.ssm.dashboards_password in config.yaml, else from + # CH_DEV_DASHBOARDS_PASSWORD. It is set only when the user is created. + password: {secret: dashboards_password} + roles: [reporting] + etl: + password: {secret: etl_password} + roles: [loader] + default_roles: [loader] + +# A block per environment merges over the above: mappings merge and lists replace. +# `absent: true` drops a user or role in that environment only. +# environments: +# dev: +# users: +# etl: {absent: true} diff --git a/examples/basic/config.yaml b/examples/basic/config.yaml index 626645c..3de43b5 100644 --- a/examples/basic/config.yaml +++ b/examples/basic/config.yaml @@ -5,7 +5,6 @@ defaults: port: 8443 secure: true admin_user: default - dict_reader_name: dict_reader environments: dev: diff --git a/scripts/bundle_privileges.py b/scripts/bundle_privileges.py new file mode 100644 index 0000000..8beb6c2 --- /dev/null +++ b/scripts/bundle_privileges.py @@ -0,0 +1,97 @@ +"""Write ch_migrate/access/privileges_26_3.json from a throwaway ClickHouse 26.3 container. + +`access validate` checks privilege names offline against that file. This starts its own +`clickhouse/clickhouse-server:26.3` container, records the list with +`ch_migrate.access.bundle.record_privileges`, and removes the container, even on failure. +Review the diff before committing it. `tests/integration/test_access_privilege_list.py` +fails when the file and the image disagree. + + uv run --locked python scripts/bundle_privileges.py +""" + +from __future__ import annotations + +import json +import secrets +import subprocess +import sys +import time +from pathlib import Path +from urllib.error import URLError +from urllib.request import urlopen + +import clickhouse_connect + +from ch_migrate.access.bundle import record_privileges +from ch_migrate.access.privileges import BUNDLED_LIST + +IMAGE = "clickhouse/clickhouse-server:26.3" +SCRATCH_ROLE = "chm_privilege_list_scratch" + + +def main() -> int: + name = "chm-privileges-" + secrets.token_hex(4) + password = secrets.token_hex(16) + try: + port = _start_container(name, password) + client = _connect(port, password) + document = record_privileges(client, SCRATCH_ROLE) + client.close() + finally: + subprocess.run(["docker", "rm", "--force", "--volumes", name], capture_output=True) + BUNDLED_LIST.write_text(_format(document)) + count = len(document["privileges"]) + print(f"Wrote {count} privileges from {document['version']} to {_relative(BUNDLED_LIST)}") + return 0 + + +def _start_container(name: str, password: str) -> int: + subprocess.run( + ["docker", "run", "--detach", "--name", name, "--publish", "127.0.0.1::8123"] + + ["--env", f"CLICKHOUSE_PASSWORD={password}"] + + ["--env", "CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1", IMAGE], + check=True, + capture_output=True, + ) + result = subprocess.run( + ["docker", "port", name, "8123/tcp"], check=True, capture_output=True, text=True + ) + return int(result.stdout.strip().rsplit(":", 1)[1]) + + +def _connect(port: int, password: str): # type: ignore[no-untyped-def] + _wait_for_ping(port) + return clickhouse_connect.get_client( + host="127.0.0.1", port=port, username="default", password=password + ) + + +def _format(document: dict) -> str: + """One privilege per line, so a new image's changes read as a short diff.""" + rows = ",\n".join(" " + json.dumps(row) for row in document["privileges"]) + return ( + f'{{\n "version": {json.dumps(document["version"])},\n "privileges": [\n{rows}\n ],\n' + f' "source_spellings": {json.dumps(document["source_spellings"])}\n}}\n' + ) + + +def _wait_for_ping(port: int) -> None: + deadline = time.monotonic() + 60 + while True: + try: + with urlopen(f"http://127.0.0.1:{port}/ping", timeout=2) as response: + if response.status == 200: + return + except (OSError, URLError): + pass + if time.monotonic() > deadline: + raise TimeoutError("ClickHouse did not answer /ping within 60 seconds") + time.sleep(0.5) + + +def _relative(path: Path) -> str: + return str(path.relative_to(Path.cwd())) if path.is_relative_to(Path.cwd()) else str(path) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/clean_wheel_access.sh b/scripts/clean_wheel_access.sh new file mode 100755 index 0000000..c1ce50f --- /dev/null +++ b/scripts/clean_wheel_access.sh @@ -0,0 +1,191 @@ +#!/usr/bin/env bash +# Run the access workflow from the built wheel alone, against a ClickHouse 26.3 container +# this script owns. +# +# scripts/clean_wheel_access.sh +# +# 1. Builds the wheel from this checkout. +# 2. Creates a venv in a temporary directory and installs only that wheel, with its +# dependencies pinned to uv.lock. Nothing is imported from the checkout. +# 3. Starts its own clickhouse/clickhouse-server:26.3 container on a random loopback port. +# 4. In a new project: init, bootstrap, new, up; access plan (0); adds a role and a user +# holding it to access.yaml; access plan (1); access apply; access plan (0); +# access check (0). Every exit code is checked. +# 5. Removes the container and its volumes with `docker rm -fv`, even on failure. +# +# Exits non-zero at the first step that fails. Needs Docker and uv. +set -euo pipefail + +IMAGE="clickhouse/clickhouse-server:26.3" +PYTHON_VERSION="3.10" +# How long the server has to answer once its container starts, and the bounds on each +# readiness request within that. +READY_SECONDS=60 +CONNECT_SECONDS=2 +REQUEST_SECONDS=5 +REPO=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +WORK=$(cd "$(mktemp -d "${TMPDIR:-/tmp}/chm-wheel.XXXXXX")" && pwd -P) +CONTAINER="chm-wheel-${WORK##*.}" +VENV="$WORK/venv" +PROJECT="$WORK/project" + +cleanup() { + docker rm -fv "$CONTAINER" >/dev/null 2>&1 || true + rm -rf "$WORK" +} +trap cleanup EXIT +trap 'exit 130' INT TERM + +step() { + echo "==> $*" +} + +secret() { + od -An -tx1 -N16 /dev/urandom | tr -d ' \n' +} + +build_and_install() { + step "Building the wheel" + (cd "$REPO" && uv build -q --wheel --out-dir "$WORK/dist") + local wheels=("$WORK"/dist/*.whl) + [ "${#wheels[@]}" -eq 1 ] || { echo "Expected one wheel, found ${#wheels[@]}" >&2; exit 1; } + step "Installing $(basename "${wheels[0]}") alone into a Python $PYTHON_VERSION venv" + (cd "$REPO" && uv export -q --locked --no-dev --no-emit-project --no-hashes \ + --output-file "$WORK/constraints.txt") + uv venv -q --python "$PYTHON_VERSION" "$VENV" + uv pip install -q --python "$VENV/bin/python" --constraint "$WORK/constraints.txt" \ + "${wheels[0]}" + "$VENV/bin/python" -I - "$VENV" <<'PY' +import os +import sys + +import ch_migrate + +where = os.path.realpath(ch_migrate.__file__) +if not where.startswith(os.path.realpath(sys.argv[1]) + os.sep): + sys.exit(f"ch_migrate was imported from {where}, outside the venv") +print(f"ch_migrate {ch_migrate.__version__} from {os.path.dirname(where)}") +PY +} + +start_server() { + step "Starting $IMAGE as $CONTAINER" + CLICKHOUSE_PASSWORD="$ADMIN_PASSWORD" docker run --detach --name "$CONTAINER" \ + --publish 127.0.0.1::8123 --env CLICKHOUSE_PASSWORD \ + --env CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1 "$IMAGE" >/dev/null + local address + address=$(docker port "$CONTAINER" 8123/tcp | head -n 1) + PORT=${address##*:} + wait_for_server +} + +# Ask the server for its version until it answers, for up to READY_SECONDS. Every curl is +# bounded: a server that accepts a connection but never answers can't hold the loop past +# its deadline, or keep the EXIT trap from removing the container. +wait_for_server() { + local version left deadline=$((SECONDS + READY_SECONDS)) + while left=$((deadline - SECONDS)); [ "$left" -gt 0 ]; do + if version=$(curl -sf --connect-timeout "$CONNECT_SECONDS" \ + --max-time "$((left < REQUEST_SECONDS ? left : REQUEST_SECONDS))" \ + -u "default:$ADMIN_PASSWORD" --data-binary "SELECT version()" "http://127.0.0.1:$PORT/"); then + echo "ClickHouse $version on 127.0.0.1:$PORT" + return + fi + sleep 0.5 + done + echo "ClickHouse wasn't ready in $READY_SECONDS s" >&2 + exit 1 +} + +# Run the installed ch-migrate in the project, with nothing inherited from the caller's +# environment, so no CH_* variable or PYTHONPATH can leak in. +chm() { + (cd "$PROJECT" && env -i PATH="$VENV/bin:/usr/bin:/bin" HOME="$WORK" PYTHONUTF8=1 \ + NO_COLOR=1 "$VENV/bin/ch-migrate" "$@") +} + +# expect CODE ARGS...: run `ch-migrate ARGS...` and fail unless it exits CODE. +expect() { + local want=$1 got=0 + shift + step "ch-migrate $* (expect exit $want)" + chm "$@" || got=$? + if [ "$got" -ne "$want" ]; then + echo "FAIL: ch-migrate $* exited $got, expected $want" >&2 + exit 1 + fi +} + +write_project_files() { + cat >"$PROJECT/config.yaml" <"$PROJECT/.env.local" <&2; exit 1; } + cat >"$up" <<'EOF' +CREATE TABLE IF NOT EXISTS {db}.logs (id UInt64) +ENGINE = MergeTree ORDER BY id; +ALTER TABLE {db}.logs ADD COLUMN IF NOT EXISTS status String; +EOF + echo 'DROP TABLE IF EXISTS {db}.logs;' >"$down" +} + +declare_role_and_user() { + step "Adding a role and a user holding it to access.yaml" + cat >>"$PROJECT/access.yaml" <<'EOF' + +roles: + analyst: + grants: + - SELECT, SHOW TABLES ON {db}.* + +users: + dashboards: + password: {secret: dashboards_password} + roles: [analyst] +EOF +} + +main() { + ADMIN_PASSWORD=$(secret) + build_and_install + start_server + mkdir "$PROJECT" + expect 0 init --name wheel_check + write_project_files + expect 0 bootstrap dev + expect 0 new dev add_status --table logs + fill_migration + expect 0 up dev + expect 0 access plan dev + declare_role_and_user + expect 1 access plan dev + expect 0 access apply dev + expect 0 access plan dev + expect 0 access check dev + step "Every step exited as expected" +} + +main "$@" diff --git a/tests/access/conftest.py b/tests/access/conftest.py new file mode 100644 index 0000000..e0a12ce --- /dev/null +++ b/tests/access/conftest.py @@ -0,0 +1,70 @@ +"""Shared fixtures for the offline access tests: a project's settings and its files.""" + +from __future__ import annotations + +import textwrap + +import pytest + +from ch_migrate.access.loader import validate_access +from ch_migrate.access.settings import ProjectSettings + +CONFIG_YAML = """\ +project: + name: shop +environments: + dev: + host: localhost + database: shop_dev + migration_user: shop_migrator + admin_user: shop_admin + production: + host: localhost + database: shop_prod + migration_user: shop_migrator + admin_user: shop_admin +""" + + +@pytest.fixture +def settings(): + return ProjectSettings( + environment="dev", + database="shop_dev", + project="shop", + migration_user="shop_migrator", + admin_user="shop_admin", + environments=("dev", "production"), + ) + + +@pytest.fixture +def validate(tmp_path, settings): + """Write access.yaml (dedented) and validate it; returns the Validation.""" + + def run(text, environment=None): + (tmp_path / "access.yaml").write_text(textwrap.dedent(text)) + chosen = settings if environment is None else _for(settings, environment) + return validate_access(chosen, tmp_path) + + return run + + +@pytest.fixture +def project(tmp_path, monkeypatch): + """A project directory holding config.yaml, as the working directory.""" + (tmp_path / "config.yaml").write_text(CONFIG_YAML) + monkeypatch.chdir(tmp_path) + return tmp_path + + +def _for(settings, environment): + database = {"dev": "shop_dev", "production": "shop_prod"}[environment] + return ProjectSettings( + environment=environment, + database=database, + project=settings.project, + migration_user=settings.migration_user, + admin_user=settings.admin_user, + environments=settings.environments, + ) diff --git a/tests/access/fake_access_server.py b/tests/access/fake_access_server.py new file mode 100644 index 0000000..5ecf126 --- /dev/null +++ b/tests/access/fake_access_server.py @@ -0,0 +1,225 @@ +"""A stand-in for the admin's connection: canned rows for each statement in `sql/live.sql`. + +`FakeServer.hold(spec)` fills its tables with what a declaration asks for, as if the SQL +from `access validate --sql` had been run. `empty_reads` makes the first reads find no user, +role, grant or membership, as a replica that is behind would. + +For `access apply` it answers `currentUser()` with `login` and records every write in +`writes`. A write whose SQL contains a key of `failing` raises that message, and after any +other write the server holds `converges_to`, when that is set. + +For `access check` it records each `CHECK GRANT` in `checks`, and answers 0 for one that +contains an entry of `lacking`, else 1. + +It answers `hostName()` with `node`, or refuses it when `node` is None. That isn't a read of +access, so it isn't recorded in `reads`. + +Where users and roles are replicated, the reader reads every replica at once (design note, +2.5). `clusters` are the clusters that hold this node, each with its hosts, as +`system.clusters` lists them, and `replicas` are the replicas each read reaches. Each +replica holds the same tables, except that one named in `behind` shows nothing for that +many reads. With `replica_error` set, every read of every replica fails with that message. +A read of a table on every replica is recorded in `reads` under the table's own name, as one +read, and its parameters and settings in `replica_parameters` and `replica_settings`. + +The admin's own grants are `own_grants`, `ALL ON *.* WITH GRANT OPTION` unless a test sets +them. With none, its `CHECK GRANT CLUSTER` still answering 1 is a server that grants CLUSTER +to every login, as ClickHouse Cloud does. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass + +from clickhouse_connect.driver.exceptions import DatabaseError + +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.privileges import BUNDLED_LIST, bundled_tree +from ch_migrate.access.templates import statement + +STATEMENTS = ( + "privileges", + "storage", + "roles", + "users", + "grants", + "role_grants", + "accepted_sources", + "own_grants", + "clusters", + "replicas", + "replica_roles", + "replica_users", + "replica_grants", + "replica_role_grants", +) +ENTITY_TABLES = ("roles", "users", "grants", "role_grants") + + +@dataclass(frozen=True) +class Written: + """One statement `apply` sent: its SQL, bound parameters and settings.""" + + sql: str + parameters: dict + settings: dict + + +class FakeServer: + """Answers the reader's queries from tables of rows, as the system tables would.""" + + server_version = "26.3.1.1" + + def __init__(self, storage="replicated"): + self.storage = storage # None: the login can't read system.user_directories + self.tables = {name: [] for name in ENTITY_TABLES} + self.sources = {"REMOTE", "S3"} + self.empty_reads = 0 + self.reads = [] + self.closed = False + self.login = "shop_admin" + self.writes = [] + self.raw = [] # the statements sent by raw_query + self.login_roles = [] # the roles the login apply runs as holds + self.failing = {} + self.converges_to = None + self.checks = [] + self.lacking = set() + self.node = "node-1" + self.clusters = [{"cluster": "default", "hosts": ["node-1:9000", "node-2:9000"]}] + self.replicas = ("node-1", "node-2") + self.behind = {} + self.replica_error = None + self.replica_settings = [] + self.replica_parameters = [] + self.own_grants = grant_rows(parse_grant("ALL ON *.* WITH GRANT OPTION")) + + def query(self, sql, parameters=None, settings=None): + if sql == statement("apply", "current_user"): + return _Result([{"name": self.login}]) + if sql == statement("apply", "current_roles"): + return _Result([{"name": role} for role in self.login_roles]) + if sql == statement("live", "node"): + if self.node is None: + raise DatabaseError("Code: 497. Not enough privileges. (ACCESS_DENIED)") + return _Result([{"name": self.node}]) + [name] = [name for name in STATEMENTS if statement("live", name) == sql] + if name.startswith("replica"): + return _Result(self._every_replica(name, parameters or {}, settings)) + self.reads.append(name) + return _Result(self._rows(name, parameters or {})) + + def raw_query(self, sql, parameters=None, settings=None): + """`apply` sends a statement with bound parameters, a password, this way.""" + self.raw.append(sql) + return self.command(sql, parameters, settings) + + def command(self, sql, parameters=None, settings=None): + if sql.startswith("CHECK GRANT"): + self.checks.append(sql) + return 0 if any(part in sql for part in self.lacking) else 1 + self.writes.append(Written(sql, parameters or {}, settings or {})) + for part, message in self.failing.items(): + if part in sql: + raise DatabaseError(message) + if self.converges_to is not None: + self.tables = {name: [] for name in ENTITY_TABLES} + self.hold(self.converges_to) + + def close(self): + self.closed = True + + def hold(self, spec): + """Hold everything `spec` declares: its roles, users, memberships and grants.""" + migration = spec.migration + self._add(("role", migration.role), migration.all_grants) + self._add(("user", migration.user), roles=(migration.role,)) + for role in spec.roles: + self._add(("role", role.name), role.grants, role.roles) + for user in spec.users: + self._add(("user", user.name), user.grants, user.roles) + + def _add(self, entity, grants=(), roles=()): + kind, name = entity + self.tables[f"{kind}s"].append( + {"name": name, "default_roles_all": 1, "default_roles_except": []} + ) + holder = {"user_name": None, "role_name": None, f"{kind}_name": name} + for role in roles: + self.tables["role_grants"].append( + { + **holder, + "granted_role_name": role, + "granted_role_is_default": 1, + "with_admin_option": 0, + } + ) + for grant in grants: + self.tables["grants"] += [{**holder, **row} for row in grant_rows(grant)] + + def _every_replica(self, name, parameters, settings): + self.replica_settings.append(settings) + self.replica_parameters.append(parameters) + if self.replica_error is not None: + raise DatabaseError(self.replica_error) + if name == "replicas": + return [{"replica": replica} for replica in self.replicas] + table = name.removeprefix("replica_") + self.reads.append(table) + rows = self._rows(table, parameters) + reads = self.reads.count("privileges") + return [ + {"replica": replica, **row} + for replica in self.replicas + if reads > self.behind.get(replica, 0) + for row in rows + ] + + def _rows(self, name, parameters): + if name == "own_grants": + return self.own_grants + if name == "clusters": + return self.clusters + if name == "privileges": + return json.loads(BUNDLED_LIST.read_text())["privileges"] + if name == "storage": + if self.storage is None: + raise DatabaseError("Code: 497. Not enough privileges. (ACCESS_DENIED)") + return [{"type": self.storage}] + if name == "accepted_sources": + return [{"source": s} for s in parameters["sources"] if s in self.sources] + if self.reads.count("privileges") <= self.empty_reads: + return [] # each read starts with the privilege tree + names = parameters["names"] + return [ + row + for row in self.tables[name] + if {row.get("name"), row.get("user_name"), row.get("role_name")} & set(names) + ] + + +def grant_rows(grant, **flags): + """`system.grants` rows for one grant: one per privilege, under its canonical name.""" + tree, target = bundled_tree(), grant.target + return [ + { + "access_type": tree.canonical(privilege) or privilege, + "access_object": target.source or "", + "database": target.database, + "table": target.table, + "column": None, + "is_partial_revoke": 0, + "grant_option": int(grant.grant_option), + **flags, + } + for privilege in grant.privileges + ] + + +class _Result: + def __init__(self, rows): + self._rows = rows + + def named_results(self): + return iter(self._rows) diff --git a/tests/access/test_access_file.py b/tests/access/test_access_file.py new file mode 100644 index 0000000..edc4a08 --- /dev/null +++ b/tests/access/test_access_file.py @@ -0,0 +1,538 @@ +"""access.yaml (2.3): every rule, with the text of each validation error. + +Each error names the file, the key path and the reason. `validate` lists them all. +""" + +import pytest + +from ch_migrate.access.loader import EMPTY_ACCESS_FILE, declares_access +from ch_migrate.access.model import Grant, Role, Secret, Target, User + +DESIGN_NOTE_EXAMPLE = """\ + # Desired users, roles and grants. + migration_role: + profile: core + grants: + - CREATE FUNCTION, DROP FUNCTION ON *.* + + roles: + analyst: + grants: + - SELECT, SHOW TABLES ON {db}.* + loader: + grants: + - INSERT, SELECT ON {db}.events + reporting: + roles: [analyst] + + users: + dashboards: + password: {secret: dashboards_password} + roles: [reporting] + etl: + password: {secret: etl_password} + roles: [loader] + default_roles: [loader] + grants: + - SELECT ON {db}.regions + + environments: + production: + users: + etl: {absent: true} + """ + + +def errors(result): + return [str(problem) for problem in result.errors] + + +def warnings(result): + return [str(problem) for problem in result.warnings] + + +def test_the_design_note_example_is_valid(validate): + result = validate(DESIGN_NOTE_EXAMPLE) + assert (errors(result), warnings(result)) == ([], []) + spec = result.spec + assert spec.migration.profile.name == "core" + assert spec.migration.grants == (Grant(("CREATE FUNCTION", "DROP FUNCTION"), Target()),) + assert spec.roles == ( + Role("analyst", (Grant(("SELECT", "SHOW TABLES"), Target("shop_dev")),)), + Role("loader", (Grant(("INSERT", "SELECT"), Target("shop_dev", "events")),)), + Role("reporting", roles=("analyst",)), + ) + assert spec.users == ( + User("dashboards", Secret("dashboards_password"), roles=("reporting",)), + User( + "etl", + Secret("etl_password"), + grants=(Grant(("SELECT",), Target("shop_dev", "regions")),), + roles=("loader",), + default_roles=("loader",), + ), + ) + + +def test_an_environment_block_applies_only_to_its_environment(validate): + production = validate(DESIGN_NOTE_EXAMPLE, environment="production").spec + assert [(user.name, user.absent) for user in production.users] == [ + ("dashboards", False), + ("etl", True), + ] + etl = production.users[1] + assert etl.roles == ("loader",) # the base's fields stay; absent is added + assert production.roles[0].grants[0].target == Target("shop_prod") + + +@pytest.mark.parametrize("text", ["", "# only a comment\n", "\n\n"]) +def test_an_empty_file_is_an_error(validate, text): + """It would read as core with nothing declared, though an empty + access.yaml, or one `access show ENV > access.yaml` emptied, means legacy or a lost file.""" + result = validate(text) + assert result.spec is None + assert errors(result) == [f"access.yaml: {EMPTY_ACCESS_FILE}"] + + +def test_a_file_naming_only_the_profile_declares_nothing_else(validate): + result = validate("migration_role: {profile: core}\n") + assert errors(result) == [] + assert (result.spec.roles, result.spec.users, result.spec.legacy) == ((), (), False) + assert result.spec.migration.profile.name == "core" + + +@pytest.mark.parametrize(("text", "declares"), [(None, False), ("migration_role: {}\n", True)]) +def test_declares_access_follows_validates_rule(tmp_path, text, declares): + if text is not None: + (tmp_path / "access.yaml").write_text(text) + assert declares_access(tmp_path) is declares + + +def test_declares_access_names_a_file_it_cant_read(tmp_path): + (tmp_path / "access.yaml").write_text("roles: [unclosed\n") + with pytest.raises(ValueError, match="access.yaml can't be read"): + declares_access(tmp_path) + + +def test_declares_access_refuses_an_empty_file(tmp_path): + (tmp_path / "access.yaml").write_text("# nothing\n") + with pytest.raises(ValueError, match="access.yaml is empty"): + declares_access(tmp_path) + + +def test_the_legacy_profile_can_be_chosen(validate): + result = validate("migration_role: {profile: legacy}\n") + assert result.spec.migration.profile.name == "legacy" + + +@pytest.mark.parametrize( + "text, error", + [ + ( + "grants: []\n", + "access.yaml: grants: unknown key; the keys here are " + "migration_role, roles, users or environments", + ), + ( + "roles: {analyst: {grant: []}}\n", + "access.yaml: roles.analyst.grant: unknown key; " + "the keys here are grants, roles or absent", + ), + ( + "users: {etl: {role: []}}\n", + "access.yaml: users.etl.role: unknown key; " + "the keys here are password, roles, default_roles, grants or absent", + ), + ( + "migration_role: {profiles: core}\n", + "access.yaml: migration_role.profiles: " + "unknown key; the keys here are profile or grants", + ), + ( + "roles: {a: {grants: [{grant: SELECT ON x.*, why: no}]}}\n", + "access.yaml: roles.a.grants[0].why: unknown key; the keys here are grant or best_effort", + ), + ( + "environments: {dev: {environments: {}}}\n", + "access.yaml: environments.dev.environments: " + "unknown key; the keys here are migration_role, roles or users", + ), + ], +) +def test_unknown_keys_are_errors_naming_the_key_path(validate, text, error): + assert errors(validate(text)) == [error] + + +@pytest.mark.parametrize( + "text, error", + [ + ("- roles\n", "access.yaml: expected a mapping, found a list"), + ("roles: [analyst]\n", "access.yaml: roles: expected a mapping of names, found a list"), + ("roles: {a: [SELECT ON x.*]}\n", "access.yaml: roles.a: expected a mapping, found a list"), + ( + "roles: {a: {grants: SELECT ON x.*}}\n", + "access.yaml: roles.a.grants: expected a list of grants, found a string", + ), + ( + "roles: {a: {grants: [3]}}\n", + "access.yaml: roles.a.grants[0]: " + "expected a grant or {grant: ..., best_effort: true}, found a number", + ), + ( + "roles: {a: {grants: [{best_effort: true}]}}\n", + "access.yaml: roles.a.grants[0].grant: expected the grant as a string", + ), + ( + "roles: {a: {grants: [{grant: CLUSTER ON *.*, best_effort: maybe}]}}\n", + "access.yaml: roles.a.grants[0].best_effort: expected true or false, found a string", + ), + ( + "roles: {a: {roles: reporting}}\n", + "access.yaml: roles.a.roles: expected a list of role names, found a string", + ), + ( + "roles: {a: {absent: 1}}\n", + "access.yaml: roles.a.absent: expected true or false, found a number", + ), + ( + "environments: [dev]\n", + "access.yaml: environments: expected a mapping of environments, found a list", + ), + ], +) +def test_values_of_the_wrong_shape_are_errors(validate, text, error): + assert errors(validate(text)) == [error] + + +def test_every_error_is_listed(validate): + result = validate( + """\ + roles: + a: {grant: []} + b: {grants: [SELECT ON x.t*]} + users: + c: {password: hunter2} + """ + ) + assert errors(result) == [ + "access.yaml: roles.a.grant: unknown key; the keys here are grants, roles or absent", + "access.yaml: roles.b.grants[0]: `SELECT ON x.t*`: " + "prefix targets such as `x.t*` aren't supported in v1", + "access.yaml: users.c.password: expected {secret: NAME}; access.yaml never holds a password", + ] + assert result.spec is None + + +def test_invalid_yaml_names_the_line(validate): + result = validate("roles:\n a: {grants: [SELECT ON {db}.*]}\n") + [error] = errors(result) + assert error.startswith("access.yaml: line 2, column ") + assert "not valid YAML" in error + + +def test_grants_and_best_effort_entries(validate): + result = validate( + """\ + roles: + ops: + grants: + - DELETE ON {db}.events WITH GRANT OPTION + - {grant: CLUSTER ON *.*, best_effort: true} + - {grant: "SELECT ON system.parts"} + """ + ) + assert result.spec.roles[0].grants == ( + Grant(("ALTER DELETE",), Target("shop_dev", "events"), grant_option=True), + Grant(("CLUSTER",), Target(), best_effort=True), + Grant(("SELECT",), Target("system", "parts")), + ) + + +def test_grant_errors_quote_the_grant_as_written(validate): + result = validate("roles: {a: {grants: [REMOTE ON *.*, 'SELECT(id) ON {db}.t']}}\n") + assert errors(result) == [ + "access.yaml: roles.a.grants[0]: `REMOTE ON *.*`: " + "this is the old spelling of a source grant: write `READ, WRITE ON REMOTE`", + "access.yaml: roles.a.grants[1]: `SELECT(id) ON {db}.t`: " + "column grants, such as SELECT(id), aren't supported in v1", + ] + + +def test_unknown_privilege_names_are_warnings(validate): + result = validate("roles: {a: {grants: ['SELEKT ON {db}.*']}}\n") + assert errors(result) == [] + assert warnings(result) == [ + "access.yaml: roles.a.grants[0]: `SELEKT ON {db}.*`: ClickHouse 26.3 has no privilege " + "named SELEKT; `access plan` checks it on the server" + ] + assert result.spec.roles[0].grants[0].privileges == ("SELEKT",) + + +def test_placeholders_are_rendered_in_names_and_targets(validate): + result = validate( + """\ + roles: + '{project}_{env}_reader': + grants: ['SELECT ON {db}.*'] + users: + ci: + password: {secret: ci_password} + roles: ['{migration_role}', '{project}_{env}_reader'] + """ + ) + assert errors(result) == [] + assert result.spec.roles[0] == Role( + "shop_dev_reader", (Grant(("SELECT",), Target("shop_dev")),) + ) + assert result.spec.users[0].roles == ("shop_migration_role", "shop_dev_reader") + + +def test_an_unknown_placeholder_is_an_error(validate): + result = validate("roles: {'{team}_reader': {}}\n") + assert errors(result) == [ + "access.yaml: roles.{team}_reader: unknown placeholder {team}; " + "the placeholders are {db}, {project}, {env} or {migration_role}" + ] + + +@pytest.mark.parametrize( + "text, error", + [ + ( + "roles: {my-role: {}}\n", + "access.yaml: roles.my-role: Invalid name: 'my-role'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ( + "users: {u: {roles: ['{env}-x']}}\n", + "access.yaml: users.u.roles[0]: Invalid name: 'dev-x'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ( + "users: {u: {roles: [{project}]}}\n", + "access.yaml: users.u.roles[0]: found a mapping: " + "quote a name that starts with {, as in '{db}_x'", + ), + ( + "users: {u: {roles: [3]}}\n", + "access.yaml: users.u.roles[0]: expected a name, found a number", + ), + ], +) +def test_every_rendered_name_must_be_a_valid_identifier(validate, text, error): + assert error in errors(validate(text)) + + +def test_two_names_that_render_the_same_are_an_error(validate): + result = validate("roles: {'{project}_r': {}, shop_r: {}}\n") + assert errors(result) == ["access.yaml: roles.shop_r: declares shop_r a second time"] + + +@pytest.mark.parametrize( + "password, error", + [ + ("hunter2", "expected {secret: NAME}; access.yaml never holds a password"), + ("{secret: x, path: y}", "expected {secret: NAME}; access.yaml never holds a password"), + ("{ssm: /a/b}", "expected {secret: NAME}; access.yaml never holds a password"), + ], +) +def test_a_password_is_only_ever_a_named_secret(validate, password, error): + result = validate(f"users: {{etl: {{password: {password}}}}}\n") + assert errors(result) == [f"access.yaml: users.etl.password: {error}"] + + +def test_a_secret_name_must_be_an_identifier(validate): + result = validate("users: {etl: {password: {secret: etl-password}}}\n") + assert errors(result) == [ + "access.yaml: users.etl.password.secret: Invalid name: 'etl-password'. " + "Must start with letter/underscore and contain only alphanumeric/underscore." + ] + + +def test_one_direction_of_a_source_is_a_warning(validate): + """Decision 12. Both directions in two entries are one grant; core's READ ON REMOTE isn't + the user's to change, so the design note's example, on core, warns about nothing.""" + result = validate( + """\ + migration_role: {grants: ['WRITE ON *.*']} + roles: + reader: {grants: [READ ON S3, READ ON REMOTE, {grant: WRITE ON REMOTE, best_effort: true}]} + """ + ) + assert errors(result) == [] + setting = ( + "which the server keeps only with access_control_improvements.enable_read_write_grants " + "on. With it off, ClickHouse's default, it holds READ and WRITE on {} together, and " + "`plan` compares them as one grant." + ) + assert warnings(result) == [ + f"access.yaml: migration_role.grants: `WRITE ON *.*` gives WRITE alone, {setting.format('*.*')}", + f"access.yaml: roles.reader.grants: `READ ON S3` gives READ alone, {setting.format('S3')}", + ] + + +def test_a_user_without_a_password_is_a_warning(validate): + result = validate("users: {etl: {roles: [loader]}, old: {absent: true}}\n") + assert errors(result) == [] + assert warnings(result) == [ + "access.yaml: users.etl: no password, so it is never created and must already exist. " + "Set `password: {secret: NAME}` to have it created." + ] + + +def test_memberships_on_users_and_roles(validate): + result = validate( + """\ + roles: + reporting: {roles: [analyst, finance]} + users: + viewer: {password: {secret: viewer_password}, roles: [reporting]} + """ + ) + assert errors(result) == [] # analyst and finance aren't declared: `plan` checks the server + assert result.spec.roles[0].roles == ("analyst", "finance") + assert result.spec.users[0].default_roles is None # every membership is a default role + + +def test_default_roles_must_be_among_the_users_roles(validate): + result = validate( + """\ + users: + etl: {password: {secret: p}, roles: [loader], default_roles: [loader, auditor, ops]} + ci: {password: {secret: p}, default_roles: [loader]} + """ + ) + assert errors(result) == [ + "access.yaml: users.etl.default_roles: auditor, ops aren't in roles", + "access.yaml: users.ci.default_roles: loader isn't in roles", + ] + + +def test_an_empty_default_roles_list_means_none(validate): + result = validate("users: {etl: {password: {secret: p}, roles: [a], default_roles: []}}\n") + assert result.spec.users[0].default_roles == () + + +def test_nothing_may_hold_a_role_declared_absent(validate): + result = validate( + """\ + roles: + old: {absent: true} + new: {roles: [old]} + users: + etl: {password: {secret: p}, roles: [old]} + gone: {absent: true, roles: [old]} + """ + ) + assert errors(result) == [ + "access.yaml: roles.new.roles: old is declared absent, so nothing can hold it", + "access.yaml: users.etl.roles: old is declared absent, so nothing can hold it", + ] + + +def test_absent_marks_a_user_or_role_to_drop(validate): + result = validate("roles: {old: {absent: true}}\nusers: {gone: {absent: true}}\n") + assert result.spec.roles == (Role("old", absent=True),) + assert result.spec.users == (User("gone", absent=True),) + + +def test_environment_blocks_deep_merge_mappings_and_replace_lists(validate): + text = """\ + roles: + analyst: {grants: ['SELECT ON {db}.*'], roles: [base]} + environments: + dev: + roles: + analyst: {grants: ['SELECT ON {db}.events']} + extra: {} + """ + result = validate(text) + analyst, extra = result.spec.roles + assert analyst.grants == (Grant(("SELECT",), Target("shop_dev", "events")),) # replaced + assert analyst.roles == ("base",) # kept: the block didn't set it + assert extra == Role("extra") + assert validate(text, environment="production").spec.roles == ( + Role("analyst", (Grant(("SELECT",), Target("shop_prod")),), roles=("base",)), + ) + + +def test_absent_in_an_environment_block_drops_only_there(validate): + text = "users:\n etl: {password: {secret: p}}\nenvironments:\n dev:\n users: {etl: {absent: true}}\n" + assert validate(text).spec.users[0].absent + assert not validate(text, environment="production").spec.users[0].absent + + +def test_the_migration_role_can_change_per_environment(validate): + text = ( + "migration_role: {grants: [CREATE FUNCTION ON *.*]}\n" + "environments: {dev: {migration_role: {profile: legacy}}}\n" + ) + dev = validate(text).spec.migration + assert (dev.profile.name, dev.grants) == ("legacy", (Grant(("CREATE FUNCTION",), Target()),)) + assert validate(text, environment="production").spec.migration.profile.name == "core" + + +def test_an_environment_config_yaml_lacks_is_an_error(validate): + result = validate("environments: {prod: {users: {}}}\n") + assert errors(result) == [ + "access.yaml: environments.prod: config.yaml has no environment named prod" + ] + + +def test_errors_in_another_environments_block_are_still_reported(validate): + result = validate("environments: {production: {roles: {a: {grant: []}}}}\n") + assert errors(result) == [ + "access.yaml: environments.production.roles.a.grant: " + "unknown key; the keys here are grants, roles or absent" + ] + + +def test_an_unknown_profile_is_an_error(validate): + result = validate("migration_role: {profile: full}\n") + assert errors(result) == [ + "access.yaml: migration_role.profile: unknown profile 'full'; the profiles are core and legacy" + ] + + +@pytest.mark.parametrize( + "text, error", + [ + ( + "roles: {shop_migration_role: {}}\n", + "access.yaml: roles.shop_migration_role: " + "this is the migration role: add its grants under migration_role.grants", + ), + ( + "roles: {'{migration_role}': {absent: true}}\n", + "access.yaml: roles.{migration_role}: " + "this is the migration role: add its grants under migration_role.grants", + ), + ( + "users: {shop_migrator: {}}\n", + "access.yaml: users.shop_migrator: " + "this is the migration user, which `bootstrap` manages", + ), + ( + "users: {shop_admin: {}}\n", + "access.yaml: users.shop_admin: " + "this is config.yaml's admin_user, which ch-migrate never changes", + ), + ], +) +def test_the_migration_identity_and_the_admin_cannot_be_declared(validate, text, error): + assert errors(validate(text)) == [error] + + +def test_an_error_after_a_merge_names_the_environment_block(validate): + text = ( + "users:\n etl: {password: {secret: p}, roles: [a], default_roles: [a]}\n" + "environments:\n dev:\n users: {etl: {roles: [b]}}\n" + ) + assert errors(validate(text)) == ["access.yaml: users.etl.default_roles: a isn't in roles"] + assert errors(validate(text.replace("default_roles: [a]", ""))) == [] + moved = text.replace("default_roles: [a]}", "}").replace( + "roles: [b]}", "roles: [b], default_roles: [a]}" + ) + assert errors(validate(moved)) == [ + "access.yaml: environments.dev.users.etl.default_roles: a isn't in roles" + ] diff --git a/tests/access/test_access_live.py b/tests/access/test_access_live.py new file mode 100644 index 0000000..09528fc --- /dev/null +++ b/tests/access/test_access_live.py @@ -0,0 +1,329 @@ +"""The live reader without a server: one read, reads after writes, and the version floor. + +`FakeServer` answers the statements in `sql/live.sql` from tables of rows. +""" + +import time + +import pytest +import yaml +from fake_access_server import FakeServer, grant_rows + +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.live import ( + LiveState, + Membership, + Patience, + Wanted, + read_live, + read_settled, +) +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.rights import Right, Scope +from ch_migrate.access.server import ( + AccessError, + Login, + connect, + connect_admin, + require_supported_version, +) +from ch_migrate.access.settings import ProjectSettings, ServerSettings, SettingsError, load_settings + +TREE = bundled_tree() + + +def held_by(holder, text, **flags): + """`system.grants` rows for a grant held by `holder`, such as "role analyst".""" + return [{**_holder(holder), **row} for row in grant_rows(parse_grant(text), **flags)] + + +def membership(holder, role, **flags): + row = {**_holder(holder), "granted_role_name": role} + return {**row, "granted_role_is_default": 1, "with_admin_option": 0, **flags} + + +def _holder(holder): + kind, name = holder.split() + return {"user_name": None, "role_name": None, f"{kind}_name": name} + + +@pytest.fixture +def live(): + """One read of a server with a role, two users it was asked about, and one it wasn't.""" + server = FakeServer(storage="local_directory") + server.tables["roles"] = [{"name": "analyst"}] + server.tables["users"] = [ + {"name": "etl", "default_roles_all": 0, "default_roles_except": []}, + {"name": "analyst", "default_roles_all": 1, "default_roles_except": ["loader"]}, + {"name": "stranger", "default_roles_all": 1, "default_roles_except": []}, + ] + server.tables["grants"] = [ + *held_by("role analyst", "SELECT ON d.* WITH GRANT OPTION"), + *held_by("role analyst", "SELECT ON d.secrets", is_partial_revoke=1), + *held_by("user etl", "READ ON REMOTE"), + *held_by("user stranger", "INSERT ON d.*"), + ] + server.tables["role_grants"] = [ + membership("user etl", "loader", granted_role_is_default=0), + membership("user etl", "analyst", with_admin_option=1), + membership("user stranger", "analyst"), + ] + state = read_live(server, Wanted(("analyst", "etl", "nobody"), ("REMOTE", "NOWHERE"))) + assert "storage" in server.reads and server.reads.count("grants") == 1 + return state + + +def test_one_read_finds_the_users_and_roles_asked_about(live): + assert (live.storage, live.may_lag, live.sources) == ("local_directory", False, {"REMOTE"}) + assert (set(live.roles), set(live.users)) == ({"analyst"}, {"etl", "analyst"}) + assert live.find("role", "nobody") is None and live.find("user", "stranger") is None + + +def test_one_read_sorts_the_rows_by_user_and_role(live): + role = live.find("role", "analyst") + assert role.holdings.holds(Right("SELECT", Scope("d", "events"), True)) + assert not role.holdings.holds(Right("SELECT", Scope("d", "secrets"))) + user = live.find("user", "etl") + assert user.holdings.holds(Right("READ", Scope(source="REMOTE"))) + assert user.memberships == ( + Membership("analyst", default=True, admin_option=True), + Membership("loader", default=False), + ) + assert (user.default_all, live.find("user", "analyst").default_except) == (False, ("loader",)) + + +def test_no_source_is_asked_about_when_none_is_declared(): + server = FakeServer() + assert read_live(server, Wanted(("analyst",))).sources == frozenset() + assert "accepted_sources" not in server.reads + + +@pytest.mark.parametrize( + ("storage", "may_lag"), + [("local_directory", False), ("replicated", True), ("memory", True), (None, True)], +) +def test_only_a_nodes_own_disk_is_never_behind(storage, may_lag): + """Keeper, a storage the reader doesn't know, and one it can't read may all be behind.""" + live = read_live(FakeServer(storage=storage), Wanted(())) + assert (live.storage, live.may_lag) == (storage, may_lag) + + +def test_a_server_error_while_reading_is_an_access_error(): + """Such as a login that can't read `system.grants`: the server's own first line.""" + with pytest.raises(AccessError, match="Not enough privileges"): + read_live(_Denied(), Wanted(("analyst",))) + + +class _Denied(FakeServer): + def _rows(self, name, parameters): + from clickhouse_connect.driver.exceptions import DatabaseError + + if name == "grants": + raise DatabaseError( + "Code: 497. DB::Exception: admin: Not enough privileges. To execute this query, " + "it's necessary to have the grant SELECT ON system.grants. (ACCESS_DENIED) " + "(version 26.3.62.3 (official build))" + ) + return super()._rows(name, parameters) + + +class _Reads: + """A reader that is unsettled for its first `empty` reads; `waits` records each sleep. + + Its clock, `now`, moves on with each sleep, and by `read_seconds` with each read. + """ + + def __init__(self, empty, storage="replicated", read_seconds=0.0): + self.empty, self.storage, self.count, self.waits, self.notices = empty, storage, 0, [], [] + self.now, self.read_seconds = 0.0, read_seconds + + def read(self): + self.count += 1 + self.now += self.read_seconds + return LiveState(TREE, self.storage) + + def sleep(self, seconds): + self.waits.append(seconds) + self.now += seconds + + def unsettled(self, state): + return self.count <= self.empty + + def patience(self, seconds=30.0): + return Patience( + seconds=seconds, sleep=self.sleep, clock=lambda: self.now, on_wait=self.notices.append + ) + + +def test_a_settled_read_is_not_repeated(): + reads = _Reads(empty=0) + read_settled(reads.read, reads.unsettled, reads.patience()) + assert (reads.count, reads.waits, reads.notices) == (1, [], []) + + +def test_an_unsettled_read_is_repeated_with_waits_that_double(): + reads = _Reads(empty=8) + read_settled(reads.read, reads.unsettled, reads.patience()) + assert reads.count == 9 + assert reads.waits == [0.05, 0.1, 0.2, 0.4, 0.8, 1.6, 2.0, 2.0] + assert reads.notices == [30.0], "the wait is announced once" + + +def test_reading_stops_at_the_time_limit(): + reads = _Reads(empty=1000) + read_settled(reads.read, reads.unsettled, reads.patience(seconds=1.0)) + assert reads.waits == [0.05, 0.1, 0.2, 0.4, pytest.approx(0.25)] + assert sum(reads.waits) == pytest.approx(1.0) and reads.count == 6 + + +def test_the_time_limit_counts_the_time_reads_take(): + """A 1 s limit with 5 s reads took 31 s when only the waits counted. Now it takes 5 s.""" + reads = _Reads(empty=1000, read_seconds=5.0) + read_settled(reads.read, reads.unsettled, reads.patience(seconds=1.0)) + assert (reads.count, reads.waits, reads.notices, reads.now) == (1, [], [], 5.0) + + +def test_slow_reads_stop_once_the_deadline_has_passed(): + """With 0.3 s reads and a 1 s limit, the third read starts at 0.75 s and is the last.""" + reads = _Reads(empty=1000, read_seconds=0.3) + read_settled(reads.read, reads.unsettled, reads.patience(seconds=1.0)) + assert (reads.count, reads.waits) == (3, [0.05, 0.1]) + assert reads.now == pytest.approx(1.05) + + +def test_the_time_limit_is_measured_on_the_monotonic_clock(): + """Not wall time, which can jump.""" + assert Patience().clock is time.monotonic + + +@pytest.mark.parametrize(("seconds", "storage"), [(0, "replicated"), (30, "local_directory")]) +def test_no_time_limit_or_a_nodes_own_disk_reads_once(seconds, storage): + reads = _Reads(empty=1000, storage=storage) + read_settled(reads.read, reads.unsettled, reads.patience(seconds=seconds)) + assert (reads.count, reads.waits) == (1, []) + + +@pytest.mark.parametrize("version", ["25.8.1.1", "25.8.33.6", "25.10.2.3", "26.3.62.3", "100.1.1"]) +def test_25_8_and_later_are_supported(version): + require_supported_version(version) + + +@pytest.mark.parametrize("version", ["24.8.14.39", "25.7.9.9", "25.3.1", "9.10.1.1"]) +def test_an_older_server_is_refused_by_its_version(version): + """Compared as numbers: 25.10 is later than 25.8, and 9.10 is earlier.""" + with pytest.raises(AccessError) as refused: + require_supported_version(version) + assert str(refused.value) == ( + f"The server runs ClickHouse {version}. " + "`bootstrap` and the `access` commands that connect need 25.8 or later." + ) + + +def test_a_version_that_cannot_be_read_is_refused(): + with pytest.raises(AccessError, match="Can't read the server's version from 'unknown'"): + require_supported_version("unknown") + + +def settings(**server): + return ProjectSettings( + environment="dev", + database="shop_dev", + project="shop", + migration_user="shop_migrator", + admin_user="shop_admin", + server=ServerSettings(**server), + ) + + +def test_connecting_resolves_only_the_login_secret_and_checks_the_version(monkeypatch): + import clickhouse_connect + + calls = [] + + def get_client(**kwargs): + calls.append(kwargs) + return FakeServer() + + monkeypatch.setattr(clickhouse_connect, "get_client", get_client) + monkeypatch.setenv("CH_DEV_ADMIN_PASSWORD", "admin-secret") + monkeypatch.delenv("CH_DEV_MIGRATION_PASSWORD", raising=False) + connect_admin(settings(host="db.example", secure=False)) + connect(settings(host="db.example", port=9440), Login("shop_migrator", "admin_password")) + assert [(call["host"], call["port"], call["username"], call["secure"]) for call in calls] == [ + ("db.example", 8123, "shop_admin", False), + ("db.example", 9440, "shop_migrator", True), + ] + assert {call["password"] for call in calls} == {"admin-secret"} + + monkeypatch.setattr(FakeServer, "server_version", "24.8.14.39") + with pytest.raises(AccessError, match="The server runs ClickHouse 24.8.14.39"): + connect_admin(settings(host="db.example")) + + +def test_connecting_needs_a_host_and_the_secret(monkeypatch): + monkeypatch.delenv("CH_DEV_ADMIN_PASSWORD", raising=False) + with pytest.raises(AccessError, match="host is required in config.yaml for environment 'dev'"): + connect_admin(settings()) + with pytest.raises(AccessError, match="CH_DEV_ADMIN_PASSWORD is required"): + connect_admin(settings(host="db.example")) + + +def write_config(tmp_path, **environment): + config = { + "project": {"name": "shop"}, + "defaults": {"secure": False, "aws_region": "eu-west-1"}, + "environments": {"dev": {"database": "shop_dev", "migration_user": "m", **environment}}, + } + path = tmp_path / "config.yaml" + path.write_text(yaml.safe_dump(config)) + return path + + +def test_settings_read_the_server_keys_with_no_secret(tmp_path): + path = write_config(tmp_path, host="db.example", port=8124, cluster="main") + assert load_settings("dev", path).server == ServerSettings( + host="db.example", + port=8124, + secure=False, + cluster="main", + aws_region="eu-west-1", + read_timeout=30.0, + ) + assert load_settings("dev", write_config(tmp_path)).server.host is None + timed = load_settings("dev", write_config(tmp_path, access_read_timeout=1.5)) + assert timed.server.read_timeout == 1.5 + + +@pytest.mark.parametrize( + "value", + [ + "soon", + -1, + True, + None, + float("inf"), + float("nan"), + pytest.param(int("9" * 400), id="400-digits"), + ], +) +def test_the_read_timeout_must_be_seconds(tmp_path, value): + """`.inf` and `.nan` in YAML are floats, but no number of seconds. Neither is an integer + too large for a float, which would raise OverflowError where seconds are counted.""" + with pytest.raises(SettingsError) as error: + load_settings("dev", write_config(tmp_path, access_read_timeout=value)) + assert str(error.value) == ( + "access_read_timeout in config.yaml must be a number of seconds, 0 or more" + ) + + +@pytest.mark.parametrize("value", [None, "main", "it's a cluster"]) +def test_the_cluster_is_kept_as_written(tmp_path, value): + """Its characters aren't checked, because the SQL that names it quotes it.""" + assert load_settings("dev", write_config(tmp_path, cluster=value)).server.cluster == value + + +@pytest.mark.parametrize("value", [8123, True, False, 0, [], ["main"], {"name": "main"}]) +def test_the_cluster_must_be_a_string(tmp_path, value): + with pytest.raises(SettingsError) as error: + load_settings("dev", write_config(tmp_path, cluster=value)) + assert str(error.value) == "cluster in config.yaml must be a string" diff --git a/tests/access/test_access_planner.py b/tests/access/test_access_planner.py new file mode 100644 index 0000000..29b011c --- /dev/null +++ b/tests/access/test_access_planner.py @@ -0,0 +1,467 @@ +"""The planner: one declaration and one read of the server in, the plan's lines out. + +No server here: each test builds what the server holds by hand, on the bundled 26.3 +privilege tree. `tests/integration/test_access_plan.py` runs the same rules on Docker. +""" + +from dataclasses import replace + +import pytest + +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.live import LiveEntity, LiveState, Membership +from ch_migrate.access.planner import build_plan, wanted +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.rights import Holdings, Scope, StoredRow + +TREE = bundled_tree() +MIGRATION_ROLE, MIGRATION_USER = "shop_migration_role", "shop_migrator" + + +def holding(*grants, roles=(), revoked=()): + """A user or role that holds these grants, partial revokes and roles.""" + rows = [flag_row for grant in grants for flag_row in stored(grant)] + rows += [flag_row for grant in revoked for flag_row in stored(grant, revoke=True)] + memberships = tuple( + role if isinstance(role, Membership) else Membership(role) for role in roles + ) + return LiveEntity(Holdings(tuple(rows)), memberships) + + +def stored(text, revoke=False): + grant = parse_grant(text) + scope = Scope.of(grant.target) + flags = [ + flag for name in grant.privileges for flag in TREE.flags(TREE.canonical(name), scope.kind) + ] + return [StoredRow(flag, scope, grant.grant_option, revoke) for flag in sorted(flags)] + + +def server(spec, roles=None, users=None): + """A server whose migration role and user match `spec`, plus these roles and users.""" + migration = spec.migration + in_sync = holding(*(str(grant) for grant in migration.all_grants)) + return LiveState( + TREE, + "local_directory", + {migration.user: holding(roles=(migration.role,)), **(users or {})}, + {migration.role: in_sync, **(roles or {})}, + frozenset({"REMOTE"}), + ) + + +def lines(plan): + return [f"{change.marker} {change}" for change in plan.changes] + + +def planned(validate, text, **held): + spec = validate(text).spec + return build_plan(spec, server(spec, **held)) + + +ROLE = "roles: {analyst: {grants: ['SELECT, SHOW TABLES ON {db}.*']}}" + + +def test_in_sync_has_no_lines_and_exits_0(validate): + held = holding("SHOW TABLES ON shop_dev.*", "SELECT ON shop_dev.* ") + plan = planned(validate, ROLE, roles={"analyst": held}) + assert (lines(plan), plan.shortfalls, plan.errors) == ([], (), ()) + assert (plan.exit_code, plan.missing_rows) == (0, False) + + +def test_nothing_on_the_server_is_all_creates_and_grants_in_apply_order(validate): + spec = validate( + """\ + roles: + analyst: {grants: ['SELECT ON {db}.*']} + reporting: {roles: [analyst]} + users: + etl: + password: {secret: etl_password} + roles: [reporting, analyst] + default_roles: [reporting] + grants: ['INSERT ON {db}.events'] + """ + ).spec + plan = build_plan(spec, LiveState(TREE, sources=frozenset({"REMOTE"}))) + assert [line for line in lines(plan) if MIGRATION_ROLE not in line] == [ + "+ create role analyst", + "+ create role reporting", + "+ create user shop_migrator", + "+ create user etl", + "+ grant role analyst to role reporting", + "+ grant role reporting to user etl", + "+ grant role analyst to user etl", + "+ grant SELECT ON shop_dev.* to role analyst", + "+ grant INSERT ON shop_dev.events to user etl", + "+ set the default roles of user etl to reporting", + ] + assert lines(plan)[0] == f"+ create role {MIGRATION_ROLE}" + assert (plan.exit_code, plan.missing_rows) == (1, True) + assert len(plan.pending) == len(plan.changes) + + +def test_other_flags_on_the_same_scope_are_one_revoke(validate): + held = holding("SELECT, SHOW TABLES, INSERT, ALTER UPDATE ON shop_dev.*") + plan = planned(validate, ROLE, roles={"analyst": held}) + assert lines(plan) == [ + "~ adopt role analyst: it exists on the server, and access.yaml now manages it", + "- revoke ALTER UPDATE, INSERT ON shop_dev.* from role analyst", + ] + assert (plan.exit_code, plan.missing_rows) == (1, False) + + +def test_narrowing_a_privilege_revokes_the_other_leaves(validate): + text = "roles: {editor: {grants: ['ALTER UPDATE ON {db}.*']}}" + plan = planned(validate, text, roles={"editor": holding("ALTER ON shop_dev.*")}) + [_, revoke] = plan.changes + assert revoke.action == "revoke" and revoke.grant.target.database == "shop_dev" + assert "ALTER" not in revoke.grant.privileges + assert "ALTER UPDATE" not in revoke.grant.privileges + assert "ALTER DELETE" in revoke.grant.privileges + + +def test_an_option_that_is_not_declared_is_revoked_alone(validate): + held = holding("SELECT, SHOW TABLES ON shop_dev.* WITH GRANT OPTION") + plan = planned(validate, ROLE, roles={"analyst": held}) + assert lines(plan)[1:] == [ + "- revoke the grant option for SELECT, SHOW TABLES ON shop_dev.* from role analyst" + ] + + +def test_a_missing_option_is_granted(validate): + text = "roles: {analyst: {grants: ['SELECT ON {db}.* WITH GRANT OPTION']}}" + plan = planned(validate, text, roles={"analyst": holding("SELECT ON shop_dev.*")}) + assert lines(plan)[1:] == ["+ grant SELECT ON shop_dev.* WITH GRANT OPTION to role analyst"] + + +@pytest.mark.parametrize( + ("declared", "held", "instead_of"), + [ + ( + "SELECT ON {db}.events", + ["SELECT ON shop_dev.*"], + "revoke SELECT ON shop_dev.* from role r", + ), + ( + "SELECT ON {db}.*", + ["SELECT ON *.*"], + "revoke SELECT ON *.* from role r", + ), + ( + "READ ON REMOTE", + ["READ ON *.*"], + "revoke READ ON *.* from role r", + ), + ( + "SELECT ON {db}.events WITH GRANT OPTION", + ["SELECT ON shop_dev.* WITH GRANT OPTION"], + "revoke SELECT ON shop_dev.* from role r", + ), + ], +) +def test_narrowing_a_scope_is_one_replace(validate, declared, held, instead_of): + """The broader grant absorbs the narrower one, so it can't be a grant and a revoke.""" + plan = planned( + validate, f"roles: {{r: {{grants: ['{declared}']}}}}", roles={"r": holding(*held)} + ) + assert lines(plan)[1:] == [ + "- replace the grants of role r with its declared set in one statement, " + f"instead of: {instead_of}" + ] + [replace] = plan.pending + assert [change.action for change in replace.covers] == ["revoke"] + + +def test_an_option_on_a_broader_scope_than_a_declared_option_is_a_replace(validate): + """Revoking the option on `db.*` would take the declared option on `db.events` too.""" + text = "roles: {r: {grants: ['SELECT ON {db}.*', 'SELECT ON {db}.events WITH GRANT OPTION']}}" + held = holding("SELECT ON shop_dev.* WITH GRANT OPTION") + plan = planned(validate, text, roles={"r": held}) + assert lines(plan)[1:] == [ + "- replace the grants of role r with its declared set in one statement, instead of: " + "revoke the grant option for SELECT ON shop_dev.* from role r" + ] + + +def test_a_replace_covers_the_grants_it_makes_and_everything_it_takes_away(validate): + text = "roles: {r: {grants: ['SELECT ON {db}.events', 'INSERT ON {db}.events']}}" + held = holding("SELECT, SHOW TABLES ON shop_dev.*", "CREATE ROLE ON *.*") + plan = planned(validate, text, roles={"r": held}) + assert lines(plan)[1:] == [ + "- replace the grants of role r with its declared set in one statement, instead of: " + "grant INSERT ON shop_dev.events to role r; " + "revoke CREATE ROLE ON *.* from role r; " + "revoke SELECT, SHOW TABLES ON shop_dev.* from role r" + ] + assert plan.missing_rows, "the grant it covers is a row a replica might not have yet" + + +def test_a_partial_revoke_inside_a_declared_grant_is_granted_again(validate): + held = holding("SELECT, SHOW TABLES ON shop_dev.*", revoked=["SELECT ON shop_dev.secrets"]) + plan = planned(validate, ROLE, roles={"analyst": held}) + assert lines(plan)[1:] == ["+ grant SELECT ON shop_dev.* to role analyst"] + + +def test_a_column_grant_is_narrower_than_its_table_and_revoked_by_column(validate): + text = "roles: {r: {grants: ['INSERT ON {db}.events']}}" + column = StoredRow("SELECT", Scope("shop_dev", "events", "id")) + held = LiveEntity(Holdings((*stored("INSERT ON shop_dev.events"), column))) + plan = planned(validate, text, roles={"r": held}) + assert lines(plan)[1:] == ["- revoke SELECT(id) ON shop_dev.events from role r"] + + +def test_memberships_are_granted_and_revoked_and_an_admin_option_is_revoked(validate): + text = """\ + roles: {a: {}, b: {}, c: {}} + users: {u: {password: {secret: p}, roles: [a, b]}} + """ + user = holding(roles=(Membership("b", admin_option=True), "c")) + plan = planned(validate, text, roles=dict.fromkeys("abc", holding()), users={"u": user}) + assert lines(plan) == [ + "~ adopt user u: it exists on the server, and access.yaml now manages it", + "+ grant role a to user u", + "- revoke role c from user u", + "- revoke the admin option for role b from user u", + ] + + +def test_a_membership_may_name_an_undeclared_role_that_the_server_has(validate): + text = "users: {u: {password: {secret: p}, roles: [outsider]}}" + plan = planned(validate, text, roles={"outsider": holding()}) + assert lines(plan) == ["+ create user u", "+ grant role outsider to user u"] + missing = planned(validate, text) + assert (missing.exit_code, missing.missing_rows) == (2, True) + assert missing.errors == ( + "user u is declared to hold role outsider, " + "which access.yaml doesn't declare and the server doesn't have.", + ) + + +def test_a_user_with_no_password_is_never_created(validate): + text = "users: {u: {grants: ['SELECT ON {db}.*']}}" + plan = planned(validate, text) + assert (plan.exit_code, plan.missing_rows, lines(plan)) == (2, True, []) + assert plan.errors == ( + "user u isn't on the server and has no password, so it can't be created. " + "Set `password: {secret: NAME}`, or create the user first.", + ) + existing = planned(validate, text, users={"u": holding("SELECT ON shop_dev.*")}) + assert (existing.exit_code, lines(existing)) == (0, []) + + +def test_absent_drops_what_exists_and_ignores_what_does_not(validate): + text = """\ + roles: {old_role: {absent: true}, never_was: {absent: true}} + users: {old_user: {absent: true}} + """ + plan = planned(validate, text, roles={"old_role": holding()}, users={"old_user": holding()}) + assert lines(plan) == ["- drop user old_user", "- drop role old_role"] + assert (plan.exit_code, plan.missing_rows) == (1, False) + + +@pytest.mark.parametrize( + ("declared", "held", "line"), + [ + # Default roles ALL: the role granted now becomes a default role by itself. + ("roles: [a, b]", holding(roles=("a",)), None), + # An explicit list: the role granted now wouldn't be a default role. + ( + "roles: [a, b]", + replace(holding(roles=("a",)), default_all=False), + "+ set the default roles of user u to all its roles", + ), + ( + "roles: [a, b], default_roles: [a]", + replace(holding(roles=("a", Membership("b", False))), default_all=False), + None, + ), + ( + "roles: [a, b], default_roles: [a]", + holding(roles=("a", "b")), + "+ set the default roles of user u to a", + ), + ( + "roles: [a], default_roles: []", + holding(roles=("a",)), + "+ set the default roles of user u to none", + ), + ("roles: [a, b]", replace(holding(roles=("a", "b")), default_except=("b",)), "ALL"), + ], +) +def test_default_roles_are_set_when_they_would_not_match(validate, declared, held, line): + text = f"roles: {{a: {{}}, b: {{}}}}\nusers: {{u: {{password: {{secret: p}}, {declared}}}}}" + plan = planned(validate, text, roles=dict.fromkeys("ab", holding()), users={"u": held}) + found = [change for change in plan.changes if change.action == "set_default_roles"] + if line == "ALL": + line = "+ set the default roles of user u to all its roles" + assert [f"{change.marker} {change}" for change in found] == ([line] if line else []) + + +def test_the_migration_role_is_added_to_and_never_revoked_or_replaced(validate): + spec = validate("migration_role: {grants: ['CREATE FUNCTION ON *.*']}").spec + live = server(spec) + held = holding( + *(str(grant) for grant in spec.migration.profile.grants if "mutations" not in str(grant)), + "SELECT ON *.*", + "INSERT ON other.* WITH GRANT OPTION", + "DROP TABLE ON shop_dev.* WITH GRANT OPTION", + roles=("helper",), + ) + plan = build_plan(spec, LiveState(TREE, None, live.users, {MIGRATION_ROLE: held}, live.sources)) + assert lines(plan) == [ + f"+ grant CREATE FUNCTION ON *.* to role {MIGRATION_ROLE}", + f"! role {MIGRATION_ROLE} holds SELECT ON *.* beyond its profile", + f"! role {MIGRATION_ROLE} holds INSERT ON other.* WITH GRANT OPTION beyond its profile", + f"! role {MIGRATION_ROLE} holds the grant option for DROP TABLE ON shop_dev.* " + "beyond its profile", + f"! role {MIGRATION_ROLE} holds role helper beyond its profile", + ] + assert [change.action for change in plan.pending] == ["grant"] + + +def test_the_nearest_row_decides_what_the_migration_role_holds(validate): + """`SELECT ON *.*`, revoked on `system.*`, granted again on the tables core needs.""" + spec = validate("{}").spec + tables = ("databases", "tables", "mutations", "dictionaries", "parts", "replicas") + held = holding( + *(str(grant) for grant in spec.migration.profile.grants), + "SELECT ON *.*", + *(f"SELECT ON system.{table}" for table in tables), + revoked=["SELECT ON system.*"], + ) + live = server(spec) + plan = build_plan(spec, LiveState(TREE, None, live.users, {MIGRATION_ROLE: held}, live.sources)) + assert (plan.exit_code, plan.shortfalls) == (0, ()) + assert lines(plan) == [f"! role {MIGRATION_ROLE} holds SELECT ON *.* beyond its profile"] + + +def test_a_best_effort_shortfall_is_a_warning_and_names_the_part_missing(validate): + spec = validate("roles: {ops: {grants: [{grant: 'CLUSTER ON *.*', best_effort: true}]}}").spec + grants = [str(grant) for grant in spec.migration.all_grants] + held = holding( + *(grant for grant in grants if "REMOTE" not in grant and "SYNC" not in grant), + "SYSTEM SYNC REPLICA ON shop_dev.*", + ) + live = server(spec, roles={"ops": holding()}) + plan = build_plan( + spec, LiveState(TREE, None, live.users, {**live.roles, MIGRATION_ROLE: held}, live.sources) + ) + assert (plan.exit_code, lines(plan), plan.missing_rows) == (0, [], False) + assert [str(shortfall) for shortfall in plan.shortfalls] == [ + f"best-effort: role {MIGRATION_ROLE} lacks SYSTEM SYNC DATABASE REPLICA ON shop_dev.*", + f"best-effort: role {MIGRATION_ROLE} lacks READ ON REMOTE", + "best-effort: role ops lacks CLUSTER ON *.*", + ] + + +def test_a_held_best_effort_grant_is_not_surplus(validate): + text = "roles: {ops: {grants: [{grant: 'CLUSTER ON *.*', best_effort: true}]}}" + plan = planned(validate, text, roles={"ops": holding("CLUSTER ON *.*")}) + assert (lines(plan), plan.shortfalls) == ([], ()) + + +@pytest.mark.parametrize( + ("declared", "held"), + [ + ("READ ON REMOTE", "READ, WRITE ON REMOTE"), + ("WRITE ON REMOTE", "READ, WRITE ON REMOTE"), + ("READ ON *.*", "READ, WRITE ON *.*"), + ("READ ON REMOTE WITH GRANT OPTION", "READ, WRITE ON REMOTE WITH GRANT OPTION"), + ], +) +def test_read_and_write_on_one_source_compare_as_one_grant(validate, declared, held): + """Decision 12: where the server keeps them together, one direction declared is in sync.""" + text = f"roles: {{reader: {{grants: ['{declared}']}}}}" + plan = planned(validate, text, roles={"reader": holding(held)}) + assert (lines(plan), plan.exit_code) == ([], 0) + + +@pytest.mark.parametrize( + ("held", "expected"), + [ + # The declared direction itself must be held; the other is never revoked. + (("WRITE ON REMOTE",), "+ grant READ ON REMOTE to role reader"), + # The other direction on another scope isn't the same grant. + (("READ ON REMOTE", "WRITE ON *.*"), "- revoke WRITE ON *.* from role reader"), + # A grant option goes with the pair, as declared. + ( + ("READ, WRITE ON REMOTE WITH GRANT OPTION",), + "- revoke the grant option for READ, WRITE ON REMOTE from role reader", + ), + ], +) +def test_the_other_direction_differs_only_where_it_isnt_the_same_grant(validate, held, expected): + text = "roles: {reader: {grants: ['READ ON REMOTE']}}" + plan = planned(validate, text, roles={"reader": holding(*held)}) + assert lines(plan) == [ + "~ adopt role reader: it exists on the server, and access.yaml now manages it", + expected, + ] + + +def test_the_migration_role_holding_both_directions_of_its_source_has_no_extra(validate): + """Core's best-effort READ ON REMOTE reads back as READ and WRITE on Keeper storage.""" + spec = validate("{}").spec + held = holding(*(str(grant) for grant in spec.migration.all_grants), "WRITE ON REMOTE") + live = server(spec) + plan = build_plan(spec, LiveState(TREE, None, live.users, {MIGRATION_ROLE: held}, live.sources)) + assert (lines(plan), plan.shortfalls, plan.exit_code) == ([], (), 0) + + +@pytest.mark.parametrize( + ("grant", "sources", "problem"), + [ + ("SELEKT ON {db}.*", ("REMOTE",), "the server has no privilege named SELEKT"), + ("READ ON KAFKA", ("REMOTE",), "the server has no data source named KAFKA"), + ( + "READ ON Distributed", + ("REMOTE", "Distributed"), + "the server stores Distributed under another name: " + "write the source's own name, in upper case, such as REMOTE", + ), + ], +) +def test_what_the_server_cannot_grant(validate, grant, sources, problem): + """Required, it is an error; best-effort, a shortfall that says why.""" + spec = validate(f"roles: {{r: {{grants: ['{grant}']}}}}").spec + rendered = spec.roles[0].grants[0] + plan = build_plan(spec, replace(server(spec), sources=frozenset(sources))) + assert (plan.exit_code, plan.errors) == (2, (f"role r: `{rendered}`: {problem}.",)) + + spec = validate(f"roles: {{r: {{grants: [{{grant: '{grant}', best_effort: true}}]}}}}").spec + plan = build_plan(spec, replace(server(spec), sources=frozenset(sources))) + assert (plan.exit_code, plan.errors) == (1, ()) + assert [str(shortfall) for shortfall in plan.shortfalls] == [ + f"best-effort: role r can't be given {rendered}: {problem}" + ] + + +def test_legacy_mode_compares_only_the_migration_role_and_user(tmp_path, settings): + """No access.yaml: the read-only and dictionary roles from config.yaml are left alone.""" + from ch_migrate.access.loader import validate_access + + legacy = replace(settings, mcp_user_name="shop_mcp", dict_reader_name="shop_dict") + spec = validate_access(legacy, tmp_path).spec + assert spec.legacy and {role.name for role in spec.roles} == { + "shop_readonly_role", + "shop_dict_role", + } + assert wanted(spec).names == (MIGRATION_ROLE, MIGRATION_USER) + plan = build_plan(spec, server(spec)) + assert (plan.exit_code, lines(plan)) == (0, []) + assert build_plan(spec, LiveState(TREE)).pending[0].action == "create_role" + + +def test_wanted_names_every_declared_user_and_role_and_each_source(validate): + spec = validate( + """\ + roles: + reader: {grants: [READ ON S3, 'SELECT ON {db}.*']} + gone: {absent: true} + users: + u: {password: {secret: p}, roles: [reader, outsider]} + """ + ).spec + assert wanted(spec).names == (MIGRATION_ROLE, MIGRATION_USER, "reader", "gone", "u", "outsider") + assert wanted(spec).sources == ("REMOTE", "S3") diff --git a/tests/access/test_access_profiles.py b/tests/access/test_access_profiles.py new file mode 100644 index 0000000..3531a86 --- /dev/null +++ b/tests/access/test_access_profiles.py @@ -0,0 +1,115 @@ +"""The built-in profiles (2.4) and legacy mode, which must match 0.8's `bootstrap`.""" + +import re + +import pytest +from click.testing import CliRunner + +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.profiles import PROFILE_DIR, load_profiles +from ch_migrate.bootstrap import build_bootstrap_sql +from ch_migrate.cli import main +from ch_migrate.sql import split_statements + +VALUES = { + "db": "shop_dev", + "project": "shop", + "env": "dev", + "migration_role": "shop_migration_role", +} +# The statements `validate --sql` must share with 0.8's `build_bootstrap_sql`. +COMPARED = re.compile(r"^(GRANT|CREATE ROLE|CREATE USER)\b") +# 0.8 quotes the password; `--sql` prints an unquoted placeholder that names the secret. +PASSWORD_0_8 = re.compile(r"IDENTIFIED BY '(?:[^'\\]|\\.|'')*'") +PLACEHOLDER = re.compile(r"IDENTIFIED BY ") + + +@pytest.fixture(scope="module") +def profiles(): + profiles, reader = load_profiles(VALUES, bundled_tree()) + assert (reader.errors, reader.warnings) == ([], []) + return profiles + + +def test_the_profiles_are_core_and_legacy_and_ship_as_yaml(): + assert sorted(path.name for path in PROFILE_DIR.glob("*.yaml")) == ["core.yaml", "legacy.yaml"] + + +def test_core_requires_the_database_rights_without_grant_option(profiles): + required = [grant for grant in profiles["core"].grants if not grant.best_effort] + on_db = { + name + for grant in required + if grant.target == Target("shop_dev") + for name in grant.privileges + } + assert on_db == { + "CREATE TABLE", "DROP TABLE", "UNDROP TABLE", "ALTER", + "CREATE VIEW", "DROP VIEW", "CREATE DICTIONARY", "DROP DICTIONARY", + "SELECT", "INSERT", "DELETE", "TRUNCATE", "OPTIMIZE", + "SHOW TABLES", "SHOW COLUMNS", "SHOW DICTIONARIES", + } # fmt: skip + system = {grant.target.table for grant in required if grant.target.database == "system"} + assert system == {"databases", "tables", "mutations", "dictionaries"} + assert not any(grant.grant_option for grant in profiles["core"].grants) + + +def test_core_makes_cluster_and_system_extras_best_effort(profiles): + best_effort = [str(grant) for grant in profiles["core"].grants if grant.best_effort] + assert best_effort == [ + "SELECT ON system.parts", + "SELECT ON system.replicas", + "SYSTEM SYNC REPLICA, SYSTEM SYNC DATABASE REPLICA ON shop_dev.*", + "CLUSTER ON *.*", + "READ ON REMOTE", + "CREATE TEMPORARY TABLE ON *.*", + ] + + +def test_profiles_keep_0_8_spelling(profiles): + """Built-in grants render as written, so legacy SQL is 0.8's SQL; DELETE stays DELETE.""" + assert ( + Grant( + ("SELECT", "INSERT", "DELETE", "TRUNCATE", "OPTIMIZE"), + Target("shop_dev"), + grant_option=True, + ) + in profiles["legacy"].grants + ) + + +@pytest.mark.parametrize("mcp", [False, True]) +@pytest.mark.parametrize("dict_reader", [False, True]) +def test_legacy_sql_matches_0_8_build_bootstrap_sql(project, mcp, dict_reader): + """The same GRANT, CREATE ROLE and CREATE USER statements, ignoring order and passwords.""" + names = { + "mcp_user_name": "shop_mcp" if mcp else None, + "dict_reader_name": "shop_dict" if dict_reader else None, + } + _set_config(project, names) + result = CliRunner().invoke(main, ["access", "validate", "dev", "--sql"]) + assert result.exit_code == 0, result.output + expected = build_bootstrap_sql( + project="shop", + db="shop_dev", + migration_user="shop_migrator", + migration_password="pw", + mcp_user_name=names["mcp_user_name"], + mcp_password="pw" if mcp else None, + dict_reader_name=names["dict_reader_name"], + dict_reader_password="pw" if dict_reader else None, + ) + assert _compared(result.stdout, PLACEHOLDER) == _compared(expected, PASSWORD_0_8) + assert len(_compared(expected, PASSWORD_0_8)) == 26 + 5 * mcp + 3 * dict_reader + + +def _set_config(project, names): + config = (project / "config.yaml").read_text() + extra = "".join(f" {key}: {value}\n" for key, value in names.items() if value) + (project / "config.yaml").write_text(config.replace(" admin_user: shop_admin\n", extra, 1)) + + +def _compared(sql, password): + statements = (" ".join(statement.sql.split()) for statement in split_statements(sql)) + return sorted(password.sub("IDENTIFIED BY ?", s) for s in statements if COMPARED.match(s)) diff --git a/tests/access/test_access_rights.py b/tests/access/test_access_rights.py new file mode 100644 index 0000000..14b5812 --- /dev/null +++ b/tests/access/test_access_rights.py @@ -0,0 +1,212 @@ +"""Rights: grants compared flag by flag, as the spike record's "The comparison" describes. + +The row shapes below are what ClickHouse 26.3 stores for each sequence of statements, read +from `system.grants` on Docker. The privilege tree is the bundled 26.3 list. +""" + +import pytest + +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.rights import ( + Holdings, + Right, + Scope, + StoredRow, + Surplus, + fold, + grant_problems, + rights_of, + stored_rows, +) + +TREE = bundled_tree() +EVERYWHERE, DB, EVENTS = Scope(), Scope("d"), Scope("d", "events") +REMOTE = Scope(source="REMOTE") + + +def row(scope, flag="SELECT", **marks): + """A stored row; `option=True` and `revoke=True` mark it.""" + return StoredRow(flag, scope, marks.get("option", False), marks.get("revoke", False)) + + +def right(scope, option=False, flag="SELECT"): + return Right(flag, scope, option) + + +@pytest.mark.parametrize( + ("outer", "inner", "contained"), + [ + (EVERYWHERE, EVENTS, True), + (EVERYWHERE, REMOTE, True), + (DB, EVENTS, True), + (DB, DB, True), + (EVENTS, DB, False), + (DB, Scope("other", "events"), False), + (EVENTS, Scope("d", "events", "id"), True), + (Scope("d", "events", "id"), EVENTS, False), + (Scope("d", "events", "id"), Scope("d", "events", "name"), False), + (REMOTE, REMOTE, True), + (REMOTE, Scope(source="S3"), False), + (REMOTE, DB, False), + (DB, REMOTE, False), + (REMOTE, EVERYWHERE, False), + ], +) +def test_a_scope_contains_what_is_inside_it(outer, inner, contained): + assert outer.contains(inner) is contained + + +def test_a_grant_means_the_flags_its_scope_allows(): + """`CREATE ON db.*` is four flags; on a table `ALTER` loses the `ALTER DATABASE` flags.""" + create = rights_of(TREE, parse_grant("CREATE ON d.*")) + assert {r.flag for r in create} == { + "CREATE DATABASE", + "CREATE TABLE", + "CREATE VIEW", + "CREATE DICTIONARY", + } + on_table = {r.flag for r in rights_of(TREE, parse_grant("ALTER ON d.events"))} + on_database = {r.flag for r in rights_of(TREE, parse_grant("ALTER ON d.*"))} + assert on_database - on_table == TREE.flags("ALTER DATABASE", "database") != frozenset() + assert rights_of(TREE, parse_grant("DELETE ON d.*")) == {right(DB, flag="ALTER DELETE")} + assert rights_of(TREE, parse_grant("READ ON REMOTE")) == {right(REMOTE, flag="READ")} + assert rights_of(TREE, parse_grant("SELEKT ON d.*")) == frozenset() + + +def test_what_the_server_would_reject_is_named(): + assert grant_problems(TREE, parse_grant("SELECT, SELEKT ON d.*")) == [ + "the server has no privilege named SELEKT" + ] + assert grant_problems(TREE, parse_grant("CREATE USER ON d.*")) == [ + "the server can't grant CREATE USER on a database" + ] + assert grant_problems(TREE, parse_grant("SELECT ON d.events")) == [] + + +def test_a_broader_grant_holds_a_narrower_right_and_an_option_holds_the_plain_right(): + """Folding cancels out: no row is stored for a grant that a broader one absorbs.""" + held = Holdings((row(DB, option=True),)) + assert held.holds(right(EVENTS)) and held.holds(right(EVENTS, option=True)) + assert not held.holds(right(EVERYWHERE)) and not held.holds(right(Scope("other"))) + plain = Holdings((row(DB),)) + assert plain.holds(right(DB)) and not plain.holds(right(DB, option=True)) + + +def test_a_partial_revoke_takes_the_right_away_inside_a_broader_grant(): + """`GRANT SELECT ON d.* WITH GRANT OPTION`, then `REVOKE SELECT ON d.events`.""" + held = Holdings((row(DB, option=True), row(EVENTS, revoke=True))) + assert not held.holds(right(EVENTS)) + assert not held.holds(right(DB)), "a hole inside it: the declared grant isn't whole" + assert held.holds(right(Scope("d", "other"), option=True)) + + +def test_revoking_only_the_grant_option_leaves_the_right(): + """`GRANT SELECT ON d.* WITH GRANT OPTION`, then `REVOKE GRANT OPTION FOR ... ON d.events`.""" + held = Holdings((row(DB, option=True), row(EVENTS, option=True, revoke=True))) + assert held.holds(right(EVENTS)) and held.holds(right(DB)) + assert not held.holds(right(EVENTS, option=True)) + assert not held.holds(right(DB, option=True)) + + +def test_the_nearest_row_decides(): + """`GRANT ON *.*`, `REVOKE ON d.*`, `GRANT ON d.events`: the table grant wins there.""" + held = Holdings((row(EVERYWHERE), row(DB, revoke=True), row(EVENTS))) + assert held.holds(right(EVENTS)) + assert not held.holds(right(Scope("d", "other"))) and not held.holds(right(DB)) + assert held.holds(right(Scope("elsewhere"))) + assert not held.holds(right(EVERYWHERE)) + + +def test_an_option_on_a_table_inside_a_plain_database_grant(): + """`GRANT SELECT ON d.*`, then `GRANT SELECT ON d.events WITH GRANT OPTION`.""" + held = Holdings((row(DB), row(EVENTS, option=True))) + assert held.holds(right(EVENTS, option=True)) and held.holds(right(DB)) + assert not held.holds(right(DB, option=True)) + + +def test_surplus_is_what_no_desired_right_covers(): + held = Holdings((row(DB, option=True), row(DB, flag="INSERT"), row(EVENTS, revoke=True))) + assert held.surplus(frozenset({right(DB, option=True), right(DB, flag="INSERT")})) == () + assert held.surplus(frozenset({right(DB)})) == ( + Surplus(row(DB, option=True), option_only=True), + Surplus(row(DB, flag="INSERT")), + ) + assert held.surplus(frozenset({right(EVENTS)})) == ( + Surplus(row(DB, option=True)), + Surplus(row(DB, flag="INSERT")), + ) + + +@pytest.mark.parametrize( + ("surplus", "desired", "undermines"), + [ + # Other flags on the same scope: a plain revoke. + (Surplus(row(DB, flag="INSERT")), right(DB), False), + # The same flag and scope, option only: REVOKE GRANT OPTION FOR. + (Surplus(row(DB, option=True), option_only=True), right(DB), False), + # The same flag on a strictly broader scope: revoking it takes the declared right. + (Surplus(row(DB)), right(EVENTS), True), + (Surplus(row(EVERYWHERE)), right(DB), True), + (Surplus(row(EVERYWHERE, flag="READ")), right(REMOTE, flag="READ"), True), + # Only the option goes: a plain right inside survives, one with option doesn't. + (Surplus(row(DB, option=True), option_only=True), right(EVENTS), False), + (Surplus(row(DB, option=True), option_only=True), right(EVENTS, option=True), True), + (Surplus(row(DB)), right(Scope("other", "events")), False), + ], +) +def test_a_surplus_undermines_a_desired_right_strictly_inside_it(surplus, desired, undermines): + assert surplus.undermines([desired]) is undermines + + +def test_fold_names_a_group_only_when_every_flag_of_it_is_there(): + """Narrowing ALTER to ALTER UPDATE revokes the other leaves, never ALTER itself.""" + alter = TREE.flags("ALTER", "database") + assert fold(TREE, alter, "database") == ("ALTER",) + others = fold(TREE, alter - {"ALTER UPDATE"}, "database") + assert "ALTER" not in others and "ALTER UPDATE" not in others and "ALTER DELETE" in others + assert len(others) < len(alter) - 1 + unfolded = frozenset().union(*(TREE.flags(name, "database") for name in others)) + assert unfolded == alter - {"ALTER UPDATE"} + assert fold(TREE, TREE.flags("ALL", "database"), "database") == ("ALL",) + assert fold(TREE, {"READ", "WRITE"}, "source") == ("READ", "WRITE"), "never ALL ON S3" + assert fold(TREE, {"SELECT", "INSERT", "NOT A FLAG"}, "table") == ( + "INSERT", + "NOT A FLAG", + "SELECT", + ) + + +def test_a_stored_row_becomes_its_flags_on_its_scope(): + stored = { + "access_type": "READ", + "access_object": "REMOTE", + "database": None, + "table": None, + "column": None, + "is_partial_revoke": 0, + "grant_option": 1, + } + assert stored_rows(TREE, stored) == [StoredRow("READ", REMOTE, True, False)] + every_source = {**stored, "access_object": "", "grant_option": 0} + assert stored_rows(TREE, every_source) == [StoredRow("READ", EVERYWHERE)] + column = {**every_source, "access_type": "SELECT", "database": "d", "table": "events"} + assert stored_rows(TREE, {**column, "column": "id", "is_partial_revoke": 1}) == [ + StoredRow("SELECT", Scope("d", "events", "id"), False, True) + ] + group = stored_rows(TREE, {**column, "access_type": "ALTER TABLE", "table": None}) + assert {flag_row.flag for flag_row in group} == TREE.flags("ALTER TABLE", "database") + + +def test_a_row_the_tree_cannot_expand_is_kept_under_its_own_name(): + """So it still counts as held, and is revoked or listed like any other row.""" + stored = { + "access_type": "SOMETHING NEW", + "access_object": "", + "database": "d", + "table": None, + "column": None, + "is_partial_revoke": 0, + "grant_option": 0, + } + assert stored_rows(TREE, stored) == [StoredRow("SOMETHING NEW", DB)] diff --git a/tests/access/test_access_show.py b/tests/access/test_access_show.py new file mode 100644 index 0000000..844bfe2 --- /dev/null +++ b/tests/access/test_access_show.py @@ -0,0 +1,177 @@ +"""`access show` without a server: what a read of the server becomes as access.yaml text.""" + +import pytest +import yaml + +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.live import LiveEntity, LiveState, Membership +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.rights import Holdings, Scope, StoredRow +from ch_migrate.access.server import AccessError +from ch_migrate.access.show import Showing, show_access + +TREE = bundled_tree() +HEADER = [ + "# What the server holds for dev, in access.yaml's form (`ch-migrate access show`).", + "# Passwords are never shown. For ch-migrate to create a user, add its", + "# `password: {secret: NAME}`.", +] + + +def holding(*grants, roles=(), extra_rows=()): + rows = [flag_row for grant in grants for flag_row in stored(grant)] + memberships = tuple( + role if isinstance(role, Membership) else Membership(role) for role in roles + ) + return LiveEntity(Holdings((*rows, *extra_rows)), memberships) + + +def stored(text, revoke=False): + grant = parse_grant(text) + scope = Scope.of(grant.target) + return [ + StoredRow(flag, scope, grant.grant_option, revoke) + for name in grant.privileges + for flag in sorted(TREE.flags(TREE.canonical(name), scope.kind)) + ] + + +@pytest.fixture +def showing(validate, settings): + def build(text, *names): + return Showing(settings, validate(text).spec, names) + + return build + + +def test_a_role_prints_its_grants_then_its_roles(showing): + """The project's database is `{db}`; the header says passwords are never shown.""" + role = holding( + "SELECT, SHOW TABLES ON shop_dev.*", + "SELECT ON shop_dev.events WITH GRANT OPTION", + "ALTER ON other.*", + "READ ON REMOTE", + roles=("base",), + ) + live = LiveState(TREE, roles={"analyst": role, "empty": holding()}) + shown = show_access(showing("{}", "analyst", "empty"), live) + assert shown.warnings == () + assert shown.text.splitlines() == [ + *HEADER, + "roles:", + " analyst:", + " grants:", + " - ALTER ON other.*", + " - READ ON REMOTE", + " - SELECT ON {db}.events WITH GRANT OPTION", + " - SELECT, SHOW TABLES ON {db}.*", + " roles:", + " - base", + " empty: {}", + ] + + +def test_a_user_prints_its_roles_then_default_roles_when_they_are_not_all(showing): + etl = holding( + "INSERT ON shop_dev.events", roles=("analyst", Membership("loader", default=False)) + ) + users = { + "etl": etl, + "all_default": holding(roles=("analyst",)), + "none_default": holding(roles=(Membership("analyst", default=False),)), + } + shown = show_access(showing("{}", *users), LiveState(TREE, users=users)) + assert shown.warnings == () + assert yaml.safe_load(shown.text) == { + "users": { + "etl": { + "roles": ["analyst", "loader"], + "default_roles": ["analyst"], + "grants": ["INSERT ON {db}.events"], + }, + "all_default": {"roles": ["analyst"]}, + "none_default": {"roles": ["analyst"], "default_roles": []}, + }, + } + assert list(yaml.safe_load(shown.text)["users"]["etl"]) == ["roles", "default_roles", "grants"] + + +def test_what_access_yaml_cannot_declare_is_left_out_with_a_warning(showing): + rows = ( + StoredRow("SELECT", Scope("shop_dev", "events", "id")), + *stored("SELECT ON shop_dev.secrets", revoke=True), + StoredRow("INSERT", Scope("shop_dev", "events"), grant_option=True, revoke=True), + StoredRow("TABLE ENGINE", Scope(source="MergeTree")), + StoredRow("READ", Scope(source="S3")), + StoredRow("WRITE", Scope(source="S3")), + ) + role = holding("SELECT ON shop_dev.*", extra_rows=rows) + user = holding(roles=(Membership("r", admin_option=True),)) + shown = show_access( + showing("{}", "r", "u"), LiveState(TREE, roles={"r": role}, users={"u": user}) + ) + assert yaml.safe_load(shown.text) == { + "roles": {"r": {"grants": ["READ, WRITE ON S3", "SELECT ON {db}.*"]}}, + "users": {"u": {"roles": ["r"]}}, + } + assert shown.warnings == ( + "role r holds SELECT(id) ON shop_dev.events: column grants aren't in v1, " + "so it is left out.", + "role r has a partial revoke of SELECT ON shop_dev.secrets, which access.yaml can't " + "declare. `access plan` shows the grant that clears it.", + "role r has a partial revoke of the grant option for INSERT ON shop_dev.events, " + "which access.yaml can't declare. `access plan` shows the grant that clears it.", + "role r holds TABLE ENGINE ON MergeTree, which access.yaml can't declare, " + "so it is left out.", + "user u holds role r with admin option, which access.yaml can't declare.", + ) + + +def test_the_migration_role_prints_its_profile_and_what_it_holds_beyond_it(showing): + request = showing("migration_role: {profile: legacy}", "shop_migration_role") + profile = [str(grant) for grant in request.spec.migration.profile.grants] + role = holding( + *profile, "CREATE DATABASE ON shop_dev.*", "SELECT ON other.*", roles=("helper",) + ) + shown = show_access(request, LiveState(TREE, roles={"shop_migration_role": role})) + assert yaml.safe_load(shown.text) == { + "migration_role": { + "profile": "legacy", + "grants": ["CREATE DATABASE ON {db}.*", "SELECT ON other.*"], + } + } + assert shown.warnings == ( + "role shop_migration_role holds role helper, which migration_role can't declare.", + ) + + +def test_without_names_it_covers_what_access_yaml_declares(showing): + request = showing( + """\ + roles: {analyst: {}, gone: {absent: true}} + users: {etl: {password: {secret: p}}} + """ + ) + assert request.names == request.wanted.names == ("analyst", "gone", "etl") + assert request.expected == ("analyst", "etl"), "one declared absent needn't be there" + live = LiveState(TREE, roles={"analyst": holding()}) + present = LiveState(TREE, roles={"analyst": holding()}, users={"etl": holding()}) + assert request.unsettled(live) and not request.unsettled(present) + shown = show_access(request, live) + assert yaml.safe_load(shown.text) == {"roles": {"analyst": {}}} + assert shown.warnings == ("etl is declared but isn't on the server, so it isn't shown.",) + still_there = LiveState(TREE, roles={"analyst": holding(), "gone": holding()}) + assert set(yaml.safe_load(show_access(request, still_there).text)["roles"]) == { + "analyst", + "gone", + } + assert show_access(showing("{}"), LiveState(TREE)).text.splitlines() == [*HEADER, "{}"] + + +def test_a_name_the_server_lacks_or_access_yaml_cannot_declare_is_refused(showing): + with pytest.raises(AccessError, match="The server has no user or role named nobody."): + show_access(showing("{}", "nobody"), LiveState(TREE)) + for name, reason in (("shop_admin", "admin_user"), ("shop_migrator", "the migration user")): + with pytest.raises(AccessError, match=f"{name} is .*{reason}"): + showing("{}", name).check() + showing("{}", "analyst", "shop_migration_role").check() diff --git a/tests/access/test_access_sql.py b/tests/access/test_access_sql.py new file mode 100644 index 0000000..b14c679 --- /dev/null +++ b/tests/access/test_access_sql.py @@ -0,0 +1,115 @@ +"""The SQL `access validate --sql` prints: apply's order, best-effort grants, secret placeholders.""" + +import re + +import pytest + +from ch_migrate.access.render import render_sql, users_that_must_exist + +FILE = """\ + migration_role: + grants: [CREATE FUNCTION ON *.*] + roles: + reader: + grants: + - SELECT ON {db}.* WITH GRANT OPTION + - {grant: CLUSTER ON *.*, best_effort: true} + - {grant: SELECT ON system.* WITH GRANT OPTION, best_effort: true} + old: {absent: true} + users: + etl: + password: {secret: etl_password} + roles: [reader, writer] + default_roles: [reader] + grants: ['DELETE ON {db}.events'] + viewer: + roles: [reader] + default_roles: [] + grants: ['SHOW TABLES ON {db}.*'] + gone: {absent: true} + """ +# Every user with no password, beside the migration user, which always has one. +NO_PASSWORDS = """\ + users: + viewer: {roles: [reader], grants: ['SELECT ON {db}.*']} + ops: {} + """ +PLACEHOLDER = re.compile(r"") +# The smallest access.yaml: an empty one is an error. +CORE_ONLY = "migration_role: {profile: core}\n" + + +def test_statements_follow_applys_order(validate): + sql = render_sql(validate(FILE).spec) + core = len(validate(CORE_ONLY).spec.migration.profile.grants) + assert sql[:8] == [ + "CREATE ROLE IF NOT EXISTS shop_migration_role", + "CREATE ROLE IF NOT EXISTS reader", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY ", + "CREATE USER IF NOT EXISTS etl IDENTIFIED BY ", + "GRANT shop_migration_role TO shop_migrator", + "GRANT reader, writer TO etl", + "GRANT reader TO viewer", + "GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON shop_dev.* TO shop_migration_role", + ] + assert sql[7 + core :] == [ + "GRANT CREATE FUNCTION ON *.* TO shop_migration_role", + "GRANT SELECT ON shop_dev.* TO reader WITH GRANT OPTION", + "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO reader", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO reader WITH GRANT OPTION", + "GRANT ALTER DELETE ON shop_dev.events TO etl", + "GRANT SHOW TABLES ON shop_dev.* TO viewer", + "SET DEFAULT ROLE reader TO etl", + "SET DEFAULT ROLE NONE TO viewer", + "DROP USER IF EXISTS gone", + "DROP ROLE IF EXISTS old", + ] + + +@pytest.mark.parametrize( + "text", [FILE, NO_PASSWORDS, CORE_ONLY], ids=["mixed", "no-passwords", "core-only"] +) +def test_every_create_user_is_identified_by_an_unquoted_placeholder(validate, text): + """A CREATE USER with no IDENTIFIED clause is a no_password login on 26.3, so none is printed. + + The placeholder is unquoted, so SQL run unedited fails to parse instead of setting the + placeholder text as the password. + """ + sql = render_sql(validate(text).spec) + creates = [statement for statement in sql if statement.startswith("CREATE USER")] + assert creates + for statement in creates: + assert re.fullmatch(r"CREATE USER IF NOT EXISTS \w+ IDENTIFIED BY ", statement) + assert all( + PLACEHOLDER.search(statement) is None for statement in sql if statement not in creates + ) + assert "'" + ] + assert "GRANT reader TO viewer" in sql + assert "GRANT SELECT ON shop_dev.* TO viewer" in sql + + +def test_absent_users_are_not_users_that_must_exist(validate): + assert users_that_must_exist(validate(FILE).spec) == ["viewer"] + + +def test_best_effort_profile_grants_use_current_grants(validate): + sql = render_sql(validate(CORE_ONLY).spec) + assert "GRANT CURRENT GRANTS(READ ON REMOTE) TO shop_migration_role" in sql + assert "GRANT SELECT ON system.dictionaries TO shop_migration_role" in sql + + +def test_no_secret_is_read_even_when_one_is_set(validate, monkeypatch): + monkeypatch.setenv("CH_DEV_ETL_PASSWORD", "sentinel-etl") + monkeypatch.setenv("CH_DEV_MIGRATION_PASSWORD", "sentinel-migration") + sql = "\n".join(render_sql(validate(FILE).spec)) + assert "sentinel" not in sql + assert "IDENTIFIED BY " in sql diff --git a/tests/access/test_access_writes.py b/tests/access/test_access_writes.py new file mode 100644 index 0000000..0df1ba6 --- /dev/null +++ b/tests/access/test_access_writes.py @@ -0,0 +1,230 @@ +"""The statements `access apply` sends for a change (design note, 2.5). + +The integration tests run them on a server; these pin their text: a replace and the grant +options after it, names quoted, default roles, and ON CLUSTER with its settings. +""" + +import pytest +from fake_access_server import FakeServer, grant_rows + +from ch_migrate.access.live import LiveState, Wanted, read_live +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.planner import Change, Entity, build_plan +from ch_migrate.access.privileges import bundled_tree +from ch_migrate.access.writes import ( + ON_CLUSTER_SETTINGS, + Unkept, + Writing, + best_effort_writes, + writes_for, +) + +READER = Entity("role", "reader") + + +def held(*grants, revoked=None): + """One read of a server where `reader` holds these grants, less a `revoked` one inside.""" + fake = FakeServer(storage="local_directory") + fake.tables["roles"].append({"name": "reader"}) + rows = [row for grant in grants for row in grant_rows(grant)] + if revoked is not None: + rows += grant_rows(revoked, is_partial_revoke=1) + fake.tables["grants"] += [{"user_name": None, "role_name": "reader", **row} for row in rows] + return read_live(fake, Wanted(("reader",))) + + +def replace_writes(spec, live): + """The SQL of the one replace that the plan for `reader` holds.""" + [change] = [change for change in build_plan(spec, live).changes if change.action == "replace"] + return [write.sql for write in writes_for(change, Writing(spec, live))] + + +def sql(change, spec, cluster=None): + [write] = writes_for(change, Writing(spec, LiveState(bundled_tree()), cluster)) + return write.sql + + +def test_a_replace_gives_the_whole_set_then_the_grant_options(validate): + spec = validate( + """ + roles: + reader: + grants: ['SELECT ON {db}.events', 'INSERT ON {db}.events WITH GRANT OPTION'] + """ + ).spec + live = held(Grant(("SELECT", "INSERT"), Target("shop_dev"), grant_option=True)) + assert replace_writes(spec, live) == [ + "GRANT SELECT ON `shop_dev`.`events`, INSERT ON `shop_dev`.`events` TO `reader` " + "WITH REPLACE OPTION", + "GRANT INSERT ON `shop_dev`.`events` TO `reader` WITH GRANT OPTION", + ] + + +def test_a_replace_holds_only_what_is_held_of_a_best_effort_grant(validate): + """The admin may not hold CLUSTER, so a replace never asks for it; a try comes later.""" + spec = validate( + """ + roles: + reader: + grants: + - SELECT ON {db}.events + - {grant: SELECT ON system.parts, best_effort: true} + - {grant: CLUSTER ON *.*, best_effort: true} + """ + ).spec + live = held(Grant(("SELECT",), Target("shop_dev")), Grant(("SELECT",), Target("system"))) + assert replace_writes(spec, live) == [ + "GRANT SELECT ON `shop_dev`.`events`, SELECT ON `system`.`parts` TO `reader` " + "WITH REPLACE OPTION", + ] + + +SYSTEM_BEST_EFFORT = """ +roles: + reader: + grants: + - SELECT ON {db}.events + - {grant: SELECT ON system.*, best_effort: true} +""" + + +def test_a_replace_keeps_what_is_held_inside_a_best_effort_grant(validate): + """`SELECT ON system.*` declared best-effort, only `system.tables` held.""" + live = held( + Grant(("SELECT",), Target("shop_dev")), + Grant(("SELECT",), Target("system", "tables")), + ) + assert replace_writes(validate(SYSTEM_BEST_EFFORT).spec, live) == [ + "GRANT SELECT ON `shop_dev`.`events`, SELECT ON `system`.`tables` TO `reader` " + "WITH REPLACE OPTION", + ] + + +@pytest.mark.parametrize("above", [Target("system"), Target()], ids=["system.*", "*.*"]) +def test_a_revoke_inside_a_best_effort_grant_stops_the_replace(validate, above): + """`SELECT ON system.*`, or on `*.*`, held but not on `system.users`. + No GRANT can keep that exactly, so the replace isn't sent, and the role keeps its grants.""" + live = held( + Grant(("SELECT",), Target("shop_dev")), + Grant(("SELECT",), above), + revoked=Grant(("SELECT",), Target("system", "users")), + ) + with pytest.raises(Unkept) as unkept: + replace_writes(validate(SYSTEM_BEST_EFFORT).spec, live) + assert str(unkept.value) == ( + "what it holds of the best-effort grant SELECT ON system.* has SELECT ON system.users " + "revoked inside it, which a replace can't keep, so it keeps the access it has" + ) + + +@pytest.mark.parametrize("option", [False, True]) +def test_a_revoked_grant_option_inside_stops_a_replace_that_keeps_the_option(validate, option): + """The grant option of `SELECT ON system.*` held, but not on `system.users`. That stops + the replace only where the best-effort grant carries the option.""" + declared = "SELECT ON system.* WITH GRANT OPTION" if option else "SELECT ON system.*" + spec = validate(SYSTEM_BEST_EFFORT.replace("SELECT ON system.*", declared)).spec + live = held( + Grant(("SELECT",), Target("shop_dev")), + Grant(("SELECT",), Target("system"), grant_option=True), + revoked=Grant(("SELECT",), Target("system", "users"), grant_option=True), + ) + if option: + with pytest.raises(Unkept, match="has the grant option for SELECT ON system.users "): + replace_writes(spec, live) + else: + assert replace_writes(spec, live) == [ + "GRANT SELECT ON `shop_dev`.`events`, SELECT ON `system`.* TO `reader` " + "WITH REPLACE OPTION", + ] + + +def test_the_migration_role_is_never_replaced(validate): + spec = validate("{}\n").spec + change = Change("replace", Entity("role", "shop_migration_role")) + with pytest.raises(ValueError, match="only ever added to"): + writes_for(change, Writing(spec, LiveState(bundled_tree()))) + + +@pytest.mark.parametrize( + ("grant", "expected"), + [ + (Grant(("SELECT(we`ird)",), Target("odd-db", "t")), "SELECT(`we\\`ird`) ON `odd-db`.`t`"), + (Grant(("READ",), Target(source="S3")), "READ ON S3"), + (Grant(("TABLE ENGINE",), Target(source="MergeTree")), "TABLE ENGINE ON MergeTree"), + (Grant(("CREATE ROLE",), Target()), "CREATE ROLE ON *.*"), + ], +) +def test_names_read_from_the_server_are_quoted(validate, grant, expected): + spec = validate("{}\n").spec + assert sql(Change("revoke", READER, grant=grant), spec) == f"REVOKE {expected} FROM `reader`" + + +@pytest.mark.parametrize( + ("roles", "expected"), [(None, "ALL"), ((), "NONE"), (("a", "b"), "`a`, `b`")] +) +def test_default_roles(validate, roles, expected): + change = Change("set_default_roles", Entity("user", "u"), roles=roles) + assert sql(change, validate("{}\n").spec) == f"ALTER USER `u` DEFAULT ROLE {expected}" + + +def test_on_cluster_statements_wait_for_every_host(validate): + spec = validate("{}\n").spec + change = Change("grant_role", Entity("user", "u"), roles=("r",)) + [write] = writes_for(change, Writing(spec, LiveState(bundled_tree()), "it_cluster")) + assert write.sql == "GRANT ON CLUSTER `it_cluster` `r` TO `u`" + assert write.settings["wait_end_of_query"] == 1 + drop = "DROP ROLE IF EXISTS `reader` ON CLUSTER `c`" + assert sql(Change("drop_role", READER), spec, "c") == drop + + +def test_every_on_cluster_form_quotes_the_cluster(validate): + """The cluster's name is quoted, so one such as `c-1` parses in all 15 forms.""" + spec = validate("roles: {reader: {grants: ['SELECT ON {db}.events']}}\n").spec + writing = Writing(spec, LiveState(bundled_tree()), "c-1", {"u": "secret"}) + sql = [write.sql for change in every_form() for write in writes_for(change, writing)] + assert len(sql) == 15 + assert all(text.count(" ON CLUSTER `c-1`") == 1 for text in sql), sql + assert "GRANT ON CLUSTER `c-1` `reader` TO `u`" in sql + + +def test_a_best_effort_grant_is_current_grants_or_a_plain_grant_per_privilege(): + """Decision 12: ClickHouse refuses CURRENT GRANTS ON CLUSTER, so there each privilege is a + GRANT of its own, which the admin may refuse without stopping the others.""" + names = ("SYSTEM SYNC REPLICA", "SYSTEM SYNC DATABASE REPLICA") + grant = Grant(names, Target("db"), grant_option=True, best_effort=True) + [write] = best_effort_writes("r", grant, None) + assert (write.sql, write.settings, write.gives) == ( + "GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA, SYSTEM SYNC DATABASE REPLICA ON `db`.*) " + "TO `r` WITH GRANT OPTION", + {}, + grant, + ) + writes = best_effort_writes("r", grant, "c") + assert [write.sql for write in writes] == [ + f"GRANT ON CLUSTER `c` {name} ON `db`.* TO `r` WITH GRANT OPTION" for name in names + ] + assert all(write.settings == ON_CLUSTER_SETTINGS for write in writes) + assert [write.gives.privileges for write in writes] == [(name,) for name in names] + + +def every_form(): + """One change for each statement in `sql/apply.sql` that can run ON CLUSTER.""" + user, select = Entity("user", "u"), Grant(("SELECT",), Target("db", "t")) + optioned = Grant(("SELECT",), Target("db", "t"), grant_option=True) + return [ + Change("create_role", READER), + Change("create_user", user), + Change("reset_password", user), + Change("grant_role", user, roles=("reader",)), + Change("grant", READER, grant=select), + Change("grant", READER, grant=optioned), + Change("replace", READER), + Change("best_effort", READER, grant=optioned), + Change("set_default_roles", user, roles=("reader",)), + Change("revoke", READER, grant=select), + Change("revoke_grant_option", READER, grant=select), + Change("revoke_role", user, roles=("reader",)), + Change("revoke_admin_option", user, roles=("reader",)), + Change("drop_user", user), + Change("drop_role", READER), + ] diff --git a/tests/access/test_apply_command.py b/tests/access/test_apply_command.py new file mode 100644 index 0000000..bfa9339 --- /dev/null +++ b/tests/access/test_apply_command.py @@ -0,0 +1,712 @@ +"""`access apply` without a server: what it refuses, what it sends, and in what order. + +The admin's connection is a `FakeServer` that records each write. Exit 2 means that nothing +was written, so every exit-2 test also checks that the server saw no write. Statements +apply sends are checked by text here; `tests/integration/test_access_apply.py` runs them. +""" + +import pytest +from click.testing import CliRunner +from fake_access_server import FakeServer, grant_rows + +from ch_migrate.access.loader import validate_access +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.settings import load_settings +from ch_migrate.access.templates import statement +from ch_migrate.cli import main + +ACCESS_YAML = """\ +roles: + analyst: {grants: ['SELECT, SHOW TABLES ON {db}.*']} +users: + dashboards: {password: {secret: dashboards_password}, roles: [analyst]} +""" +PASSWORDS = {"DASHBOARDS": "Dash!" + "1a" * 12, "MIGRATION": "Migr!" + "2b" * 12} +IN_SYNC = "✓ In sync for dev (access.yaml): {} applied.\n" + + +def run(*args): + result = CliRunner().invoke(main, ["access", *args]) + assert result.exception is None or isinstance(result.exception, SystemExit), result.output + return result + + +@pytest.fixture +def server(project, monkeypatch): + """A server holding nothing, on each node's own disk; secrets set.""" + (project / "access.yaml").write_text(ACCESS_YAML) + fake = FakeServer(storage="local_directory") + monkeypatch.setattr("ch_migrate.access.cli.connect_admin", lambda settings: fake) + for name, value in PASSWORDS.items(): + monkeypatch.setenv(f"CH_DEV_{name}_PASSWORD", value) + return fake + + +@pytest.fixture +def spec(project, server): + """What ACCESS_YAML declares, as `FakeServer.hold` takes it.""" + return declaration(project) + + +def declaration(project): + return validate_access(load_settings("dev", project / "config.yaml"), project).spec + + +def set_config(project, line): + """Add one line under the `dev` environment in config.yaml.""" + path = project / "config.yaml" + path.write_text( + path.read_text().replace(" host: localhost\n", f" host: localhost\n{line}\n", 1) + ) + + +def sent(server): + return [write.sql for write in server.writes] + + +def holds_instead(server, grantee, role): + """The server holds `role`, and none other, where `grantee` holds a role.""" + server.tables["roles"].append({"name": role}) + for row in server.tables["role_grants"]: + if grantee in (row["user_name"], row["role_name"]): + row["granted_role_name"] = role + + +def drop_grants(server, role): + """The server holds no grant for `role`.""" + server.tables["grants"] = [row for row in server.tables["grants"] if row["role_name"] != role] + + +def shows_first(server, tables): + """After `apply`'s writes, its first read shows `tables`, as a replica that is behind + would, and the reads after it show what the server holds.""" + query, reads = server.query, [] + + def lagging(sql, parameters=None, settings=None): + if server.writes and sql == statement("live", "privileges"): + reads.append(sql) # each read starts with the privilege tree + if len(reads) != 1: + return query(sql, parameters, settings) + held, server.tables = server.tables, tables + try: + return query(sql, parameters, settings) + finally: + server.tables = held + + server.query = lagging + + +def holds_less_system_users(server, role): + """`role` holds `SELECT ON {db}.*` instead of its declared table, so narrowing it is a + replace, and its best-effort `SELECT ON system.*` less `system.users`, which a replace + can't keep.""" + for row in server.tables["grants"]: + if row["role_name"] == role and row["database"] == "shop_dev": + row["table"] = None + revoked = grant_rows(Grant(("SELECT",), Target("system", "users")), is_partial_revoke=1) + server.tables["grants"] += [{"user_name": None, "role_name": role, **row} for row in revoked] + + +def test_in_sync_sends_nothing_and_reports_0_changes(server, spec): + server.hold(spec) + result = run("apply", "dev") + assert (result.exit_code, result.stdout, result.stderr) == (0, IN_SYNC.format("0 changes"), "") + assert server.writes == [] + + +def test_creates_come_first_and_passwords_are_bound_never_written(server, spec): + server.converges_to = spec + result = run("apply", "dev") + assert result.exit_code == 0, result.output + assert sent(server)[:5] == [ + "CREATE ROLE IF NOT EXISTS `shop_migration_role`", + "CREATE ROLE IF NOT EXISTS `analyst`", + "CREATE USER IF NOT EXISTS `shop_migrator` IDENTIFIED BY {password:String}", + "CREATE USER IF NOT EXISTS `dashboards` IDENTIFIED BY {password:String}", + "GRANT `shop_migration_role` TO `shop_migrator`", + ] + assert [write.parameters for write in server.writes[2:4]] == [ + {"password": PASSWORDS["MIGRATION"]}, + {"password": PASSWORDS["DASHBOARDS"]}, + ] + # Only the password statements go by raw_query, form-encoded. + assert server.raw == sent(server)[2:4] + assert "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO `shop_migration_role`" in sent(server) + assert not any(password in result.output for password in PASSWORDS.values()) + assert result.stdout.splitlines()[-1] == IN_SYNC.format("15 changes").strip() + + +def test_cluster_granted_to_every_login_is_never_tried(server, spec): + """Where the server grants CLUSTER to every login, as ClickHouse Cloud does, the + migration role already holds it: `apply` sends no `CURRENT GRANTS(CLUSTER ...)` and prints + no best-effort line for it, on any run.""" + server.own_grants = [] + server.converges_to = spec + result = run("apply", "dev") + assert result.exit_code == 0, result.output + assert not any("CLUSTER" in sql for sql in sent(server)) + assert "CLUSTER" not in result.output + + +def test_an_unset_secret_exits_2_before_any_write(server, monkeypatch): + monkeypatch.delenv("CH_DEV_DASHBOARDS_PASSWORD") + result = run("apply", "dev") + assert (result.exit_code, result.stdout) == (2, ""), result.output + assert result.stderr.startswith("✗ CH_DEV_DASHBOARDS_PASSWORD is required.") + assert server.writes == [] + + +def test_the_login_apply_runs_as_is_never_declared(server): + server.login = "dashboards" + result = run("apply", "dev") + assert (result.exit_code, result.stdout, server.writes) == (2, "", []), result.output + assert result.stderr == ( + "✗ `apply` is logged in as dashboards, which access.yaml declares. " + "ch-migrate never changes the login it runs as.\n" + ) + + +def test_apply_never_takes_access_from_a_role_the_login_holds(server, spec, project): + """A revoke from a role the admin holds could cut a right a later + statement needs. Holding a declared role is fine: granting it needs ADMIN OPTION.""" + server.hold(spec) + server.login_roles = ["analyst"] + assert run("apply", "dev").exit_code == 0 and server.writes == [] + narrower = ACCESS_YAML.replace("SELECT, SHOW TABLES ON {db}.*", "SELECT ON {db}.*") + (project / "access.yaml").write_text(narrower) # revokes SHOW TABLES from analyst + result = run("apply", "dev") + assert (result.exit_code, server.writes) == (2, []), result.output + assert ( + "✗ access.yaml would revoke from, replace or drop role analyst, which the login " + "`apply` runs as holds." + ) in result.stderr + + +def test_a_migration_user_that_is_the_admin_exits_2(server, project): + path = project / "config.yaml" + path.write_text(path.read_text().replace("admin_user: shop_admin", "admin_user: shop_migrator")) + result = run("apply", "dev") + assert (result.exit_code, result.stdout, server.writes) == (2, "", []), result.output + assert result.stderr.startswith( + "✗ The migration user shop_migrator is config.yaml's admin_user" + ) + + +def test_a_plan_error_exits_2_before_any_write(server, project): + (project / "access.yaml").write_text("users: {nopass: {}}\n") + result = run("apply", "dev") + assert (result.exit_code, result.stdout, server.writes) == (2, "", []), result.output + assert "user nopass isn't on the server and has no password" in result.stderr + + +def test_a_failed_membership_keeps_the_role_it_replaces(server, spec): + """2.5: a user moving from role `old` to `analyst` keeps `old` if `analyst` fails.""" + server.hold(spec) + server.tables["roles"].append({"name": "old"}) + for row in server.tables["role_grants"]: + if row["user_name"] == "dashboards": + row["granted_role_name"] = "old" + server.failing = { + "GRANT `analyst` TO `dashboards`": "Code: 497. DB::Exception: no. (ACCESS_DENIED)" + } + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert sent(server) == ["GRANT `analyst` TO `dashboards`"] + assert result.stderr.splitlines()[:2] == [ + "✗ grant role analyst to user dashboards: no. (ACCESS_DENIED)", + "! skipped: revoke role old from user dashboards, because a change to user dashboards " + "failed, so it keeps the access it has", + ] + assert "- revoke role old from user dashboards" in result.stdout.splitlines() + + +@pytest.mark.parametrize("failing", ["analyst", "base"]) +def test_a_failed_role_keeps_its_holders_old_access(server, project, failing): + """2.5: a failed change to a role counts for every declared holder, directly or through + declared roles. The user moving from `old` to `analyst`, which holds `base`, keeps `old`.""" + (project / "access.yaml").write_text( + "roles:\n" + " base: {grants: ['SELECT ON {db}.events']}\n" + " analyst: {grants: ['SELECT ON {db}.regions'], roles: [base]}\n" + "users:\n" + " dashboards: {password: {secret: dashboards_password}, roles: [analyst]}\n" + ) + server.hold(declaration(project)) + holds_instead(server, "dashboards", "old") + drop_grants(server, failing) + server.failing = {f"TO `{failing}`": "Code: 497. DB::Exception: no. (ACCESS_DENIED)"} + table = {"analyst": "regions", "base": "events"}[failing] + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert sent(server)[0] == "GRANT `analyst` TO `dashboards`" + assert result.stderr.splitlines()[:2] == [ + f"✗ grant SELECT ON shop_dev.{table} to role {failing}: no. (ACCESS_DENIED)", + "! skipped: revoke role old from user dashboards, because a change to role " + f"{failing}, which it holds, failed, so it keeps the access it has", + ] + assert not any(sql.startswith("REVOKE") for sql in sent(server)) + + +def test_a_failed_sibling_role_holds_back_the_revoke(server, project): + """`dashboards` holds `old` and `new`, and access.yaml moves its + read on events from `old` to `new`. Granting it to `new` fails, so `old` keeps it.""" + holding = "users:\n dashboards: {password: {secret: dashboards_password}, roles: [old, new]}\n" + (project / "access.yaml").write_text( + "roles:\n old: {grants: ['SELECT ON {db}.events']}\n new: {}\n" + holding + ) + server.hold(declaration(project)) + (project / "access.yaml").write_text( + "roles:\n old: {}\n new: {grants: ['SELECT ON {db}.*']}\n" + holding + ) + server.failing = {"TO `new`": "Code: 497. DB::Exception: no. (ACCESS_DENIED)"} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any(sql.startswith("REVOKE") for sql in sent(server)), sent(server) + assert ( + "! skipped: revoke SELECT ON shop_dev.events from role old, because an earlier change " + "to role new failed, so it keeps the access it has" + ) in result.stderr.splitlines() + + +@pytest.mark.parametrize( + ("failing", "reason"), + [ + ("GRANT `base` TO `reader`", "a change to role reader failed"), + (" TO `base`", "a change to role base, which it holds, failed"), + ], +) +def test_a_replace_waits_for_its_own_changes_and_its_roles(server, project, failing, reason): + """2.5: a replace is gated like a revoke: an earlier failure for the role, or for a role it + holds, skips it, so the role keeps what it holds.""" + (project / "access.yaml").write_text( + "roles:\n" + " base: {grants: ['SELECT ON {db}.regions']}\n" + " reader: {grants: ['SELECT ON {db}.events'], roles: [base]}\n" + ) + server.hold(declaration(project)) + for row in server.tables["grants"]: + if row["role_name"] == "reader": + row["table"] = None # it holds SELECT ON {db}.*: narrowing is a replace + if failing.startswith("GRANT `base`"): + server.tables["role_grants"] = [ + row for row in server.tables["role_grants"] if row["role_name"] != "reader" + ] + else: + drop_grants(server, "base") + server.failing = {failing: "Code: 497. DB::Exception: no. (ACCESS_DENIED)"} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any("REPLACE OPTION" in sql for sql in sent(server)) + assert ( + "! skipped: replace the grants of role reader with its declared set in one statement, " + "instead of: revoke SELECT ON shop_dev.* from role reader, because " + f"{reason}, so it keeps the access it has" + ) in result.stderr.splitlines() + + +def test_a_role_is_replaced_before_its_holders(server, project): + """`reader`, declared first, holds `base`, and both narrow a scope. + Base's replace runs first and fails, so reader's is skipped and named.""" + (project / "access.yaml").write_text( + "roles:\n" + " reader: {grants: ['SELECT ON {db}.events'], roles: [base]}\n" + " base: {grants: ['SELECT ON {db}.regions']}\n" + ) + server.hold(declaration(project)) + for row in server.tables["grants"]: + if row["role_name"] in ("reader", "base"): + row["table"] = None # each holds SELECT ON {db}.*: narrowing is a replace + denied = "Code: 497. DB::Exception: no. (ACCESS_DENIED)" + server.failing = {"TO `base` WITH REPLACE OPTION": denied} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert [sql for sql in sent(server) if "REPLACE OPTION" in sql] == [ + "GRANT SELECT ON `shop_dev`.`regions` TO `base` WITH REPLACE OPTION" + ] + assert ( + "! skipped: replace the grants of role reader with its declared set in one statement, " + "instead of: revoke SELECT ON shop_dev.* from role reader, because a change to role " + "base, which it holds, failed, so it keeps the access it has" + ) in result.stderr.splitlines() + + +def test_a_replace_that_cannot_keep_a_revoke_is_skipped_and_holds_back_its_holders(server, project): + """`reader` holds best-effort `SELECT ON system.*` less `system.users`, + and narrows a scope. Its replace isn't sent, and the user moving to it keeps `old`.""" + (project / "access.yaml").write_text( + "roles:\n" + " reader:\n" + " grants: ['SELECT ON {db}.events', {grant: SELECT ON system.*, best_effort: true}]\n" + "users:\n" + " dashboards: {password: {secret: dashboards_password}, roles: [reader]}\n" + ) + server.hold(declaration(project)) + holds_instead(server, "dashboards", "old") + for row in server.tables["grants"]: + if row["role_name"] == "reader" and row["database"] == "shop_dev": + row["table"] = None # it holds SELECT ON {db}.*: narrowing is a replace + revoked = grant_rows(Grant(("SELECT",), Target("system", "users")), is_partial_revoke=1) + server.tables["grants"] += [ + {"user_name": None, "role_name": "reader", **row} for row in revoked + ] + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any("REPLACE OPTION" in sql or sql.startswith("REVOKE") for sql in sent(server)) + assert result.stderr.splitlines()[:2] == [ + "! skipped: replace the grants of role reader with its declared set in one statement, " + "instead of: revoke SELECT ON shop_dev.* from role reader, because what it holds of the " + "best-effort grant SELECT ON system.* has SELECT ON system.users revoked inside it, " + "which a replace can't keep, so it keeps the access it has", + "! skipped: revoke role old from user dashboards, because a change to role reader, " + "which it holds, couldn't be sent, so it keeps the access it has", + ] + + +def test_a_replace_that_cannot_be_sent_holds_back_the_drops(server, project): + """The user moves from `old`, declared `absent: true`, to `reader`, + whose replace can't keep a revoke inside its best-effort grant. Nothing failed, but the + revoke of `old` and its drop are both skipped and named, so the user keeps `old`.""" + declared = ( + "roles:\n" + " reader:\n" + " grants: ['SELECT ON {db}.events', {grant: SELECT ON system.*, best_effort: true}]\n" + "users:\n" + " dashboards: {password: {secret: dashboards_password}, roles: [reader]}\n" + ) + (project / "access.yaml").write_text(declared) + server.hold(declaration(project)) + holds_instead(server, "dashboards", "old") + holds_less_system_users(server, "reader") + absent = declared.replace("users:\n", " old: {absent: true}\nusers:\n") + (project / "access.yaml").write_text(absent) + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert "GRANT `reader` TO `dashboards`" in sent(server) + assert not any(sql.startswith(("DROP", "REVOKE")) for sql in sent(server)), sent(server) + skipped = [line for line in result.stderr.splitlines() if line.startswith("! skipped: ")] + assert skipped[0].startswith("! skipped: replace the grants of role reader "), skipped + assert skipped[1:] == [ + "! skipped: revoke role old from user dashboards, because a change to role reader, " + "which it holds, couldn't be sent, so it keeps the access it has", + "! skipped: drop role old, because the replace of role reader couldn't be sent", + ] + + +@pytest.mark.parametrize( + ("failing", "reason"), + [ + ("GRANT `analyst` TO `dashboards`", "a change to user dashboards failed"), + (" TO `analyst`", "a change to role analyst, which it holds, failed"), + ], +) +def test_default_roles_wait_like_revokes(server, project, failing, reason): + """A user moving from `old` to `analyst`, its new default role, keeps + `old` active at login if granting `analyst`, or analyst's own grant, fails.""" + (project / "access.yaml").write_text( + ACCESS_YAML.replace("roles: [analyst]}", "roles: [analyst], default_roles: [analyst]}") + ) + server.hold(declaration(project)) + holds_instead(server, "dashboards", "old") + for row in server.tables["users"]: + if row["name"] == "dashboards": + row["default_roles_all"] = 0 # only `old`, which role_grants marks as default + drop_grants(server, "analyst") + server.failing = {failing: "Code: 497. DB::Exception: no. (ACCESS_DENIED)"} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any("DEFAULT ROLE" in sql for sql in sent(server)) + assert ( + "! skipped: set the default roles of user dashboards to analyst, because " + f"{reason}, so it keeps the access it has" + ) in result.stderr.splitlines() + + +def test_drops_wait_until_nothing_has_failed(server, spec, project): + server.hold(spec) + server.tables["users"].append( + {"name": "gone", "default_roles_all": 1, "default_roles_except": []} + ) + (project / "access.yaml").write_text( + ACCESS_YAML + " gone: {absent: true}\n x: {password: {secret: dashboards_password}}\n" + ) + server.failing = { + "CREATE USER IF NOT EXISTS `x`": "Code: 497. DB::Exception: no. (ACCESS_DENIED)" + } + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any(sql.startswith("DROP") for sql in sent(server)) + assert ( + "! skipped: drop user gone, because an earlier change failed" in result.stderr.splitlines() + ) + + +def test_on_cluster_where_users_are_on_each_node(server, project): + set_config(project, " cluster: it_cluster") + assert run("apply", "dev").exit_code == 1 # the fake never converges + assert server.writes and all(" ON CLUSTER `it_cluster`" in sql for sql in sent(server)) + assert all(write.settings["wait_end_of_query"] == 1 for write in server.writes) + + +def test_on_a_cluster_each_best_effort_privilege_is_its_own_grant(server, spec, project): + """Decision 12: never CURRENT GRANTS ON CLUSTER. A refused privilege is a warning, and the + privileges after it are still sent.""" + set_config(project, " cluster: it_cluster") + server.converges_to = spec + refusal = "Code: 497. DB::Exception: shop_admin: Not enough privileges. (ACCESS_DENIED)" + server.failing = {" CLUSTER ON *.* TO ": refusal} + result = run("apply", "dev") + assert result.exit_code == 0, result.output + assert not any("CURRENT GRANTS" in sql for sql in sent(server)) + best_effort = [ + "SELECT ON `system`.`parts`", + "SELECT ON `system`.`replicas`", + "SYSTEM SYNC DATABASE REPLICA ON `shop_dev`.*", + "SYSTEM SYNC REPLICA ON `shop_dev`.*", + "CLUSTER ON *.*", + "READ ON REMOTE", + "CREATE TEMPORARY TABLE ON *.*", + ] + expected = [ + f"GRANT ON CLUSTER `it_cluster` {grant} TO `shop_migration_role`" for grant in best_effort + ] + assert [sql for sql in sent(server) if sql in expected] == expected + assert result.stderr == ( + "! grant role shop_migration_role as much of CLUSTER ON *.* as the admin holds " + "(best-effort): shop_admin: Not enough privileges. (ACCESS_DENIED)\n" + ) + + +def test_no_on_cluster_where_users_are_in_keeper(server, project): + set_config(project, " cluster: it_cluster") + set_config(project, " access_read_timeout: 0") # nothing here would ever show up + server.storage = "replicated" + run("apply", "dev") + assert server.writes and not any("ON CLUSTER" in sql for sql in sent(server)) + assert all(write.settings == {} for write in server.writes) + + +def test_a_cluster_with_unknown_storage_exits_2(server, project): + set_config(project, " cluster: it_cluster") + set_config(project, " access_read_timeout: 0") # unknown storage may lag: don't wait + server.storage = None + result = run("apply", "dev") + assert (result.exit_code, server.writes) == (2, []), result.output + assert "Grant the admin SELECT ON system.user_directories." in result.stderr + + +def test_reads_again_while_a_changed_role_still_differs(server, project): + """A replica shows only the first statement of a mixed-option + replace, then all of it. What is pending for the role then is a grant option, not the + replace `apply` made, and `apply` still reads again, and ends in sync. + + No cluster holds the node, so the node is read on its own, and the reason is said once, + though `apply` reads before and after its writes.""" + (project / "access.yaml").write_text( + "roles:\n" + " mixed: {grants: ['SELECT ON {db}.events', 'INSERT ON {db}.events WITH GRANT OPTION']}\n" + ) + spec = declaration(project) + server.storage, server.clusters = "replicated", [] + server.hold(spec) + for row in server.tables["grants"]: + if row["role_name"] == "mixed": + row.update(table=None, grant_option=1) # SELECT, INSERT ON {db}.*: a replace + first = FakeServer() + first.hold(spec) + for row in first.tables["grants"]: + if row["role_name"] == "mixed": + row["grant_option"] = 0 # the replace's first statement: the set, no option + server.converges_to = spec + shows_first(server, first.tables) + result = run("apply", "dev") + assert result.exit_code == 0, result.output + assert sent(server) == [ + "GRANT SELECT ON `shop_dev`.`events`, INSERT ON `shop_dev`.`events` TO `mixed` " + "WITH REPLACE OPTION", + "GRANT INSERT ON `shop_dev`.`events` TO `mixed` WITH GRANT OPTION", + ] + assert "Reading again for up to" in result.stderr + assert result.stderr.count("Can't read every replica at once") == 1 + assert result.stdout.splitlines()[-1] == IN_SYNC.format("1 change").strip() + + +def test_a_change_that_failed_is_not_read_for_again(server, project): + """A change `apply` failed at stays pending however long it reads, so it isn't read for + again, although another change to the same role landed.""" + set_config(project, " access_read_timeout: 1") + server.storage, server.clusters = "replicated", [] + grants = ["SELECT ON {db}.events", "INSERT ON {db}.regions", "INSERT ON {db}.events"] + server.hold(declared_role(project, grants)) + server.converges_to = declared_role(project, grants[:2]) # once INSERT ON events is revoked + declared_role(project, grants[:1]) + revoking = "REVOKE INSERT ON `shop_dev`.`regions`" + server.failing = {revoking: "Code: 497. DB::Exception: no. (ACCESS_DENIED)"} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert sent(server) == [ + "REVOKE INSERT ON `shop_dev`.`events` FROM `reader`", + f"{revoking} FROM `reader`", + ] + assert "Reading again" not in result.stderr + assert "✗ revoke INSERT ON shop_dev.regions from role reader: no. (ACCESS_DENIED)" in ( + result.stderr.splitlines() + ) + + +def test_ctrl_c_after_a_write_names_the_stop_and_exits_130(server): + def interrupt(sql, parameters=None, settings=None): + answer = FakeServer.command(server, sql, parameters, settings) + if server.writes: # a CHECK GRANT while reading isn't a write + raise KeyboardInterrupt + return answer + + server.command = interrupt + result = run("apply", "dev") + assert result.exit_code == 130, result.output + assert "✗ `apply` stopped part-way: interrupted." in result.stderr + assert "ch-migrate access plan shows what still differs." in result.stderr + + +def declared_role(project, grants): + """Declare only role `reader`, with these grants, and return the declaration.""" + (project / "access.yaml").write_text(f"roles:\n reader: {{grants: {grants}}}\n") + return declaration(project) + + +def test_once_a_write_has_run_an_error_exits_1_not_2(server, monkeypatch): + def broken_read(reader, wanted): + raise RuntimeError("connection reset") + + def write_then_break(sql, parameters=None, settings=None): + answer = FakeServer.command(server, sql, parameters, settings) + if server.writes: + monkeypatch.setattr("ch_migrate.access.live.Reader.read", broken_read) + return answer + + server.command = write_then_break + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert "✗ `apply` stopped part-way: RuntimeError: connection reset" in result.stderr + + +def test_reset_passwords_only_when_asked(server, spec): + server.hold(spec) + assert run("apply", "dev").exit_code == 0 and server.writes == [] + result = run("apply", "dev", "--reset-passwords") + assert result.exit_code == 0, result.output + assert [(w.sql, w.parameters) for w in server.writes] == [ + ( + "ALTER USER `dashboards` IDENTIFIED BY {password:String}", + {"password": PASSWORDS["DASHBOARDS"]}, + ), + ] + assert result.stdout == "+ reset the password of user dashboards\n" + IN_SYNC.format("1 change") + + +def test_reset_passwords_also_resets_a_user_this_run_creates(server, spec): + """Someone else could make the user between apply's read and its + `CREATE USER IF NOT EXISTS`, which then keeps their password; the reset replaces it.""" + server.hold(spec) + server.tables["users"] = [row for row in server.tables["users"] if row["name"] != "dashboards"] + server.tables["role_grants"] = [ + row for row in server.tables["role_grants"] if row["user_name"] != "dashboards" + ] + server.converges_to = spec + result = run("apply", "dev", "--reset-passwords") + assert result.exit_code == 0, result.output + assert sent(server)[:3] == [ + "CREATE USER IF NOT EXISTS `dashboards` IDENTIFIED BY {password:String}", + "ALTER USER `dashboards` IDENTIFIED BY {password:String}", + "GRANT `analyst` TO `dashboards`", + ] + assert server.writes[1].parameters == {"password": PASSWORDS["DASHBOARDS"]} + + +def test_a_reset_is_skipped_when_its_create_failed(server, spec): + """The reset would fail too, as a second error for one problem.""" + server.hold(spec) + server.tables["users"] = [row for row in server.tables["users"] if row["name"] != "dashboards"] + server.failing = {"CREATE USER IF NOT EXISTS `dashboards`": "Code: 497. no. (ACCESS_DENIED)"} + result = run("apply", "dev", "--reset-passwords") + assert result.exit_code == 1, result.output + assert not any(sql.startswith("ALTER USER `dashboards`") for sql in sent(server)) + assert ( + "! skipped: reset the password of user dashboards, because its create failed, " + "so this run gives it nothing more" in result.stderr.splitlines() + ) + + +def test_a_failed_create_holds_back_every_change_to_its_user(server, spec): + """An admin with ALTER USER and GRANT but not CREATE USER + fails the create even when someone else has made the user in the window. Their user keeps + their password, so it must not get the grants.""" + server.hold(spec) + server.tables["users"] = [row for row in server.tables["users"] if row["name"] != "dashboards"] + server.tables["role_grants"] = [ + row for row in server.tables["role_grants"] if row["user_name"] != "dashboards" + ] + server.failing = {"CREATE USER IF NOT EXISTS `dashboards`": "Code: 497. no. (ACCESS_DENIED)"} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert not any(sql.startswith("GRANT `analyst` TO `dashboards`") for sql in sent(server)) + assert ( + "! skipped: grant role analyst to user dashboards, because its create failed, " + "so this run gives it nothing more" in result.stderr.splitlines() + ) + + +def test_a_failed_reset_holds_back_every_change_to_its_user(server, spec): + """An admin without ALTER USER, or a user someone else made between the + read and the create, keeps a password this run didn't set: it gets no new access, and no + revoke runs anywhere.""" + server.hold(spec) + holds_instead(server, "dashboards", "old") + server.failing = {"ALTER USER `dashboards`": "Code: 497. no. (ACCESS_DENIED)"} + result = run("apply", "dev", "--reset-passwords") + assert result.exit_code == 1, result.output + assert sent(server) == ["ALTER USER `dashboards` IDENTIFIED BY {password:String}"] + skipped = [line for line in result.stderr.splitlines() if line.startswith("! skipped: ")] + assert skipped == [ + "! skipped: grant role analyst to user dashboards, because its password reset failed, " + "so this run gives it nothing more", + "! skipped: revoke role old from user dashboards, because its password reset failed, " + "so this run gives it nothing more", + ] + + +def test_a_user_made_in_the_window_gets_no_grant_when_its_reset_fails(server, spec): + """The create keeps someone else's password, and the reset + that would replace it fails, so the user is granted nothing.""" + server.hold(spec) + server.tables["users"] = [row for row in server.tables["users"] if row["name"] != "dashboards"] + server.tables["role_grants"] = [ + row for row in server.tables["role_grants"] if row["user_name"] != "dashboards" + ] + server.failing = {"ALTER USER `dashboards`": "Code: 497. no. (ACCESS_DENIED)"} + result = run("apply", "dev", "--reset-passwords") + assert result.exit_code == 1, result.output + assert not any(sql.startswith("GRANT `analyst` TO `dashboards`") for sql in sent(server)) + + +def test_a_failure_shows_the_servers_message_with_no_secret(server, spec): + message = ( + "Received ClickHouse exception, code: 36, server response: Code: 36. DB::Exception: " + f"bad password {PASSWORDS['DASHBOARDS']}. (BAD_ARGUMENTS) (for url http://localhost:8123)" + ) + server.failing = {"CREATE USER IF NOT EXISTS `dashboards`": message} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert ( + "✗ create user dashboards: bad password [hidden]. (BAD_ARGUMENTS)" + in result.stderr.splitlines() + ) + + +def test_an_empty_secret_hides_nothing(server, monkeypatch): + """A secret can be empty, as an SSM parameter can. Hiding "" would mark every gap.""" + monkeypatch.setattr("ch_migrate.access.applier.read_secret", lambda settings, name: "") + message = "Code: 36. DB::Exception: bad password. (BAD_ARGUMENTS)" + server.failing = {"CREATE USER IF NOT EXISTS `dashboards`": message} + result = run("apply", "dev") + assert result.exit_code == 1, result.output + assert "✗ create user dashboards: bad password. (BAD_ARGUMENTS)" in result.stderr.splitlines() diff --git a/tests/access/test_bootstrap_command.py b/tests/access/test_bootstrap_command.py new file mode 100644 index 0000000..80fa6a6 --- /dev/null +++ b/tests/access/test_bootstrap_command.py @@ -0,0 +1,343 @@ +"""`ch-migrate bootstrap` without a server: what it sends, as whom, and how it exits (2.5). + +The admin's and the migration user's connections are `FakeServer`s, opened through +`open_client`. Exit 2 means that nothing was written, so every exit-2 test also checks that +no write was sent. `tests/integration/test_access_bootstrap.py` runs the statements. +""" + +import os +import socket + +import pytest +from click.testing import CliRunner +from fake_access_server import FakeServer + +from ch_migrate.access.loader import validate_access +from ch_migrate.access.planner import Plan +from ch_migrate.access.settings import load_settings +from ch_migrate.cli import main + +CORE = "migration_role:\n profile: core\n" +DENIED = "Code: 497. Not enough privileges. (ACCESS_DENIED)" +DECLARED = CORE + "roles:\n analyst: {grants: ['SELECT ON {db}.*']}\n" +PASSWORDS = {"ADMIN": "Adm!" + "3c" * 12, "MIGRATION": "Migr!" + "2b" * 12} + + +def bootstrap(*args): + result = CliRunner().invoke(main, ["bootstrap", *args]) + assert result.exception is None or isinstance(result.exception, SystemExit), result.output + return result + + +@pytest.fixture +def servers(project, monkeypatch): + """The admin's server and the migration user's, by login; secrets set.""" + logins = {"shop_admin": FakeServer(storage="local_directory"), "shop_migrator": FakeServer()} + opened = [] + + def open_client(settings, login): + opened.append(login.user) + return logins[login.user] + + monkeypatch.setattr("ch_migrate.access.bootstrap.open_client", open_client) + for name, value in PASSWORDS.items(): + monkeypatch.setenv(f"CH_DEV_{name}_PASSWORD", value) + admin = logins["shop_admin"] + admin.opened = opened + return admin, logins["shop_migrator"] + + +@pytest.fixture +def offline(monkeypatch): + """No CH_* variables, and any socket use fails the test.""" + for name in [name for name in os.environ if name.startswith("CH_")]: + monkeypatch.delenv(name) + + def refuse(*args, **kwargs): + raise AssertionError("bootstrap --dry-run opened a socket") + + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setattr(socket, "create_connection", refuse) + monkeypatch.setattr(socket, "getaddrinfo", refuse) + + +def declaration(project): + return validate_access(load_settings("dev", project / "config.yaml"), project).spec + + +def set_config(project, line): + """Add one line under the `dev` environment in config.yaml.""" + path = project / "config.yaml" + path.write_text( + path.read_text().replace(" host: localhost\n", f" host: localhost\n{line}\n", 1) + ) + + +def sent(server): + return [write.sql for write in server.writes] + + +@pytest.mark.parametrize("access_yaml", [None, DECLARED]) +def test_dry_run_needs_no_secret_and_no_network(project, offline, access_yaml): + if access_yaml: + (project / "access.yaml").write_text(access_yaml) + result = bootstrap("dev", "--dry-run") + assert result.exit_code == 0, result.output + statements = [line for line in result.stdout.splitlines() if not line.startswith("--")] + assert statements[:4] == [ + "CREATE DATABASE IF NOT EXISTS shop_dev;", + "CREATE ROLE IF NOT EXISTS shop_migration_role;", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY ;", + "GRANT shop_migration_role TO shop_migrator;", + ] + # With access.yaml, bootstrap makes the migration identity only: `apply` makes the rest. + assert "analyst" not in result.stdout + assert ("WITH GRANT OPTION" in result.stdout) == (access_yaml is None) + + +@pytest.mark.parametrize("password_set", [False, True]) +def test_dry_run_leaves_out_an_optional_user_with_no_password_set( + project, offline, monkeypatch, password_set +): + """--dry-run shows what the real run makes, and still reads no secret: + it asks only whether CH__MCP_PASSWORD or an SSM path is set.""" + set_config(project, " mcp_user_name: shop_mcp") + if password_set: + monkeypatch.setenv("CH_DEV_MCP_PASSWORD", "never-read") + result = bootstrap("dev", "--dry-run") + assert result.exit_code == 0, result.output + assert ("shop_mcp" in result.stdout) is password_set + assert "never-read" not in result.output + assert ("skips that user" in result.stderr) is not password_set + + +def test_dry_run_says_where_on_cluster_would_apply(project, offline): + (project / "access.yaml").write_text(CORE) + set_config(project, " cluster: shop_cluster") + result = bootstrap("dev", "--dry-run") + assert result.exit_code == 0, result.output + assert "-- With cluster shop_cluster set, bootstrap runs each statement ON CLUSTER" in ( + result.stdout + ) + statements = [line for line in result.stdout.splitlines() if not line.startswith("--")] + for form in (" ON CLUSTER shop_cluster", " ON CLUSTER `shop_cluster`"): + assert statements and not any(form in sql for sql in statements), statements + + +def test_legacy_sends_every_statement_roles_and_users_first(project, servers): + """No access.yaml: 0.8's statements, on every run, never ON CLUSTER (Decision 13).""" + admin, migration = servers + set_config(project, " cluster: shop_cluster") + admin.converges_to = declaration(project) + for _ in range(2): + result = bootstrap("dev") + assert result.exit_code == 0, result.output + statements = sent(admin) + assert len(statements) == 2 * 27 # 0.8's 27 statements, the database's included + assert statements[:4] == [ + "CREATE DATABASE IF NOT EXISTS `shop_dev`", + "CREATE ROLE IF NOT EXISTS `shop_migration_role`", + "CREATE USER IF NOT EXISTS `shop_migrator` IDENTIFIED BY {password:String}", + "GRANT `shop_migration_role` TO `shop_migrator`", + ] + assert not any("ON CLUSTER" in sql for sql in statements) + assert "GRANT CURRENT GRANTS(READ ON REMOTE) TO `shop_migration_role`" in statements + assert admin.opened == ["shop_admin", "shop_migrator"] * 2 + assert result.stdout.splitlines()[-3:-1] == [ + "✓ user shop_migrator holds every required grant of role shop_migration_role (15).", + "✓ Bootstrap complete for dev.", + ] + + +@pytest.mark.parametrize( + ("key", "secret", "env"), + [ + ("mcp_user_name", "mcp_password", "CH_DEV_MCP_PASSWORD"), + ("dict_reader_name", "dict_reader_password", "CH_DEV_DICT_READER_PASSWORD"), + ], +) +def test_legacy_skips_an_optional_user_whose_password_isnt_set( + project, servers, monkeypatch, key, secret, env +): + """0.8 made an optional user only when its password was set.""" + admin, migration = servers + monkeypatch.delenv(env, raising=False) + set_config(project, f" {key}: shop_extra") + admin.converges_to = declaration(project) + result = bootstrap("dev") + assert result.exit_code == 0, result.output + assert not any("shop_extra" in sql for sql in sent(admin)), sent(admin) + assert ( + f"! {key} names shop_extra, but {secret} isn't set, so `bootstrap` skips that user " + "and its role, as 0.8 did." + ) in result.stderr.splitlines() + + +def test_legacy_attempts_every_grant_and_names_each_failure(project, servers): + """Decision 6: one refused GRANT doesn't stop the rest; a refused best-effort one warns.""" + admin, migration = servers + admin.failing = { + "CREATE FUNCTION": "Code: 497. Not enough privileges. (ACCESS_DENIED)", + "CURRENT GRANTS(READ ON REMOTE)": "Code: 62. Syntax error. (SYNTAX_ERROR)", + } + migration.lacking = {"CREATE FUNCTION"} + result = bootstrap("dev") + assert result.exit_code == 1, result.output + assert len(sent(admin)) == 27 + errors = [line for line in result.stderr.splitlines() if line.startswith("✗")] + assert errors == [ + "✗ grant CREATE FUNCTION, DROP FUNCTION ON *.* WITH GRANT OPTION to role " + "shop_migration_role: Code: 497. Not enough privileges. (ACCESS_DENIED)", + "✗ user shop_migrator lacks CREATE FUNCTION, DROP FUNCTION ON *.*", + "✗ user shop_migrator lacks 1 of the 15 required grants of role shop_migration_role.", + "✗ Bootstrap of dev isn't complete: 1 change failed; " + "user shop_migrator lacks 1 required grant.", + ] + assert ( + "! grant role shop_migration_role as much of READ ON REMOTE as the admin holds " + "(best-effort): Code: 62. Syntax error. (SYNTAX_ERROR)" + ) in result.stderr + + +@pytest.mark.parametrize("access_yaml", [CORE, None], ids=["access.yaml", "legacy"]) +def test_a_server_older_than_25_8_exits_2_before_any_write(project, servers, access_yaml): + """Every bootstrap needs 25.8, legacy too: 0.8's failed on 24.8.""" + admin, migration = servers + if access_yaml is not None: + (project / "access.yaml").write_text(access_yaml) + admin.server_version = "24.8.14.39" + result = bootstrap("dev") + assert result.exit_code == 2, result.output + assert "The server runs ClickHouse 24.8.14.39." in result.stderr + assert admin.writes == [] + + +def test_with_access_yaml_only_the_migration_identity_is_made(project, servers): + admin, migration = servers + (project / "access.yaml").write_text(DECLARED) + spec = declaration(project) + admin.converges_to = spec.__class__(spec.environment, spec.migration) + result = bootstrap("dev") + assert result.exit_code == 0, result.output + assert sent(admin)[:3] == [ + "CREATE DATABASE IF NOT EXISTS `shop_dev`", + "CREATE ROLE IF NOT EXISTS `shop_migration_role`", + "CREATE USER IF NOT EXISTS `shop_migrator` IDENTIFIED BY {password:String}", + ] + assert not any("analyst" in sql or "WITH GRANT OPTION" in sql for sql in sent(admin)) + assert result.stdout.splitlines()[:2] == [ + "→ Bootstrapping dev: database shop_dev on localhost, as shop_admin, " + "with the core profile", + "+ create database shop_dev if it doesn't exist", + ] + # Run again: in sync, so only the database's IF NOT EXISTS goes out. + admin.writes.clear() + assert bootstrap("dev").exit_code == 0 + assert sent(admin) == ["CREATE DATABASE IF NOT EXISTS `shop_dev`"] + + +def test_changes_still_pending_after_the_writes_are_named_and_exit_1(project, servers): + """A replica still behind at the deadline leaves the migration + identity pending, though the check on the node connected to passes.""" + admin, migration = servers + (project / "access.yaml").write_text(DECLARED) + set_config(project, " access_read_timeout: 0") + result = bootstrap("dev") # the admin's server never shows what was written + assert result.exit_code == 1, result.output + assert "→ Still pending for dev:" in result.stdout.splitlines() + assert "+ create role shop_migration_role" in result.stdout.splitlines() + assert result.stderr.splitlines()[-1].startswith("✗ Bootstrap of dev isn't complete: ") + assert "still pending" in result.stderr.splitlines()[-1] + + +@pytest.mark.parametrize( + ("failing", "closing"), + [ + ({}, "planning again found 2 errors"), + ({"CREATE ROLE": DENIED}, "1 change failed; planning again found 2 errors"), + ], + ids=["plan errors only", "a failed change too"], +) +def test_the_closing_line_counts_failed_changes_apart_from_plan_errors( + project, servers, monkeypatch, failing, closing +): + """An error in the plan read back after the writes isn't a failed change, but it still + leaves the bootstrap incomplete, with exit 1.""" + admin, migration = servers + (project / "access.yaml").write_text(CORE) + admin.failing = failing + errors = Plan(errors=("first error", "second error")) + monkeypatch.setattr("ch_migrate.access.applier.replan", lambda work, outcome: errors) + result = bootstrap("dev") + assert result.exit_code == 1, result.output + assert result.stderr.splitlines()[-1] == f"✗ Bootstrap of dev isn't complete: {closing}." + + +def test_with_access_yaml_a_migration_user_that_is_the_admin_exits_2(project, servers): + admin, migration = servers + (project / "access.yaml").write_text(CORE) + config = project / "config.yaml" + config.write_text( + config.read_text().replace("admin_user: shop_admin", "admin_user: shop_migrator", 1) + ) + migration.opened = [] + result = bootstrap("dev") + assert result.exit_code == 2, result.output + assert "is config.yaml's admin_user" in result.stderr + assert migration.writes == [] and admin.writes == [] + + +@pytest.mark.parametrize("access_yaml", [None, CORE]) +def test_a_missing_secret_exits_2_before_any_write(project, servers, monkeypatch, access_yaml): + admin, migration = servers + if access_yaml: + (project / "access.yaml").write_text(access_yaml) + monkeypatch.delenv("CH_DEV_MIGRATION_PASSWORD") + result = bootstrap("dev") + assert result.exit_code == 2, result.output + assert "CH_DEV_MIGRATION_PASSWORD" in result.stderr + assert admin.writes == [] + + +def test_an_invalid_access_yaml_exits_2_listing_each_error(project, servers): + admin, migration = servers + (project / "access.yaml").write_text("migration_role: {profile: nope}\nusers: [x]\n") + result = bootstrap("dev") + assert result.exit_code == 2, result.output + assert result.stderr.splitlines()[-1] == "✗ Invalid: 2 errors." + assert admin.opened == [] + + +def test_an_empty_access_yaml_exits_2_instead_of_giving_core(project, servers): + """An empty file isn't legacy mode, and isn't core either.""" + admin, migration = servers + (project / "access.yaml").write_text("") + result = bootstrap("dev") + assert result.exit_code == 2, result.output + assert "access.yaml is empty" in result.stderr + assert admin.opened == [] + + +def test_ctrl_c_during_a_write_exits_130(project, servers): + """The code `run` returns reaches the command line, as `up`'s does.""" + admin, migration = servers + + def interrupt(sql, parameters=None, settings=None): + answer = FakeServer.command(admin, sql, parameters, settings) + if admin.writes: # a CHECK GRANT while reading isn't a write + raise KeyboardInterrupt + return answer + + admin.command = interrupt + result = bootstrap("dev") + assert result.exit_code == 130, result.output + assert "`bootstrap` stopped part-way: interrupted." in result.stderr + + +def test_verbose_prints_each_statement_and_never_a_password(project, servers): + admin, migration = servers + admin.converges_to = declaration(project) + result = bootstrap("dev", "--verbose") + assert result.exit_code == 0, result.output + assert " CREATE ROLE IF NOT EXISTS `shop_migration_role`;" in result.stdout + assert not any(password in result.output for password in PASSWORDS.values()) diff --git a/tests/access/test_check_command.py b/tests/access/test_check_command.py new file mode 100644 index 0000000..209207a --- /dev/null +++ b/tests/access/test_check_command.py @@ -0,0 +1,99 @@ +"""`access check` without a server: what it checks, as whom, and how it exits (2.5). + +The migration user's connection is a `FakeServer` that answers each `CHECK GRANT`. Statements +are checked by text here; `tests/integration/test_access_bootstrap.py` runs them. +""" + +import pytest +from click.testing import CliRunner +from fake_access_server import FakeServer + +from ch_migrate.cli import main + +CORE_REQUIRED = 8 +CORE_BEST_EFFORT = 6 + + +def run(*args): + result = CliRunner().invoke(main, ["access", *args]) + assert result.exception is None or isinstance(result.exception, SystemExit), result.output + return result + + +@pytest.fixture +def server(project, monkeypatch): + """The migration user's connection; records who logged in, through `connect`.""" + fake = FakeServer() + fake.logins = [] + + def open_client(settings, login): + fake.logins.append(login) + return fake + + monkeypatch.setattr("ch_migrate.access.server.open_client", open_client) + return fake + + +def core(project, extra=""): + (project / "access.yaml").write_text("migration_role:\n profile: core\n" + extra) + + +def test_every_grant_held_exits_0_as_the_migration_user(project, server): + core(project) + result = run("check", "dev") + assert (result.exit_code, result.stderr) == (0, ""), result.output + assert result.stdout == ( + "✓ user shop_migrator holds every required grant of role shop_migration_role (8).\n" + ) + [login] = server.logins + assert (login.user, login.secret) == ("shop_migrator", "migration_password") + assert len(server.checks) == CORE_REQUIRED + CORE_BEST_EFFORT + assert server.writes == [] and server.closed + + +def test_each_grant_is_checked_as_its_flags_on_its_target(project, server): + """CHECK GRANT on a group checks flags its target can't hold, so leaves are sent.""" + run("check", "dev") # legacy mode: no access.yaml + assert ( + "CHECK GRANT ALTER ROW POLICY, CREATE ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES " + "ON `shop_dev`.*" + ) in server.checks + assert "CHECK GRANT READ ON REMOTE" in server.checks + assert not any("GRANT OPTION" in sql for sql in server.checks) + + +def test_a_missing_required_grant_exits_1_naming_it(project, server): + core(project) + server.lacking = {"`system`.`mutations`"} + result = run("check", "dev") + assert result.exit_code == 1, result.output + assert result.stdout == "" + assert result.stderr.splitlines() == [ + "✗ user shop_migrator lacks SELECT ON system.mutations", + "✗ user shop_migrator lacks 1 of the 8 required grants of role shop_migration_role.", + ] + + +def test_a_missing_best_effort_grant_warns_and_exits_0(project, server): + core(project) + server.lacking = {"CLUSTER ON"} + result = run("check", "dev") + assert result.exit_code == 0, result.output + assert result.stderr == "! best-effort: user shop_migrator lacks CLUSTER ON *.*\n" + + +def test_migration_role_grants_are_checked_too(project, server): + core(project, " grants:\n - CREATE FUNCTION ON *.*\n") + server.lacking = {"CREATE FUNCTION"} + result = run("check", "dev") + assert result.exit_code == 1, result.output + assert "✗ user shop_migrator lacks CREATE FUNCTION ON *.*" in result.stderr + + +def test_a_server_older_than_25_8_exits_2_naming_its_version(project, server): + core(project) + server.server_version = "24.8.14.39" + result = run("check", "dev") + assert result.exit_code == 2, result.output + assert "ClickHouse 24.8.14.39" in result.stderr + assert server.checks == [] diff --git a/tests/access/test_duplicate_keys.py b/tests/access/test_duplicate_keys.py new file mode 100644 index 0000000..ef6f86d --- /dev/null +++ b/tests/access/test_duplicate_keys.py @@ -0,0 +1,182 @@ +"""A key written twice in one mapping of access.yaml is an error, at any depth. + +YAML keeps the last of two equal keys and drops the first silently, so two `analyst:` +entries would become one, and a later `plan` would revoke the first one's grants. Each +error names the file, the key path, the key and both of its lines. +""" + +import textwrap + +import pytest +import yaml +from click.testing import CliRunner + +from ch_migrate.access.document import Document, parse_document +from ch_migrate.cli import main + +KEEPS_LAST = "YAML would silently keep only the last" + + +def errors(result): + return [str(problem) for problem in result.errors] + + +@pytest.mark.parametrize( + "text, error", + [ + pytest.param( + "roles:\n analyst:\n grants: ['SELECT ON {db}.*']\n loader: {}\n" + " analyst:\n grants: ['INSERT ON {db}.events']\n", + f"access.yaml: roles.analyst: duplicate key analyst on lines 2 and 5; {KEEPS_LAST}", + id="role-declared-twice", + ), + pytest.param( + "users:\n etl: {password: {secret: etl_password}, roles: [loader]}\n" + " etl: {password: {secret: etl_password}}\n", + f"access.yaml: users.etl: duplicate key etl on lines 2 and 3; {KEEPS_LAST}", + id="user-declared-twice", + ), + pytest.param( + "roles:\n analyst:\n grants: ['SELECT ON {db}.*']\n roles: []\n" + " grants: ['SELECT ON {db}.events']\n", + "access.yaml: roles.analyst.grants: " + f"duplicate key grants on lines 3 and 5; {KEEPS_LAST}", + id="entry-key-twice", + ), + pytest.param( + "users:\n etl: {password: {secret: etl_password}}\nenvironments:\n" + " production:\n users:\n etl: {absent: true}\n etl: {roles: []}\n", + "access.yaml: environments.production.users.etl: " + f"duplicate key etl on lines 6 and 7; {KEEPS_LAST}", + id="unselected-environment", + ), + ( + "roles: {}\nusers: {}\nroles: {}\n", + f"access.yaml: roles: duplicate key roles on lines 1 and 3; {KEEPS_LAST}", + ), + ( + "environments:\n production: {}\n production: {}\n", + "access.yaml: environments.production: " + f"duplicate key production on lines 2 and 3; {KEEPS_LAST}", + ), + ( + "users:\n etl:\n password: {secret: a, secret: b}\n", + "access.yaml: users.etl.password.secret: " + f"duplicate key secret on line 3, columns 16 and 27; {KEEPS_LAST}", + ), + ( + "roles: {a: {grants: [{grant: CLUSTER ON *.*, grant: SELECT ON x.*}]}}\n", + "access.yaml: roles.a.grants[0].grant: " + f"duplicate key grant on line 1, columns 23 and 46; {KEEPS_LAST}", + ), + ], +) +def test_duplicates_at_any_depth(validate, text, error): + result = validate(text) + assert errors(result) == [error] + assert result.spec is None + + +def test_each_repeat_is_named_against_the_first(validate): + result = validate("roles:\n r: {}\n r: {}\n r: {}\n") + assert errors(result) == [ + f"access.yaml: roles.r: duplicate key r on lines 2 and 3; {KEEPS_LAST}", + f"access.yaml: roles.r: duplicate key r on lines 2 and 4; {KEEPS_LAST}", + ] + + +def test_duplicates_are_listed_with_every_other_error(validate): + result = validate( + """\ + roles: + a: {grant: []} + a: {grants: [SELECT ON x.t*]} + """ + ) + assert errors(result) == [ + f"access.yaml: roles.a: duplicate key a on lines 2 and 3; {KEEPS_LAST}", + "access.yaml: roles.a.grants[0]: `SELECT ON x.t*`: " + "prefix targets such as `x.t*` aren't supported in v1", + ] + + +def test_validate_exits_2_on_a_duplicate(project): + (project / "access.yaml").write_text("roles:\n analyst: {}\n analyst: {}\n") + result = CliRunner().invoke(main, ["access", "validate", "dev"]) + assert result.exit_code == 2, result.output + assert result.stdout == "" + assert result.stderr.splitlines() == [ + f"✗ access.yaml: roles.analyst: duplicate key analyst on lines 2 and 3; {KEEPS_LAST}", + "✗ Invalid: 1 error.", + ] + + +@pytest.mark.parametrize( + "text", + [ + "", + "# nothing declared yet\n", + "- roles\n", + """\ + migration_role: + profile: core + grants: [CREATE FUNCTION, DROP FUNCTION ON *.*] + roles: + analyst: {grants: ['SELECT, SHOW TABLES ON {db}.*']} + '{project}_reader': {grants: [{grant: CLUSTER ON *.*, best_effort: true}]} + users: + dashboards: {password: {secret: dashboards_password}, roles: [analyst]} + environments: + production: + users: + dashboards: {absent: true} + """, + """\ + base: &base {grants: ['SELECT ON {db}.*'], roles: [analyst]} + roles: + a: + <<: *base + grants: ['INSERT ON {db}.t'] + b: *base + flags: {yes: on, no: off, 010: 0x10, when: 2026-11-12, '2': two, 2: dos} + """, + ], +) +def test_a_file_without_duplicates_parses_as_safe_load_does(text): + text = textwrap.dedent(text) + assert parse_document(text) == Document(yaml.safe_load(text)) + + +@pytest.mark.parametrize( + "text", + [ + "roles:\n a: {grants: [SELECT ON {db}.*]}\n", + "? [a]\n: 1\n", + "!!map a: 1\n", + "a: 1\n---\nb: 2\n", + ], +) +def test_invalid_yaml_fails_as_safe_load_does(text): + with pytest.raises(yaml.YAMLError) as expected: + yaml.safe_load(text) + with pytest.raises(type(expected.value)) as raised: + parse_document(text) + assert str(raised.value) == str(expected.value) + + +def test_keys_yaml_reads_as_equal_are_one_key(): + document = parse_document("a:\n yes: 1\n true: 2\n") + assert document.data == {"a": {True: 2}} + assert [duplicate.path for duplicate in document.duplicates] == ["a.True"] + + +def test_a_merge_key_repeats_nothing_but_a_quoted_one_is_a_key(): + merged = parse_document("b: &b {x: 1}\nc: &c {y: 2}\na:\n <<: *b\n <<: *c\n x: 3\n") + assert (merged.data["a"], merged.duplicates) == ({"x": 3, "y": 2}, ()) + quoted = parse_document("a:\n '<<': 1\n '<<': 2\n") + assert [duplicate.path for duplicate in quoted.duplicates] == ["a.<<"] + + +def test_an_aliased_mapping_is_reported_once(): + document = parse_document("x: &m {a: 1, a: 2}\ny: *m\n") + assert [duplicate.path for duplicate in document.duplicates] == ["x.a"] diff --git a/tests/access/test_grant_parser.py b/tests/access/test_grant_parser.py new file mode 100644 index 0000000..20fc9e1 --- /dev/null +++ b/tests/access/test_grant_parser.py @@ -0,0 +1,215 @@ +"""The grant syntax (2.3): ` ON [WITH GRANT OPTION]`, checked offline.""" + +import pytest + +from ch_migrate.access.grants import GrantSyntaxError, check_grant, parse_grant +from ch_migrate.access.model import Grant, Target +from ch_migrate.access.privileges import bundled_tree + +TREE = bundled_tree() + + +@pytest.mark.parametrize( + "text, expected", + [ + ("SELECT ON *.*", Grant(("SELECT",), Target())), + ("SELECT ON shop.*", Grant(("SELECT",), Target("shop"))), + ("SELECT, INSERT ON shop.events", Grant(("SELECT", "INSERT"), Target("shop", "events"))), + ("READ ON REMOTE", Grant(("READ",), Target(source="REMOTE"))), + ( + "ALTER UPDATE ,ALTER DELETE ON shop.events WITH GRANT OPTION", + Grant(("ALTER UPDATE", "ALTER DELETE"), Target("shop", "events"), grant_option=True), + ), + ("select on shop.* with grant option", Grant(("select",), Target("shop"), True)), + ], +) +def test_parses_privileges_target_and_grant_option(text, expected): + assert parse_grant(text) == expected + + +def test_best_effort_is_carried_on_the_grant(): + assert parse_grant("CLUSTER ON *.*", best_effort=True).best_effort + + +@pytest.mark.parametrize( + "text, reason", + [ + (" ", "the grant is empty"), + ("GRANT SELECT ON shop.*", "write it without the leading GRANT"), + ( + "CURRENT GRANTS(SELECT ON shop.*)", + "write a best-effort grant as {grant: ..., best_effort: true}", + ), + ( + "SELECT ON shop.* TO analyst", + "drop the TO clause: it goes to the user or role it's under", + ), + ("SELECT ON shop.* WITH REPLACE OPTION", "only WITH GRANT OPTION is allowed"), + ("SELECT ON shop.* WITH ADMIN OPTION", "only WITH GRANT OPTION is allowed"), + ("SELECT shop.*", "expected ` ON [WITH GRANT OPTION]`"), + ("SELECT ON shop.* WITH GRANT", "expected ` ON [WITH GRANT OPTION]`"), + ( + "SELECT(id, name) ON shop.events", + "column grants, such as SELECT(id), aren't supported in v1", + ), + ("SELECT, , INSERT ON shop.*", "a privilege in the list is empty"), + ( + "FOO; DROP ROLE x ON *.*", + "`FOO; DROP ROLE x` isn't a privilege name: use letters, digits, underscores and spaces", + ), + ( + "SELECT' ON shop.*", + "`SELECT'` isn't a privilege name: use letters, digits, underscores and spaces", + ), + ], +) +def test_syntax_errors_say_why(text, reason): + with pytest.raises(GrantSyntaxError) as error: + parse_grant(text) + assert str(error.value) == reason + + +TARGET_FORMS = "write `*.*`, `.*`, `.
` or a source such as `REMOTE`" + + +@pytest.mark.parametrize( + "target, reason", + [ + ("*", f"`*` isn't a target: {TARGET_FORMS}"), + ("*.events", f"`*.events` isn't a target: {TARGET_FORMS}"), + ("shop.t*", "prefix targets such as `shop.t*` aren't supported in v1"), + ("sh*.*", "prefix targets such as `sh*.*` aren't supported in v1"), + ("shop.ev*nts", "prefix targets such as `shop.ev*nts` aren't supported in v1"), + ( + "my-db.*", + "Invalid database name: 'my-db'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ( + "shop.a.b", + "Invalid table name: 'a.b'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ], +) +def test_targets_are_star_star_db_star_db_table_or_a_source(target, reason): + with pytest.raises(GrantSyntaxError) as error: + parse_grant(f"SELECT ON {target}") + assert str(error.value) == reason + + +@pytest.mark.parametrize( + "written, canonical", + [ + ("DELETE", "ALTER DELETE"), + ("update", "ALTER UPDATE"), + ("SYNC REPLICA", "SYSTEM SYNC REPLICA"), + ("all privileges", "ALL"), + ("select", "SELECT"), + ("dictget", "dictGet"), + ], +) +def test_aliases_become_canonical_names(written, canonical): + checked = check_grant(parse_grant(f"{written} ON shop.*"), TREE) + assert checked.grant.privileges == (canonical,) + assert not checked.errors and not checked.warnings + + +def test_an_unknown_privilege_is_a_warning_and_kept_as_written(): + checked = check_grant(parse_grant("SELECT, SELEKT ON shop.*"), TREE) + assert checked.grant.privileges == ("SELECT", "SELEKT") + assert checked.errors == () + assert checked.warnings == ( + "ClickHouse 26.3 has no privilege named SELEKT; `access plan` checks it on the server", + ) + + +@pytest.mark.parametrize( + "text, error", + [ + ( + "REMOTE ON *.*", + "this is the old spelling of a source grant: write `READ, WRITE ON REMOTE`", + ), + ("s3 ON *.*", "this is the old spelling of a source grant: write `READ, WRITE ON S3`"), + ( + "SOURCES ON *.*", + "this is the old spelling of a source grant: write `READ, WRITE ON *.*`", + ), + ( + "CLUSTER, REMOTE ON *.*", + "REMOTE is the old spelling of a source grant: " + "write `READ, WRITE ON REMOTE` in an entry of its own", + ), + ], +) +def test_the_old_source_spelling_is_rejected_naming_the_new_one(text, error): + assert check_grant(parse_grant(text), TREE).errors == (error,) + + +@pytest.mark.parametrize( + "text, privileges, target", + [ + ("READ ON REMOTE", ("READ",), Target(source="REMOTE")), + ("read, write on remote", ("READ", "WRITE"), Target(source="REMOTE")), + ("WRITE ON S3", ("WRITE",), Target(source="S3")), + ("READ, WRITE ON *.*", ("READ", "WRITE"), Target()), + ], +) +def test_read_and_write_take_a_source(text, privileges, target): + checked = check_grant(parse_grant(text), TREE) + assert (checked.errors, checked.warnings) == ((), ()) + assert (checked.grant.privileges, checked.grant.target) == (privileges, target) + + +@pytest.mark.parametrize( + "text, error", + [ + ("READ ON shop.*", "READ takes a source, as in `READ ON REMOTE`, or `*.*` for all"), + ("WRITE ON shop.events", "WRITE takes a source, as in `READ ON REMOTE`, or `*.*` for all"), + ( + "READ, WRITE ON shop.*", + "READ and WRITE take a source, as in `READ ON REMOTE`, or `*.*` for all", + ), + ( + "SELECT ON events", + "only READ and WRITE take a source as their target; a table is `.
`", + ), + ( + "READ, SELECT ON S3", + "only READ and WRITE take a source as their target; a table is `.
`", + ), + ], +) +def test_sources_and_tables_are_not_mixed_up(text, error): + assert check_grant(parse_grant(text), TREE).errors == (error,) + + +def test_an_unknown_source_is_a_warning(): + checked = check_grant(parse_grant("READ ON NOWHERE"), TREE) + assert checked.errors == () + assert checked.warnings == ("the bundled 26.3 list has no source named NOWHERE",) + + +@pytest.mark.parametrize( + "text, where", + [ + ("CLUSTER ON shop.*", "a database (`.*`)"), + ("CREATE DATABASE ON shop.events", "a table"), + ], +) +def test_a_privilege_that_cannot_apply_to_its_target_is_a_warning(text, where): + checked = check_grant(parse_grant(text), TREE) + privilege = text.split(" ON ")[0] + assert checked.warnings == ( + f"in ClickHouse 26.3, {privilege} can't be granted on {where}, so the server rejects it", + ) + + +def test_a_source_name_must_be_an_identifier(): + with pytest.raises(GrantSyntaxError) as error: + parse_grant("READ ON my-src") + assert str(error.value) == ( + "Invalid source name: 'my-src'. " + "Must start with letter/underscore and contain only alphanumeric/underscore." + ) diff --git a/tests/access/test_init_access_yaml.py b/tests/access/test_init_access_yaml.py new file mode 100644 index 0000000..5f104b1 --- /dev/null +++ b/tests/access/test_init_access_yaml.py @@ -0,0 +1,52 @@ +"""`init` writes an access.yaml: the core profile, with commented examples (Decision 5).""" + +import re + +import yaml +from click.testing import CliRunner + +from ch_migrate.cli import main + +# A commented line of YAML in the examples: a key, or a list item, after `# `. +EXAMPLE_LINE = re.compile(r"^(\s*)# (?=\s*(?:[\w-]+:|- ))", re.MULTILINE) + + +def init(path): + result = CliRunner().invoke(main, ["init", str(path), "--name", "shop"]) + assert result.exit_code == 0, result.output + return result + + +def validate(): + return CliRunner().invoke(main, ["access", "validate", "dev"]) + + +def test_init_writes_access_yaml_with_only_the_core_profile(tmp_path, monkeypatch): + result = init(tmp_path) + assert "Created access.yaml" in result.stdout + assert yaml.safe_load((tmp_path / "access.yaml").read_text()) == { + "migration_role": {"profile": "core"} + } + monkeypatch.chdir(tmp_path) + checked = validate() + assert checked.exit_code == 0, checked.output + assert "the migration role shop_migration_role holds the core profile" in checked.stdout + + +def test_its_commented_examples_are_valid_once_uncommented(tmp_path, monkeypatch): + init(tmp_path) + path = tmp_path / "access.yaml" + text = path.read_text() + assert "# roles:" in text and "# users:" in text and "# environments:" in text + path.write_text(EXAMPLE_LINE.sub(r"\1", text)) + monkeypatch.chdir(tmp_path) + checked = validate() + assert checked.exit_code == 0, checked.output + assert "2 roles and 1 user declared" in checked.stdout + + +def test_init_keeps_an_existing_access_yaml(tmp_path): + (tmp_path / "access.yaml").write_text("migration_role: {profile: legacy}\n") + result = init(tmp_path) + assert "Skipped access.yaml (already exists)" in result.stdout + assert (tmp_path / "access.yaml").read_text() == "migration_role: {profile: legacy}\n" diff --git a/tests/access/test_node_read.py b/tests/access/test_node_read.py new file mode 100644 index 0000000..6ea2713 --- /dev/null +++ b/tests/access/test_node_read.py @@ -0,0 +1,107 @@ +"""Which node `access plan`, `access apply` and `bootstrap` read, without a server (Decision 14). + +On a cluster whose users and roles are on each node's own disk, they read only the node they +connect to, so each prints one line naming it. The admin's connection and the migration +user's are one `FakeServer`. `tests/integration/test_access_bootstrap.py` runs the same +commands on the local-storage and Keeper cluster fixtures. +""" + +import pytest +from click.testing import CliRunner +from fake_access_server import FakeServer + +from ch_migrate.access.loader import validate_access +from ch_migrate.access.settings import load_settings +from ch_migrate.cli import main + +CORE = "migration_role:\n profile: core\n" +PASSWORDS = {"ADMIN": "Adm!" + "3c" * 12, "MIGRATION": "Migr!" + "2b" * 12} +NAMED = ( + "→ Read node {} only: users and roles are on each node's own disk. After a failed " + "ON CLUSTER apply, run ch-migrate access plan dev against each node." +) +# Each command, and the line of its stdout that names the node: `bootstrap` heads its own. +COMMANDS = [ + (("access", "plan", "dev"), 0), + (("access", "apply", "dev"), 0), + (("bootstrap", "dev"), 1), +] + + +def run(*args): + result = CliRunner().invoke(main, list(args)) + assert result.exception is None or isinstance(result.exception, SystemExit), result.output + return result + + +@pytest.fixture +def server(project, monkeypatch): + """One server for every login, on each node's own disk, with core declared; secrets set.""" + (project / "access.yaml").write_text(CORE) + fake = FakeServer(storage="local_directory") + fake.node = "ch-node-1" + monkeypatch.setattr("ch_migrate.access.cli.connect_admin", lambda settings: fake) + monkeypatch.setattr("ch_migrate.access.bootstrap.open_client", lambda settings, login: fake) + for name, value in PASSWORDS.items(): + monkeypatch.setenv(f"CH_DEV_{name}_PASSWORD", value) + return fake + + +def set_config(project, *lines): + """Add lines under the `dev` environment in config.yaml.""" + path = project / "config.yaml" + added = "".join(f"{line}\n" for line in lines) + path.write_text( + path.read_text().replace(" host: localhost\n", f" host: localhost\n{added}", 1) + ) + + +def named(result): + return [line for line in result.stdout.splitlines() if line.startswith("→ Read node")] + + +@pytest.mark.parametrize(("command", "line"), COMMANDS) +def test_a_local_storage_cluster_names_the_node_read_once(project, server, command, line): + set_config(project, " cluster: shop_cluster") + result = run(*command) + assert named(result) == [NAMED.format("ch-node-1")], result.output + assert result.stdout.splitlines()[line] == NAMED.format("ch-node-1") + + +def test_a_node_that_wont_say_its_name_is_named_by_host_and_port(project, server): + set_config(project, " cluster: shop_cluster", " port: 9123") + server.node = None + result = run("access", "plan", "dev") + assert named(result) == [NAMED.format("localhost:9123")], result.output + + +@pytest.mark.parametrize(("command", "line"), COMMANDS) +@pytest.mark.parametrize( + ("storage", "config"), + [ + ("replicated", (" cluster: shop_cluster", " access_read_timeout: 0")), + ("local_directory", ()), + ], + ids=["keeper", "single node"], +) +def test_keeper_storage_and_a_single_node_name_no_node( + project, server, command, line, storage, config +): + """The server already holds core, so each command runs to its end and exits 0.""" + server.storage = storage + set_config(project, *config) + spec = validate_access(load_settings("dev", project / "config.yaml"), project).spec + server.hold(spec) + server.converges_to = spec + result = run(*command) + assert result.exit_code == 0, result.output + assert named(result) == [], result.output + + +def test_legacy_bootstrap_on_a_cluster_names_no_node(project, server): + """Decision 13: with no access.yaml, `bootstrap` runs on its node as 0.8 does.""" + (project / "access.yaml").unlink() + set_config(project, " cluster: shop_cluster") + result = run("bootstrap", "dev") + assert result.exit_code == 0, result.output + assert named(result) == [], result.output diff --git a/tests/access/test_plan_command.py b/tests/access/test_plan_command.py new file mode 100644 index 0000000..ce3b2a2 --- /dev/null +++ b/tests/access/test_plan_command.py @@ -0,0 +1,354 @@ +"""`access plan` and `access show` without a server: reads after writes, and exit codes. + +The admin's connection is a `FakeServer`. A read that finds nothing is read again before +anything counts as absent (design note, 2.5), and whatever stops a live command exits 2, +because exit 1 means "changes pending". +""" + +import click +import pytest +from click.testing import CliRunner +from fake_access_server import FakeServer, grant_rows + +from ch_migrate import ui +from ch_migrate.access.grants import parse_grant +from ch_migrate.access.loader import validate_access +from ch_migrate.access.server import AccessError +from ch_migrate.access.settings import load_settings +from ch_migrate.cli import main + +ACCESS_YAML = """\ +roles: + analyst: {grants: ['SELECT, SHOW TABLES ON {db}.*']} +users: + dashboards: {password: {secret: dashboards_password}, roles: [analyst]} +""" +IN_SYNC = "✓ In sync for dev (access.yaml): nothing to change.\n" +WAITING = ( + "→ Something isn't on the server yet. Reading again for up to {seconds} s, " + "in case a replica is behind.\n" +) +FALLING_BACK = ( + "→ Can't read every replica at once, so a missing row is read again for up to " + "{seconds} s. {reason}\n" +) + + +def run(*args): + result = CliRunner().invoke(main, ["access", *args]) + assert result.exception is None or isinstance(result.exception, SystemExit), result.output + return result + + +@pytest.fixture +def server(project, monkeypatch): + """A server that holds everything ACCESS_YAML declares, in Keeper storage.""" + (project / "access.yaml").write_text(ACCESS_YAML) + settings = load_settings("dev", project / "config.yaml") + fake = FakeServer() + fake.hold(validate_access(settings, project).spec) + monkeypatch.setattr("ch_migrate.access.cli.connect_admin", lambda settings: fake) + return fake + + +def drop_cluster(server): + """The server holds no CLUSTER grant for anyone.""" + server.tables["grants"] = [ + row for row in server.tables["grants"] if row["access_type"] != "CLUSTER" + ] + + +def not_read_again(result): + """Neither a wait nor a fallback was announced: best-effort warnings may be there.""" + return all(line.startswith("! best-effort: ") for line in result.stderr.splitlines()) + + +def set_read_timeout(project, seconds): + config = (project / "config.yaml").read_text() + (project / "config.yaml").write_text( + config.replace( + " host: localhost\n", f" host: localhost\n access_read_timeout: {seconds}\n" + ) + ) + + +@pytest.mark.parametrize( + "clusters", + [None, [], [{"cluster": "default", "hosts": ["localhost:9000"]}]], + ids=["every replica", "no cluster", "a lone replicated node"], +) +def test_in_sync_reads_once(server, clusters): + if clusters is not None: + server.clusters = clusters + result = run("plan", "dev") + assert (result.exit_code, result.stdout, result.stderr) == (0, IN_SYNC, "") + assert server.reads.count("roles") == 1 and server.closed + + +def test_every_replica_is_read_at_once_so_what_none_holds_is_absent_at_once(server): + """Missing on every replica, a role is absent without a wait (design note, 2.5).""" + server.empty_reads = 1 + result = run("plan", "dev") + assert result.exit_code == 1, result.output + assert "+ create role analyst" in result.stdout.splitlines() + assert not_read_again(result) and server.reads.count("roles") == 1 + assert server.replica_settings[-1] == {"skip_unavailable_shards": 0} + + +def test_replicas_that_disagree_are_read_again_until_they_agree(server): + """One replica shows nothing on the first read: `plan` waits, then reports in sync. The + first read also read the node connected to, as replicas that disagree do.""" + server.behind = {"node-2": 1} + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == WAITING.format(seconds=30) + assert server.reads.count("roles") == 3 + + +def test_replicas_that_still_disagree_at_the_deadline_leave_the_node_connected_to(server, project): + """No row counts as present or absent from replicas that disagree. At + the deadline the node connected to counts, as when only it is read, and one line names + the replicas. Here that node holds everything, so `plan` is in sync.""" + set_read_timeout(project, 0.2) + server.behind = {"node-2": 1000} + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == WAITING.format(seconds=0.2) + ( + "→ Replicas node-1 and node-2 still disagree after 0.2 s, so what the node connected " + "to holds counts.\n" + ) + assert server.reads.count("roles") >= 4 + + +@pytest.mark.parametrize( + ("change", "reason"), + [ + ( + { + "replica_error": "Code: 497. DB::Exception: shop_admin: Not enough privileges. " + "To execute this query, it's necessary to have the grant READ ON REMOTE. " + "(ACCESS_DENIED) (version 26.3.1.1 (official build)) (for url http://db:8123)" + }, + "Reading every replica of cluster default failed: shop_admin: Not enough " + "privileges. To execute this query, it's necessary to have the grant READ ON " + "REMOTE. (ACCESS_DENIED)", + ), + ( + {"clusters": []}, + "No cluster in system.clusters holds this node and another host. " + "If other nodes share these users and roles, set cluster in config.yaml " + "to a cluster that lists them.", + ), + ( + {"clusters": [{"cluster": "default", "hosts": ["localhost:9000"]}]}, + "No cluster in system.clusters holds this node and another host. " + "If other nodes share these users and roles, set cluster in config.yaml " + "to a cluster that lists them.", + ), + ( + { + "clusters": [ + {"cluster": "a", "hosts": ["n1:9000", "n2:9000"]}, + {"cluster": "b", "hosts": ["n1:9000", "n3:9000"]}, + ] + }, + "Clusters a and b hold this node and list different hosts. " + "Set cluster in config.yaml to the cluster whose nodes share these users and roles.", + ), + ], + ids=["no READ ON REMOTE", "no cluster", "a one-host cluster", "two clusters"], +) +def test_when_every_replica_cant_be_read_the_node_is_read_again(server, change, reason): + """The reader says why once when an empty read makes it wait, then reports in sync.""" + for key, value in change.items(): + setattr(server, key, value) + server.empty_reads = 1 + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == WAITING.format(seconds=30) + FALLING_BACK.format( + seconds=30, reason=reason + ) + assert server.reads.count("roles") == 2 + + +TWO_HOSTS = ["node-1:9000", "node-2:9000"] + + +@pytest.mark.parametrize( + "clusters", + [ + [{"cluster": "main", "hosts": TWO_HOSTS}], + # ClickHouse Cloud's `default` and `all_groups.default` list the same hosts. + [{"cluster": "a", "hosts": TWO_HOSTS}, {"cluster": "b", "hosts": TWO_HOSTS}], + # A stock image's `default` lists localhost alone, beside the real cluster. + [ + {"cluster": "default", "hosts": ["localhost:9000"]}, + {"cluster": "main", "hosts": TWO_HOSTS}, + ], + ], + ids=["one cluster", "two with the same hosts", "a one-host default beside it"], +) +def test_the_one_cluster_holding_this_node_and_another_host_is_read_through(server, clusters): + """Every replica is read through the first by name of the clusters that list the same + hosts, so a role missing on all of them is absent at once.""" + server.clusters = clusters + server.empty_reads = 1 + result = run("plan", "dev") + assert result.exit_code == 1, result.output + assert not_read_again(result) and server.reads.count("roles") == 1 + through = [name for name in ("main", "a") if any(c["cluster"] == name for c in clusters)] + assert {parameters["cluster"] for parameters in server.replica_parameters} == set(through) + + +def test_the_configured_cluster_is_read_through_as_given(server, project): + """A configured cluster always wins: no cluster is looked for, even where none would be + found. A replica that can't be reached through it is a fallback, never a failure.""" + config = project / "config.yaml" + config.write_text( + config.read_text().replace( + " host: localhost\n", " host: localhost\n cluster: main\n" + ) + ) + server.clusters = [] + assert run("plan", "dev").stderr == "" + assert "clusters" not in server.reads + assert {parameters["cluster"] for parameters in server.replica_parameters} == {"main"} + server.replica_error = ( + "Code: 279. DB::Exception: All connection tries failed. (ALL_CONNECTION_TRIES_FAILED)" + ) + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == "" + + +def test_a_read_that_finds_nothing_is_read_again_before_it_counts_as_absent(server): + """Reading one node: one empty read, then the real rows. `plan` reports in sync, not 9 + creates and grants.""" + server.clusters = [] + server.empty_reads = 1 + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert WAITING.format(seconds=30) in result.stderr + assert server.reads.count("roles") == 2 + + +def test_what_is_still_missing_at_the_time_limit_is_absent(server, project): + set_read_timeout(project, 0.2) + server.clusters = [] + server.empty_reads = 1000 + result = run("plan", "dev") + assert result.exit_code == 1, result.output + assert "+ create role analyst" in result.stdout.splitlines() + assert WAITING.format(seconds=0.2) in result.stderr + assert server.reads.count("roles") >= 3 + + +def test_a_time_limit_of_0_reads_once(server, project): + set_read_timeout(project, 0) + server.clusters = [] # Even a fallback stays quiet when no wait is allowed. + server.empty_reads = 1 + result = run("plan", "dev") + assert result.exit_code == 1, result.output + assert server.reads.count("roles") == 1 and not_read_again(result) + + +def test_a_nodes_own_disk_is_never_behind_so_it_is_read_once(server): + server.storage = "local_directory" + server.empty_reads = 1 + result = run("plan", "dev") + assert result.exit_code == 1, result.output + assert server.reads.count("roles") == 1 and "Reading again" not in result.stderr + + +def test_a_login_that_cannot_read_the_storage_is_read_again(server): + """Not knowing where users and roles are stored, `plan` takes it that a replica may lag.""" + server.storage = None + server.empty_reads = 1 + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert server.reads.count("roles") == 2 + + +def test_a_missing_best_effort_grant_is_not_read_again(server): + """It is a warning and leads to no create or grant, so there is nothing to wait for.""" + drop_cluster(server) + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == "! best-effort: role shop_migration_role lacks CLUSTER ON *.*\n" + assert server.reads.count("roles") == 1 + + +def test_cluster_granted_to_every_login_is_held(server): + """As on ClickHouse Cloud: the admin's CHECK GRANT CLUSTER answers 1 although no grant of + its own holds it, so the migration role lacks nothing, and nothing is read again.""" + drop_cluster(server) + server.own_grants = [] + result = run("plan", "dev") + assert (result.exit_code, result.stdout, result.stderr) == (0, IN_SYNC, ""), result.output + assert server.reads.count("roles") == 1 + + +@pytest.mark.parametrize("held", ["ALL ON *.* WITH GRANT OPTION", "CLUSTER ON *.*"]) +def test_cluster_the_admin_holds_by_a_grant_is_not_granted_to_all(server, held): + """`CHECK GRANT` answers 1 for an admin that holds CLUSTER by a grant, too, so a role + without CLUSTER still lacks it, where the server needs the grant.""" + drop_cluster(server) + server.own_grants = grant_rows(parse_grant(held)) + result = run("plan", "dev") + assert (result.exit_code, result.stdout) == (0, IN_SYNC), result.output + assert result.stderr == "! best-effort: role shop_migration_role lacks CLUSTER ON *.*\n" + + +def test_show_reads_again_for_a_name_it_cannot_find(server): + server.behind = {"node-1": 1} + result = run("show", "dev", "analyst") + assert result.exit_code == 0, result.output + assert result.stdout.splitlines()[3:] == [ + "roles:", + " analyst:", + " grants:", + " - SELECT, SHOW TABLES ON {db}.*", + ] + assert result.stderr == WAITING.format(seconds=30) + assert server.reads.count("roles") == 3 and server.closed + + +@pytest.mark.parametrize("command", [("plan", "dev"), ("show", "dev")]) +@pytest.mark.parametrize( + ("error", "printed"), + [ + (RuntimeError("boom"), "✗ RuntimeError: boom\n"), + # click would exit 1 for these on its own. + (ui.Failure("No such thing.", "Try `ch-migrate status dev`."), None), + (click.ClickException("refused"), "Error: refused\n"), + ], +) +def test_an_error_that_stops_a_live_command_exits_2_never_1( + server, monkeypatch, command, error, printed +): + + def broken(*args): + raise error + + monkeypatch.setattr("ch_migrate.access.live.Reader.read", broken) + result = run(*command) + assert (result.exit_code, result.stdout) == (2, ""), result.output + assert result.stderr == (printed or "✗ No such thing.\nTry ch-migrate status dev.\n") + assert server.closed + + +def test_an_access_error_prints_its_message_and_exits_2(project, monkeypatch): + def refuse(settings): + raise AccessError("The server runs ClickHouse 24.8.14.39.") + + monkeypatch.setattr("ch_migrate.access.cli.connect_admin", refuse) + for command in ("plan", "show"): + result = run(command, "dev") + assert (result.exit_code, result.stdout) == (2, "") + assert result.stderr == "✗ The server runs ClickHouse 24.8.14.39.\n" + + +def test_an_unknown_environment_exits_2(project): + result = run("plan", "nowhere") + assert (result.exit_code, result.stdout) == (2, ""), result.output + assert result.stderr.startswith("✗ Unknown environment: nowhere.") diff --git a/tests/access/test_privilege_list.py b/tests/access/test_privilege_list.py new file mode 100644 index 0000000..adc23ff --- /dev/null +++ b/tests/access/test_privilege_list.py @@ -0,0 +1,50 @@ +"""The bundled privilege list (Decision 11), from ClickHouse 26.3's `system.privileges`. + +`tests/integration/test_access_privilege_list.py` pins it to the image; these check what +`validate` relies on. +""" + +import json + +from ch_migrate.access.privileges import BUNDLED_LIST, bundled_tree + +DOCUMENT = json.loads(BUNDLED_LIST.read_text()) +TREE = bundled_tree() + + +def test_the_list_comes_from_26_3(): + assert DOCUMENT["version"].startswith("26.3.") + assert len(DOCUMENT["privileges"]) > 200 + row = DOCUMENT["privileges"][0] + assert set(row) == {"privilege", "aliases", "level", "parent_group"} + + +def test_aliases_resolve_to_canonical_names(): + assert TREE.canonical("delete") == "ALTER DELETE" + assert TREE.canonical("ALTER DELETE") == "ALTER DELETE" + assert TREE.canonical("SOURCE READ") == "READ" + assert TREE.canonical("NOPE") is None + + +def test_read_and_write_are_source_level(): + assert (TREE.levels["READ"], TREE.levels["WRITE"]) == ("SOURCE", "SOURCE") + assert TREE.flags("READ", "source") == {"READ"} + assert TREE.flags("READ", "database") == frozenset() + + +def test_old_source_spellings_name_their_source(): + spellings = DOCUMENT["source_spellings"] + assert len(spellings) == 18 + assert (spellings["REMOTE"], spellings["S3"], spellings["SOURCES"]) == ("REMOTE", "S3", "") + assert TREE.new_source_spelling("REMOTE") == "REMOTE" + assert TREE.new_source_spelling("SOURCES") == "*.*" + assert TREE.new_source_spelling("CLUSTER") is None + assert TREE.source("remote") == "REMOTE" + + +def test_a_group_means_its_childrens_flags_where_the_scope_allows(): + create = TREE.flags("CREATE", "database") + assert {"CREATE DATABASE", "CREATE TABLE", "CREATE VIEW", "CREATE DICTIONARY"} <= create + assert "CREATE DATABASE" not in TREE.flags("ALTER", "table") + assert "ALTER DATABASE" not in TREE.flags("ALTER", "table") + assert TREE.flags("CLUSTER", "database") == frozenset() diff --git a/tests/access/test_project_settings.py b/tests/access/test_project_settings.py new file mode 100644 index 0000000..bc13d03 --- /dev/null +++ b/tests/access/test_project_settings.py @@ -0,0 +1,158 @@ +"""The config.yaml loader for `access`: the same keys as `get_env_config`, and no secrets.""" + +import pytest +import yaml + +from ch_migrate.access.settings import ProjectSettings, SettingsError, load_settings + + +def write(tmp_path, config): + path = tmp_path / "config.yaml" + path.write_text(yaml.safe_dump(config)) + return path + + +def test_reads_one_environment_merged_over_defaults(tmp_path): + path = write( + tmp_path, + { + "project": {"name": "shop"}, + "defaults": {"migration_user": "shop_migrator", "admin_user": "shop_admin"}, + "environments": { + "dev": {"database": "shop_dev", "mcp_user_name": "shop_mcp"}, + "production": {"database": "shop_prod", "admin_user": "prod_admin"}, + }, + }, + ) + assert load_settings("dev", path) == ProjectSettings( + environment="dev", + database="shop_dev", + project="shop", + migration_user="shop_migrator", + admin_user="shop_admin", + mcp_user_name="shop_mcp", + environments=("dev", "production"), + ) + assert load_settings("production", path).admin_user == "prod_admin" + + +def test_falls_back_as_0_8_does(tmp_path): + path = write( + tmp_path, {"environments": {"dev": {"database": "shop_dev", "user": "legacy_user"}}} + ) + settings = load_settings("dev", path) + assert (settings.project, settings.migration_user, settings.admin_user) == ( + "shop", + "legacy_user", + "default", + ) + assert settings.migration_role == "shop_migration_role" + assert settings.placeholders() == { + "db": "shop_dev", + "project": "shop", + "env": "dev", + "migration_role": "shop_migration_role", + } + + +def test_migration_role_names_a_role_another_project_shares(tmp_path): + """2.8: a second project directory names the role it shares, in defaults or per environment.""" + path = write( + tmp_path, + { + "project": {"name": "reports"}, + "defaults": { + "migration_user": "shop_migrator", + "migration_role": "shop_migration_role", + }, + "environments": { + "dev": {"database": "reports_dev"}, + "production": {"database": "reports", "migration_role": "prod_role"}, + }, + }, + ) + dev = load_settings("dev", path) + assert dev.migration_role == "shop_migration_role" + assert dev.placeholders()["migration_role"] == "shop_migration_role" + assert load_settings("production", path).migration_role == "prod_role" + + +def test_resolves_no_secret(tmp_path, monkeypatch): + ssm = {"migration_password": "/shop/dev/migration", "etl_password": "/shop/dev/etl"} + path = write( + tmp_path, + {"environments": {"dev": {"database": "shop_dev", "migration_user": "m", "ssm": ssm}}}, + ) + + def no_secrets(*args, **kwargs): + raise AssertionError("a secret was resolved") + + monkeypatch.setattr("ch_migrate.secrets.get_secret", no_secrets) + monkeypatch.setattr("ch_migrate.config.get_secret", no_secrets) + assert load_settings("dev", path).ssm == ssm # paths as written, never read + + +@pytest.mark.parametrize( + "config, error", + [ + ({"environments": {"prod": {}}}, "Unknown environment: dev. Available: prod"), + ({}, "Unknown environment: dev. Available: (none)"), + ( + {"environments": {"dev": {"migration_user": "m"}}}, + "database is required in config.yaml for environment 'dev'", + ), + ( + {"environments": {"dev": {"database": "d"}}}, + "migration_user is required in config.yaml for environment 'dev'", + ), + ( + {"environments": {"dev": {"database": "shop-dev", "migration_user": "m"}}}, + "Invalid database name: 'shop-dev'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ([1, 2], "config.yaml must be a mapping"), + ({"environments": ["dev"]}, "environments in config.yaml must be a mapping"), + ( + {"environments": {"dev": "shop_dev"}}, + "environments.dev in config.yaml must be a mapping", + ), + ( + {"defaults": "x", "environments": {"dev": {}}}, + "defaults in config.yaml must be a mapping", + ), + ( + {"environments": {"dev": {"database": "d", "migration_user": "m", "ssm": "/a"}}}, + "environments.dev.ssm in config.yaml must be a mapping", + ), + ( + { + "environments": { + "dev": {"database": "d", "migration_user": "m", "migration_role": "a-b"} + } + }, + "Invalid migration role: 'a-b'. " + "Must start with letter/underscore and contain only alphanumeric/underscore.", + ), + ], +) +def test_errors(tmp_path, config, error): + with pytest.raises(SettingsError) as raised: + load_settings("dev", write(tmp_path, config)) + assert str(raised.value) == error + + +def test_a_missing_config_is_an_error(tmp_path): + with pytest.raises(SettingsError) as raised: + load_settings("dev", tmp_path / "config.yaml") + assert str(raised.value) == f"Configuration file not found: {tmp_path / 'config.yaml'}" + + +def test_config_that_is_not_valid_yaml_is_an_error(tmp_path): + path = tmp_path / "config.yaml" + path.write_text("environments:\n dev: [\n") + with pytest.raises(SettingsError) as raised: + load_settings("dev", path) + assert str(raised.value) == ( + "config.yaml: line 3, column 1: not valid YAML: expected the node content, but found " + "''" + ) diff --git a/tests/access/test_secret_masking.py b/tests/access/test_secret_masking.py new file mode 100644 index 0000000..270acef --- /dev/null +++ b/tests/access/test_secret_masking.py @@ -0,0 +1,60 @@ +"""No secret shows in an error, raw or as a URL or form encodes it.""" + +from urllib.parse import quote, quote_plus + +from ch_migrate import secrets as secrets_module +from ch_migrate.access import server +from ch_migrate.access.server import hide_secrets + +SECRET = "Probe!pw/with+symbols &more" + + +def test_every_encoding_of_a_given_secret_is_hidden(): + text = " | ".join( + [SECRET, quote(SECRET), quote(SECRET, safe=""), quote_plus(SECRET), "ACCESS_DENIED"] + ) + assert hide_secrets(text, [SECRET]) == " | ".join(["[hidden]"] * 4 + ["ACCESS_DENIED"]) + + +def test_a_secret_read_earlier_is_hidden_without_being_passed(monkeypatch): + monkeypatch.setattr(secrets_module, "_SEEN", {SECRET}) + url = f"http://h:8123/?param_password={quote_plus(SECRET)}&database=d" + assert hide_secrets(f"Max retries exceeded with url: {url}") == ( + "Max retries exceeded with url: http://h:8123/?param_password=[hidden]&database=d" + ) + + +def test_an_empty_secret_hides_nothing(): + assert hide_secrets("abc", [""]) == "abc" + + +def test_read_secret_remembers_what_it_read(monkeypatch, tmp_path): + from ch_migrate.access.settings import load_settings + + (tmp_path / "config.yaml").write_text( + "project: {name: shop}\nenvironments:\n dev: {host: h, database: d, migration_user: m}\n" + ) + monkeypatch.setattr(secrets_module, "_SEEN", set()) + monkeypatch.setenv("CH_DEV_ETL_PASSWORD", SECRET) + assert ( + server.read_secret(load_settings("dev", tmp_path / "config.yaml"), "etl_password") == SECRET + ) + assert hide_secrets(SECRET) == "[hidden]" + + +def test_every_secret_get_secret_returns_is_hidden(monkeypatch): + """The migration and dictionary passwords `up` loads too, not only the access commands'.""" + from ch_migrate.secrets import get_secret + + monkeypatch.setattr(secrets_module, "_SEEN", set()) + monkeypatch.setenv("CH_DEV_DICT_READER_PASSWORD", SECRET) + assert get_secret("dev", "dict_reader_password", required=False) == SECRET + assert hide_secrets(f"PASSWORD '{SECRET}'") == "PASSWORD '[hidden]'" + + +def test_a_secret_as_sqlalchemy_escapes_it_is_hidden(): + """SQLAlchemy doubles `%` in a statement it quotes, and the + dictionary helper writes `:` as `\\:`, so neither form matched the raw secret.""" + secret = ":lead%pct" + text = "[SQL: PASSWORD ':lead%%pct'] | PASSWORD '\\:lead%pct'" + assert hide_secrets(text, [secret]) == "[SQL: PASSWORD '[hidden]'] | PASSWORD '[hidden]'" diff --git a/tests/access/test_validate_command.py b/tests/access/test_validate_command.py new file mode 100644 index 0000000..199bba2 --- /dev/null +++ b/tests/access/test_validate_command.py @@ -0,0 +1,184 @@ +"""`ch-migrate access validate ENV [--sql]`: offline, exit 0 when valid and 2 when not.""" + +import os +import socket + +import pytest +from click.testing import CliRunner + +from ch_migrate.cli import main + +VALID = """\ +roles: + analyst: {grants: ['SELECT ON {db}.*']} +users: + dashboards: {password: {secret: dashboards_password}, roles: [analyst]} +""" +INVALID = """\ +roles: + analyst: {grant: ['SELECT ON {db}.*']} + loader: {grants: [REMOTE ON *.*, 'SELECT ON {db}.t*']} +users: + etl: {password: hunter2} +""" + + +def run(*args): + return CliRunner().invoke(main, ["access", "validate", *args]) + + +@pytest.fixture +def offline(monkeypatch): + """No CH_* variables, and any socket use fails the test.""" + for name in [name for name in os.environ if name.startswith("CH_")]: + monkeypatch.delenv(name) + + def refuse(*args, **kwargs): + raise AssertionError("access validate opened a socket") + + monkeypatch.setattr(socket.socket, "connect", refuse) + monkeypatch.setattr(socket, "create_connection", refuse) + monkeypatch.setattr(socket, "getaddrinfo", refuse) + + +def test_a_valid_file_exits_0(project): + (project / "access.yaml").write_text(VALID) + result = run("dev") + assert result.exit_code == 0, result.output + assert result.stdout == ( + "✓ access.yaml is valid for dev: 1 role and 1 user declared; " + "the migration role shop_migration_role holds the core profile.\n" + ) + + +def test_an_invalid_file_exits_2_listing_every_error(project): + (project / "access.yaml").write_text(INVALID) + result = run("dev") + assert result.exit_code == 2, result.output + assert result.stdout == "" + assert result.stderr.splitlines() == [ + "✗ access.yaml: roles.analyst.grant: unknown key; the keys here are grants, roles or absent", + "✗ access.yaml: roles.loader.grants[0]: `REMOTE ON *.*`: this is the old spelling of a " + "source grant: write `READ, WRITE ON REMOTE`", + "✗ access.yaml: roles.loader.grants[1]: `SELECT ON {db}.t*`: prefix targets such as " + "`shop_dev.t*` aren't supported in v1", + "✗ access.yaml: users.etl.password: expected {secret: NAME}; " + "access.yaml never holds a password", + "✗ Invalid: 4 errors.", + ] + + +def test_warnings_leave_the_exit_code_at_0(project): + (project / "access.yaml").write_text("roles: {a: {grants: ['SELEKT ON {db}.*']}}\n") + result = run("dev") + assert result.exit_code == 0, result.output + assert result.stderr.startswith("! access.yaml: roles.a.grants[0]: `SELEKT ON {db}.*`: ") + + +def test_legacy_mode_without_access_yaml(project): + result = run("dev") + assert result.exit_code == 0, result.output + assert result.stdout == ( + "✓ No access.yaml: legacy mode, where the migration role shop_migration_role " + "holds the legacy profile.\n" + ) + + +@pytest.mark.parametrize("access_yaml", [VALID, None]) +def test_runs_with_no_ch_variables_and_sockets_blocked(project, offline, access_yaml): + config = (project / "config.yaml").read_text() + ssm = " ssm: {migration_password: /shop/m, dashboards_password: /shop/d}\n" + extra = " mcp_user_name: shop_mcp\n dict_reader_name: shop_dict\n" + ssm + (project / "config.yaml").write_text(config.replace(" admin_user: shop_admin\n", extra, 1)) + if access_yaml: + (project / "access.yaml").write_text(access_yaml) + for args in (("dev",), ("dev", "--sql")): + result = run(*args) + assert result.exit_code == 0, result.output + + +def test_sql_goes_to_stdout_and_the_summary_to_stderr(project): + (project / "access.yaml").write_text(VALID) + result = run("dev", "--sql") + assert result.exit_code == 0, result.output + lines = result.stdout.splitlines() + assert lines[:4] == [ + "-- Access for dev, from access.yaml.", + "-- Replace each with that secret's value as a quoted string, such as", + "-- 'value', before running it. Left in place, it fails to parse.", + "CREATE ROLE IF NOT EXISTS shop_migration_role;", + ] + assert ( + "CREATE USER IF NOT EXISTS dashboards IDENTIFIED BY ;" in lines + ) + assert lines[-1] == "GRANT SELECT ON shop_dev.* TO analyst;" + assert result.stderr.startswith("✓ access.yaml is valid for dev") + + +def test_sql_names_users_with_no_password_and_keeps_their_roles_and_grants(project): + (project / "access.yaml").write_text( + VALID + " viewer: {roles: [analyst], default_roles: [analyst]}\n ops: {}\n" + ) + result = run("dev", "--sql") + assert result.exit_code == 0, result.output + lines = result.stdout.splitlines() + assert lines[3] == ( + "-- Users with no password aren't created here and must already exist: viewer, ops." + ) + creates = [line for line in lines if line.startswith("CREATE USER")] + assert creates == [ + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY ;", + "CREATE USER IF NOT EXISTS dashboards IDENTIFIED BY ;", + ] + assert "GRANT analyst TO viewer;" in lines + assert "SET DEFAULT ROLE analyst TO viewer;" in lines + assert "users.viewer: no password, so it is never created" in result.stderr + + +def test_an_invalid_file_prints_no_sql(project): + (project / "access.yaml").write_text(INVALID) + result = run("dev", "--sql") + assert result.exit_code == 2 + assert result.stdout == "" + + +@pytest.mark.parametrize( + "setup, error", + [ + (lambda project: None, "✗ Unknown environment: staging. Available: dev, production\n"), + ( + lambda project: (project / "config.yaml").unlink(), + "✗ Configuration file not found: {project}/config.yaml\n", + ), + ( + lambda project: (project / "config.yaml").write_text("environments:\n staging: [\n"), + "✗ config.yaml: line 3, column 1: not valid YAML: " + "expected the node content, but found ''\n", + ), + ( + lambda project: (project / "config.yaml").write_text("environments: {staging: x}\n"), + "✗ environments.staging in config.yaml must be a mapping\n", + ), + ], +) +def test_config_errors_exit_2(project, setup, error): + setup(project) + result = run("staging") + assert result.exit_code == 2 + assert result.stderr == error.format(project=project) + + +@pytest.mark.parametrize("command", [["show", "dev"], ["plan", "dev"], ["apply", "dev"]]) +def test_an_empty_access_yaml_stops_a_live_command_before_it_connects( + project, monkeypatch, command +): + """`access show dev > access.yaml` empties the file first.""" + (project / "access.yaml").write_text("") + + def refuse(settings): + raise AssertionError("connected") + + monkeypatch.setattr("ch_migrate.access.cli.connect_admin", refuse) + result = CliRunner().invoke(main, ["access", *command]) + assert result.exit_code == 2, result.output + assert "access.yaml is empty" in result.stderr diff --git a/tests/fixtures/access/build_bootstrap_sql_0_8.json b/tests/fixtures/access/build_bootstrap_sql_0_8.json new file mode 100644 index 0000000..2f782bc --- /dev/null +++ b/tests/fixtures/access/build_bootstrap_sql_0_8.json @@ -0,0 +1,134 @@ +{ + "migration": [ + "CREATE DATABASE IF NOT EXISTS shop_dev", + "CREATE ROLE IF NOT EXISTS shop_migration_role", + "GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE VIEW, DROP VIEW ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE DICTIONARY, DROP DICTIONARY ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE FUNCTION, DROP FUNCTION ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ROLE ADMIN ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ACCESS MANAGEMENT ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE TEMPORARY TABLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT ON system.grants TO shop_migration_role", + "GRANT SELECT ON system.databases TO shop_migration_role", + "GRANT SELECT ON system.tables TO shop_migration_role", + "GRANT SELECT ON system.mutations TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.replicas) TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.parts) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(READ ON REMOTE) TO shop_migration_role", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY 'pw''one\\\\x'", + "GRANT shop_migration_role TO shop_migrator" + ], + "migration+dict_reader": [ + "CREATE DATABASE IF NOT EXISTS shop_dev", + "CREATE ROLE IF NOT EXISTS shop_migration_role", + "GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE VIEW, DROP VIEW ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE DICTIONARY, DROP DICTIONARY ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE FUNCTION, DROP FUNCTION ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ROLE ADMIN ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ACCESS MANAGEMENT ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE TEMPORARY TABLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT ON system.grants TO shop_migration_role", + "GRANT SELECT ON system.databases TO shop_migration_role", + "GRANT SELECT ON system.tables TO shop_migration_role", + "GRANT SELECT ON system.mutations TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.replicas) TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.parts) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(READ ON REMOTE) TO shop_migration_role", + "CREATE ROLE IF NOT EXISTS shop_dict_role", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY 'pw''one\\\\x'", + "GRANT shop_migration_role TO shop_migrator", + "CREATE USER IF NOT EXISTS shop_dict IDENTIFIED BY 'pw-dict'", + "GRANT shop_dict_role TO shop_dict" + ], + "migration+mcp": [ + "CREATE DATABASE IF NOT EXISTS shop_dev", + "CREATE ROLE IF NOT EXISTS shop_migration_role", + "GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE VIEW, DROP VIEW ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE DICTIONARY, DROP DICTIONARY ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE FUNCTION, DROP FUNCTION ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ROLE ADMIN ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ACCESS MANAGEMENT ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE TEMPORARY TABLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT ON system.grants TO shop_migration_role", + "GRANT SELECT ON system.databases TO shop_migration_role", + "GRANT SELECT ON system.tables TO shop_migration_role", + "GRANT SELECT ON system.mutations TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.replicas) TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.parts) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(READ ON REMOTE) TO shop_migration_role", + "CREATE ROLE IF NOT EXISTS shop_readonly_role", + "GRANT SELECT ON shop_dev.* TO shop_readonly_role", + "GRANT SHOW TABLES ON shop_dev.* TO shop_readonly_role", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY 'pw''one\\\\x'", + "GRANT shop_migration_role TO shop_migrator", + "CREATE USER IF NOT EXISTS shop_mcp IDENTIFIED BY 'pw-mcp'", + "GRANT shop_readonly_role TO shop_mcp" + ], + "migration+mcp+dict_reader": [ + "CREATE DATABASE IF NOT EXISTS shop_dev", + "CREATE ROLE IF NOT EXISTS shop_migration_role", + "GRANT CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE VIEW, DROP VIEW ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE DICTIONARY, DROP DICTIONARY ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE FUNCTION, DROP FUNCTION ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(CREATE USER, ALTER USER, DROP USER ON *.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROLE, ALTER ROLE, DROP ROLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ROLE ADMIN ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT ACCESS MANAGEMENT ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE ROW POLICY, ALTER ROW POLICY, DROP ROW POLICY, SHOW ROW POLICIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON shop_dev.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CREATE TEMPORARY TABLE ON *.* TO shop_migration_role WITH GRANT OPTION", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO shop_migration_role WITH GRANT OPTION", + "GRANT SELECT ON system.grants TO shop_migration_role", + "GRANT SELECT ON system.databases TO shop_migration_role", + "GRANT SELECT ON system.tables TO shop_migration_role", + "GRANT SELECT ON system.mutations TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.replicas) TO shop_migration_role", + "GRANT CURRENT GRANTS(SELECT ON system.parts) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(SYSTEM SYNC DATABASE REPLICA ON shop_dev.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(CLUSTER ON *.*) TO shop_migration_role", + "GRANT CURRENT GRANTS(READ ON REMOTE) TO shop_migration_role", + "CREATE ROLE IF NOT EXISTS shop_readonly_role", + "GRANT SELECT ON shop_dev.* TO shop_readonly_role", + "GRANT SHOW TABLES ON shop_dev.* TO shop_readonly_role", + "CREATE ROLE IF NOT EXISTS shop_dict_role", + "CREATE USER IF NOT EXISTS shop_migrator IDENTIFIED BY 'pw''one\\\\x'", + "GRANT shop_migration_role TO shop_migrator", + "CREATE USER IF NOT EXISTS shop_mcp IDENTIFIED BY 'pw-mcp'", + "GRANT shop_readonly_role TO shop_mcp", + "CREATE USER IF NOT EXISTS shop_dict IDENTIFIED BY 'pw-dict'", + "GRANT shop_dict_role TO shop_dict" + ] +} diff --git a/tests/fixtures/access/legacy_bootstrap_26_3.json b/tests/fixtures/access/legacy_bootstrap_26_3.json new file mode 100644 index 0000000..9e8ad32 --- /dev/null +++ b/tests/fixtures/access/legacy_bootstrap_26_3.json @@ -0,0 +1,140 @@ +{ + "limited_admin": { + "grants": [ + {"access_object": "", "access_type": "ALTER ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TEMPORARY TABLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "INSERT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "OPTIMIZE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "system", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW COLUMNS", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW DICTIONARIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW ROW POLICIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW TABLES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC DATABASE REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "TRUNCATE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "UNDROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null} + ], + "role_grants": [ + {"granted_role_is_default": 1, "granted_role_name": "{project}_migration_role", "role_name": null, "user_name": "{project}_migration", "with_admin_option": 0} + ], + "users": [ + {"default_roles_all": 1, "default_roles_except": [], "default_roles_list": [], "name": "{project}_migration"} + ], + "roles": [ + {"name": "{project}_migration_role"} + ] + }, + "mcp_user_and_dict_reader": { + "grants": [ + {"access_object": "", "access_type": "ALTER ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CLUSTER", "column": null, "database": null, "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE FUNCTION", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TEMPORARY TABLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP FUNCTION", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "INSERT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "OPTIMIZE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ROLE ADMIN", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "system", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_readonly_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW COLUMNS", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW DICTIONARIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW ROW POLICIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW TABLES", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_readonly_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW TABLES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC DATABASE REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "TRUNCATE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "UNDROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "REMOTE", "access_type": "READ", "column": null, "database": null, "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null} + ], + "role_grants": [ + {"granted_role_is_default": 1, "granted_role_name": "{project}_dict_role", "role_name": null, "user_name": "{project}_dict", "with_admin_option": 0}, + {"granted_role_is_default": 1, "granted_role_name": "{project}_migration_role", "role_name": null, "user_name": "{project}_migration", "with_admin_option": 0}, + {"granted_role_is_default": 1, "granted_role_name": "{project}_readonly_role", "role_name": null, "user_name": "{project}_mcp", "with_admin_option": 0} + ], + "users": [ + {"default_roles_all": 1, "default_roles_except": [], "default_roles_list": [], "name": "{project}_dict"}, + {"default_roles_all": 1, "default_roles_except": [], "default_roles_list": [], "name": "{project}_mcp"}, + {"default_roles_all": 1, "default_roles_except": [], "default_roles_list": [], "name": "{project}_migration"} + ], + "roles": [ + {"name": "{project}_dict_role"}, + {"name": "{project}_migration_role"}, + {"name": "{project}_readonly_role"} + ] + }, + "plain": { + "grants": [ + {"access_object": "", "access_type": "ALTER ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ALTER", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CLUSTER", "column": null, "database": null, "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE FUNCTION", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE TEMPORARY TABLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "CREATE VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP DICTIONARY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP FUNCTION", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP ROLE", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP ROW POLICY", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP USER", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "DROP VIEW", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "INSERT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "OPTIMIZE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "ROLE ADMIN", "column": null, "database": null, "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "system", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SELECT", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW COLUMNS", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW DICTIONARIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW ROW POLICIES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SHOW TABLES", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC DATABASE REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "SYSTEM SYNC REPLICA", "column": null, "database": "{db}", "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "TRUNCATE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "", "access_type": "UNDROP TABLE", "column": null, "database": "{db}", "grant_option": 1, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null}, + {"access_object": "REMOTE", "access_type": "READ", "column": null, "database": null, "grant_option": 0, "is_partial_revoke": 0, "role_name": "{project}_migration_role", "table": null, "user_name": null} + ], + "role_grants": [ + {"granted_role_is_default": 1, "granted_role_name": "{project}_migration_role", "role_name": null, "user_name": "{project}_migration", "with_admin_option": 0} + ], + "users": [ + {"default_roles_all": 1, "default_roles_except": [], "default_roles_list": [], "name": "{project}_migration"} + ], + "roles": [ + {"name": "{project}_migration_role"} + ] + } +} diff --git a/tests/integration/access_fixtures.py b/tests/integration/access_fixtures.py new file mode 100644 index 0000000..d25b04e --- /dev/null +++ b/tests/integration/access_fixtures.py @@ -0,0 +1,267 @@ +"""Access-test fixtures: projects whose admin and migration user are different logins. + +`conftest.py` imports the fixtures so every integration test can request them. + +Each project gets one random name, `it_<16 hex>`. Its database is `_db`, and every user +and role a fixture creates starts with the name. A test that creates its own users or roles +names them the same way, and the finalizer drops every user and role with that prefix. +`read_access` turns those generated names back into `{project}` and `{db}`. +""" + +from __future__ import annotations + +import json +import re +import secrets +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any + +import pytest +import yaml +from click.testing import CliRunner, Result + +from ch_migrate.cli import main + +# The 2026-10-29 limited admin, granted by the server's admin. T2 refines it. Its rights on +# the database and on `system.*` are as much of them as the server's admin holds: all, on a +# stock server; less on ClickHouse Cloud, whose admin holds neither `system.zookeeper` nor +# every privilege on a database. +LIMITED_ADMIN_GRANTS = ( + "GRANT CURRENT GRANTS(ALL ON {db}.*) TO {user} WITH GRANT OPTION", + "GRANT CREATE ROLE, CREATE USER, ROLE ADMIN ON *.* TO {user}", + "GRANT CURRENT GRANTS(SELECT ON system.*) TO {user} WITH GRANT OPTION", +) +# On 25.8 and later, the `limited_admin` fixture also gets READ ON REMOTE, without grant +# option, to read every replica where users and roles are replicated (design note, 2.5). +# 24.8 can't parse it. +REPLICA_READ_GRANT = "GRANT READ ON REMOTE TO {user}" + +# By server: whether ON CLUSTER needs the CLUSTER grant there (`requires_cluster_grant`). +_REQUIRES_CLUSTER_GRANT: dict[tuple[str, int], bool] = {} + +# Generated names: a database is the project name plus `_db`. +_GENERATED_NAME = re.compile(r"\bit_[0-9a-f]{16}(_db\b)?") + +_ACCESS_QUERIES = { + "grants": ( + "SELECT * FROM system.grants " + "WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}" + ), + "role_grants": ( + "SELECT * EXCEPT granted_role_id FROM system.role_grants " + "WHERE user_name IN {names:Array(String)} OR role_name IN {names:Array(String)}" + ), + "users": ( + "SELECT name, default_roles_all, default_roles_list, default_roles_except " + "FROM system.users WHERE name IN {names:Array(String)}" + ), + "roles": "SELECT name FROM system.roles WHERE name IN {names:Array(String)}", +} + + +@dataclass(frozen=True) +class AccessProject: + """A project for environment `it` whose migration user is not its admin.""" + + root: Path + client: Any = field(repr=False) # the server admin's connection, whoever the project's admin is + name: str + + @property + def database(self) -> str: + return self.name + "_db" + + @property + def migration_user(self) -> str: + return self.name + "_migration" + + @property + def admin(self) -> str: + """config.yaml's admin_user: the server's admin, unless a test made another.""" + config = yaml.safe_load((self.root / "config.yaml").read_text()) + return config["environments"]["it"]["admin_user"] + + @property + def migration_role(self) -> str: + """The role 0.8's `bootstrap` creates, named after the project.""" + return self.name + "_migration_role" + + @staticmethod + def new_password() -> str: + # ClickHouse Cloud's password policy needs an uppercase letter and a special character. + return "Chm!" + secrets.token_hex(24) + + def run(self, *args: str) -> Result: + return CliRunner().invoke(main, list(args), catch_exceptions=True) + + def configure(self, **settings: Any) -> None: + """Set keys under `environments.it` in config.yaml.""" + path = self.root / "config.yaml" + config = yaml.safe_load(path.read_text()) + config["environments"]["it"].update(settings) + path.write_text(yaml.safe_dump(config)) + + +@pytest.fixture +def access_project(clickhouse_server, request): + """A project that is not bootstrapped yet; the server's admin is its admin. + + It has no access.yaml, so it starts in legacy mode, as a 0.8 project does. A test that + wants an access.yaml writes its own. + """ + return new_access_project(clickhouse_server, request) + + +def new_access_project(server, request, root=None): + """`access_project` on `server`, in `root` or the test's tmp_path, as the working directory.""" + root = root or request.getfixturevalue("tmp_path") + monkeypatch = request.getfixturevalue("monkeypatch") + name = "it_" + secrets.token_hex(8) + result = CliRunner().invoke(main, ["init", str(root), "--name", name]) + assert result.exit_code == 0, result.output + (root / "access.yaml").unlink() # `init` writes one for a new project + client = server.connect() + request.addfinalizer(client.close) + project = AccessProject(root, client, name) + request.addfinalizer(lambda: _drop_project(project)) + _write_config(project, server) + monkeypatch.setenv("CH_IT_ADMIN_PASSWORD", server.password) + monkeypatch.setenv("CH_IT_MIGRATION_PASSWORD", AccessProject.new_password()) + monkeypatch.chdir(root) + return project + + +def initialize_cluster_project(cluster, project, monkeypatch): + """Initialize a project on node 1; the caller owns its cluster-wide cleanup.""" + result = project.run("init", str(project.root), "--name", project.name) + assert result.exit_code == 0, result.output + server = cluster.servers[1] + _write_config(project, server) + project.configure(cluster=cluster.name) + monkeypatch.setenv("CH_IT_ADMIN_PASSWORD", server.password) + monkeypatch.chdir(project.root) + + +@pytest.fixture +def bootstrapped_project(access_project): + """`access_project` after `ch-migrate bootstrap` created its database, role and user.""" + result = access_project.run("bootstrap", "it") + assert result.exit_code == 0, result.output + return access_project + + +@pytest.fixture +def limited_admin(access_project, clickhouse_server, monkeypatch): + """Make the project's admin a login with only `LIMITED_ADMIN_GRANTS`; return that login.""" + login = replace( + clickhouse_server, + user=access_project.name + "_admin", + password=AccessProject.new_password(), + ) + client = access_project.client + client.command(f"CREATE USER {login.user} IDENTIFIED BY '{login.password}'") + for grant in (*LIMITED_ADMIN_GRANTS, REPLICA_READ_GRANT): + client.command(grant.format(db=access_project.database, user=login.user)) + access_project.configure(admin_user=login.user) + monkeypatch.setenv("CH_IT_ADMIN_PASSWORD", login.password) + return login + + +def requires_cluster_grant(server): + """Whether ON CLUSTER needs the CLUSTER grant here, as a stock server's does. + + Asked as a new login with no grant at all: ClickHouse Cloud, for one, grants CLUSTER to + every login, so there `CHECK GRANT CLUSTER ON *.*` answers 1 for it. + """ + key = (server.host, server.port) + if key not in _REQUIRES_CLUSTER_GRANT: + _REQUIRES_CLUSTER_GRANT[key] = _probe_cluster_grant(server) + return _REQUIRES_CLUSTER_GRANT[key] + + +def query_log(client): + """Flush the query log, and return a FROM source that reads it on every replica. + + ClickHouse Cloud logs each query on the replica that served it. So where the `default` + cluster lists more than one host, every replica's log is flushed and read, rotated + `query_log_N` tables included. + """ + if client.command("SELECT count() FROM system.clusters WHERE cluster = 'default'") > 1: + client.command("SYSTEM FLUSH LOGS ON CLUSTER 'default'") + return "clusterAllReplicas('default', merge('system', '^query_log'))" + client.command("SYSTEM FLUSH LOGS") + return "system.query_log" + + +def read_access(client, users, roles): + """What the server holds for these users and roles: sorted rows, generated names replaced. + + `grants` and `role_grants` hold the rows granted to them, `users` their default roles, + and `roles` the roles that exist. + """ + names = [*users, *roles] + return {key: _access_rows(client, query, names) for key, query in _ACCESS_QUERIES.items()} + + +def _write_config(project, server): + environment = { + "host": server.host, + "port": server.port, + "secure": server.secure, + "database": project.database, + "admin_user": server.user, + "migration_user": project.migration_user, + } + config = {"project": {"name": project.name}, "environments": {"it": environment}} + (project.root / "config.yaml").write_text(yaml.safe_dump(config)) + + +def _drop_project(project): + """Drop the database and every user and role whose name starts with the project's.""" + client = project.client + client.command(f"DROP DATABASE IF EXISTS {project.database} SYNC") + for kind, table in (("USER", "system.users"), ("ROLE", "system.roles")): + names = client.query( + f"SELECT name FROM {table} WHERE startsWith(name, {{prefix:String}})", + parameters={"prefix": project.name}, + ).result_rows + for (name,) in names: + client.command(f"DROP {kind} IF EXISTS {name}") + + +def _access_rows(client, query, names): + result = client.query(query, parameters={"names": names}) + rows = [ + {column: _placeholders(value) for column, value in zip(result.column_names, row)} + for row in result.result_rows + ] + return sorted(rows, key=lambda row: json.dumps(row, sort_keys=True)) + + +def _placeholders(value): + if isinstance(value, str): + return _GENERATED_NAME.sub(lambda m: "{db}" if m.group(1) else "{project}", value) + if isinstance(value, (list, tuple)): + return [_placeholders(item) for item in value] + return value + + +def _probe_cluster_grant(server): + admin = server.connect() + login = replace( + server, user="it_" + secrets.token_hex(8) + "_probe", password=AccessProject.new_password() + ) + try: + admin.command( + f"CREATE USER {login.user} IDENTIFIED BY {{password:String}}", + parameters={"password": login.password}, + ) + client = login.connect() + try: + return client.command("CHECK GRANT CLUSTER ON *.*") == 0 + finally: + client.close() + finally: + admin.command(f"DROP USER IF EXISTS {login.user}") + admin.close() diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index a30d5a7..e83e7d2 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -18,10 +18,46 @@ import clickhouse_connect import pytest import yaml +from access_fixtures import access_project, bootstrapped_project, limited_admin # noqa: F401 from click.testing import CliRunner from ch_migrate.cli import main +_CLUSTER_FIXTURES = {"clickhouse_cluster", "clickhouse_cluster_keeper"} +# An image older than the 25.8 the live access commands need (design note, Decision 11). +OLD_IMAGE = "24.8" +# "local" keeps the image's default `user_directories`. "replicated" replaces it so that users +# and roles created by SQL go to Keeper, where every node reads them. +_ACCESS_STORAGE_XML = { + "local": "", + "replicated": """ + users.xml + /clickhouse/access/ + """, +} + + +# CLUSTER for every login, as on ClickHouse Cloud: ON CLUSTER then needs no grant. +_IMPLICIT_CLUSTER_XML = """ + + false + + +""" +# A read-only directory before the one a create goes to, as Cloud lists `jwt` first. +_LDAP_FIRST_XML = """ + + 127.0.0.11389no + uid={user_name},dc=example,dc=org + + + users.xml + chm_it_ldap + /var/lib/clickhouse/access/ + + +""" + @dataclass(frozen=True) class ClickHouseServer: @@ -55,6 +91,7 @@ class ClickHouseCluster: clients: dict[int, Any] = field(default_factory=dict, repr=False) stopped: set[int] = field(default_factory=set) name: str = "it_cluster" + access_storage: str = "local" # where users and roles live: "local" or "replicated" def stop_node(self, node: int) -> None: _docker("stop", "--time", "0", self.containers[node]) @@ -82,8 +119,8 @@ class MigrationProject: database: str cloud: bool = False - # SharedMergeTree lists metadata-only ALTERs in system.mutations with no block numbers - # (DRY-1446). They rewrite no parts, so tests count only part-rewriting mutations. + # SharedMergeTree lists metadata-only ALTERs in system.mutations with no block numbers. + # They rewrite no parts, so tests count only part-rewriting mutations. # Needs {db:String} and {table:String} parameters. REWRITES_PARTS = ( "NOT (empty(block_numbers.number) AND startsWith((SELECT engine FROM system.tables " @@ -195,6 +232,47 @@ def clickhouse_server(request): return server +@pytest.fixture(scope="session") +def old_clickhouse_server(request): + """ClickHouse 24.8, older than the live access commands' 25.8 floor, in its own container.""" + if os.environ.get("CH_MIGRATE_IT_URL"): + pytest.skip("The 24.8 checks only use their own Docker container, never an external server") + if ( + not shutil.which("docker") + or subprocess.run(["docker", "info"], capture_output=True).returncode + ): + pytest.skip("Docker is unavailable for the ClickHouse 24.8 container") + name = "chm-it-" + secrets.token_hex(8) + password = secrets.token_hex(24) + request.addfinalizer(lambda: _remove_container(name)) + _start_container(name, password, _Image(OLD_IMAGE)) + server = ClickHouseServer("127.0.0.1", _container_port(name), "default", password) + _wait_for_ping(server) + return server + + +@pytest.fixture(scope="session") +def implicit_cluster_server(request, tmp_path_factory): + """A server that grants CLUSTER to every login, so ON CLUSTER needs no grant. + + ClickHouse Cloud does: there it is the Cloud service itself. Elsewhere it is a container + of its own with `on_cluster_queries_require_cluster_grant` off. + """ + return _cloud_or_configured(request, tmp_path_factory, _IMPLICIT_CLUSTER_XML) + + +@pytest.fixture(scope="session") +def read_only_directory_server(request, tmp_path_factory): + """A server whose first user directory after users.xml can't take a create. + + ClickHouse Cloud lists `jwt` before `replicated`: there it is the Cloud service itself. + Elsewhere it is a container of its own that lists `ldap` before `local_directory`. Its + LDAP server doesn't exist, so a user created by SQL can't log in there: use users.xml's + `default`, the admin. + """ + return _cloud_or_configured(request, tmp_path_factory, _LDAP_FIRST_XML) + + @pytest.fixture(scope="session") def server_is_cloud(clickhouse_server): """ClickHouse Cloud services create Shared databases; self-hosted servers cannot.""" @@ -216,39 +294,14 @@ def cloud_scope(request): @pytest.fixture(scope="session") def clickhouse_cluster(request, tmp_path_factory): - if os.environ.get("CH_MIGRATE_IT_URL"): - pytest.skip("Cluster tests only use their own Docker nodes, never an external server") - if ( - not shutil.which("docker") - or subprocess.run(["docker", "info"], capture_output=True).returncode - ): - pytest.skip("Docker is unavailable for the replicated integration fixture") - prefix = "chm-it-" + secrets.token_hex(8) - network = _docker("network", "create", prefix) - request.addfinalizer(lambda: _remove_network(network)) - hostnames = {node: f"{prefix}-node{node}" for node in (1, 2)} - root = tmp_path_factory.mktemp("cluster-config") - password = secrets.token_hex(24) - containers = {} - # Keep acquisition and LIFO finalizers together: only successfully created IDs are removed. - for node, name in hostnames.items(): - config_path = root / f"node{node}.xml" - config_path.write_text(_cluster_xml(hostnames, node)) - container = _create_cluster_container(name, password, (prefix, config_path)) - containers[node] = container - request.addfinalizer(lambda owned=container: _remove_container(owned)) - _docker("start", container) - servers = { - node: ClickHouseServer("127.0.0.1", _container_port(container), "default", password) - for node, container in containers.items() - } - cluster = ClickHouseCluster(prefix, containers, hostnames, servers) - request.addfinalizer(cluster.close) - for node, server in servers.items(): - _wait_for_ping(server) - cluster.clients[node] = server.connect() - _wait_for_cluster(cluster) - return cluster + """Users and roles live on each node's local disk, as in the server's default config.""" + return _start_cluster(request, tmp_path_factory, "local") + + +@pytest.fixture(scope="session") +def clickhouse_cluster_keeper(request, tmp_path_factory): + """The same cluster, with users and roles stored in Keeper and shared by both nodes.""" + return _start_cluster(request, tmp_path_factory, "replicated") @pytest.fixture @@ -256,6 +309,7 @@ def cluster_project(clickhouse_cluster, tmp_path, monkeypatch, request): cluster = clickhouse_cluster result = CliRunner().invoke(main, ["init", str(tmp_path), "--name", "integration"]) assert result.exit_code == 0, result.output + (tmp_path / "access.yaml").unlink() # legacy mode, as these tests were written for _configure_project(tmp_path, cluster.servers[1]) database = "it_" + secrets.token_hex(8) config = yaml.safe_load((tmp_path / "config.yaml").read_text()) @@ -273,7 +327,7 @@ def cluster_project(clickhouse_cluster, tmp_path, monkeypatch, request): @pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items): for item in items: - if "clickhouse_cluster" in item.fixturenames: + if _CLUSTER_FIXTURES & set(item.fixturenames): item.add_marker(pytest.mark.integration) item.add_marker(pytest.mark.cluster) @@ -283,6 +337,7 @@ def pytest_collection_modifyitems(items): def project(clickhouse_server, tmp_path, monkeypatch, request): result = CliRunner().invoke(main, ["init", str(tmp_path), "--name", "integration"]) assert result.exit_code == 0, result.output + (tmp_path / "access.yaml").unlink() # legacy mode, as these tests were written for _configure_project(tmp_path, clickhouse_server) monkeypatch.setenv("CH_IT_MIGRATION_PASSWORD", clickhouse_server.password) monkeypatch.chdir(tmp_path) @@ -299,6 +354,23 @@ def project(clickhouse_server, tmp_path, monkeypatch, request): ) +@dataclass(frozen=True) +class _Image: + """The image a container runs, and a file for its config.d, if any.""" + + tag: str | None = None # None: CH_MIGRATE_IT_IMAGE, else 26.3 + config: Path | None = None + + +@dataclass(frozen=True) +class _ClusterSpec: + prefix: str + hostnames: dict[int, str] + root: Path + password: str = field(repr=False) + access_storage: str + + def _server_from_url(url): parsed = urlsplit(url) if parsed.scheme not in ("http", "https") or not parsed.hostname: @@ -312,8 +384,28 @@ def _server_from_url(url): ) -def _start_container(name, password): - image = os.environ.get("CH_MIGRATE_IT_IMAGE", "26.3") +def _cloud_or_configured(request, tmp_path_factory, xml): + """The Cloud service, or else a container of its own with `xml` in its config.d.""" + if os.environ.get("CH_MIGRATE_IT_URL"): + if not request.getfixturevalue("server_is_cloud"): + pytest.skip("This server setup needs ClickHouse Cloud or a Docker container") + return request.getfixturevalue("clickhouse_server") + if not shutil.which("docker"): + pytest.skip("Docker is unavailable and CH_MIGRATE_IT_URL is not set") + config = tmp_path_factory.mktemp("server-config") / "chm_it.xml" + config.write_text(xml) + name = "chm-it-" + secrets.token_hex(8) + password = secrets.token_hex(24) + request.addfinalizer(lambda: _remove_container(name)) + _start_container(name, password, _Image(config=config)) + server = ClickHouseServer("127.0.0.1", _container_port(name), "default", password) + _wait_for_ping(server) + return server + + +def _start_container(name, password, image=_Image()): + tag = image.tag or os.environ.get("CH_MIGRATE_IT_IMAGE", "26.3") + mount = ["--volume", f"{image.config}:/etc/clickhouse-server/config.d/chm_it.xml:ro"] result = subprocess.run( [ "docker", @@ -327,7 +419,8 @@ def _start_container(name, password): "CLICKHOUSE_PASSWORD", "--env", "CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1", - f"clickhouse/clickhouse-server:{image}", + *(mount if image.config else []), + f"clickhouse/clickhouse-server:{tag}", ], env={**os.environ, "CLICKHOUSE_PASSWORD": password}, capture_output=True, @@ -398,6 +491,53 @@ def _container_port(container): return int(_docker("port", container, "8123/tcp").rsplit(":", 1)[1]) +def _start_cluster(request, tmp_path_factory, access_storage): + """Two Docker nodes on their own network; `access_storage` is "local" or "replicated".""" + if os.environ.get("CH_MIGRATE_IT_URL"): + pytest.skip("Cluster tests only use their own Docker nodes, never an external server") + if ( + not shutil.which("docker") + or subprocess.run(["docker", "info"], capture_output=True).returncode + ): + pytest.skip("Docker is unavailable for the replicated integration fixture") + prefix = "chm-it-" + secrets.token_hex(8) + network = _docker("network", "create", prefix) + request.addfinalizer(lambda: _remove_network(network)) + hostnames = {node: f"{prefix}-node{node}" for node in (1, 2)} + root = tmp_path_factory.mktemp("cluster-config") + spec = _ClusterSpec(prefix, hostnames, root, secrets.token_hex(24), access_storage) + containers = _start_cluster_nodes(request, spec) + servers = { + node: ClickHouseServer("127.0.0.1", _container_port(container), "default", spec.password) + for node, container in containers.items() + } + cluster = ClickHouseCluster(prefix, containers, hostnames, servers) + cluster.access_storage = access_storage + request.addfinalizer(cluster.close) + for node, server in servers.items(): + _wait_for_ping(server) + cluster.clients[node] = server.connect() + _wait_for_cluster(cluster) + return cluster + + +def _start_cluster_nodes(request, spec): + containers = {} + # Keep acquisition and LIFO finalizers together: only successfully created IDs are removed. + for node, name in spec.hostnames.items(): + config_path = spec.root / f"node{node}.xml" + config_path.write_text(_cluster_xml(spec, node)) + container = _create_cluster_container(name, spec.password, (spec.prefix, config_path)) + containers[node] = container + request.addfinalizer(lambda owned=container: _remove_container(owned)) + _docker("start", container) + if node == 1 and spec.access_storage == "replicated": + # Node 2 reads its users from node 1's Keeper at startup and exits without it. + port = _container_port(container) + _wait_for_ping(ClickHouseServer("127.0.0.1", port, "default", spec.password)) + return containers + + def _create_cluster_container(name, password, resources): network, config_path = resources image = os.environ.get("CH_MIGRATE_IT_IMAGE", "26.3") @@ -459,7 +599,8 @@ def _wait_for_cluster(cluster): pytest.fail("Owned replicas or Keeper did not become ready within 60 seconds", pytrace=False) -def _cluster_xml(hostnames, node): +def _cluster_xml(spec, node): + hostnames = spec.hostnames replicas = "".join( f"{name}9000default" '' @@ -480,6 +621,7 @@ def _cluster_xml(hostnames, node): 01r{node} /clickhouse/task_queue/ddl + {_ACCESS_STORAGE_XML[spec.access_storage]} """ diff --git a/tests/integration/dialect_spike_probe.py b/tests/integration/dialect_spike_probe.py index fff15ce..4619bb1 100644 --- a/tests/integration/dialect_spike_probe.py +++ b/tests/integration/dialect_spike_probe.py @@ -1,4 +1,4 @@ -"""Explicit DRY-1391 reproduction; not part of automatic test collection. +"""Explicit reproduction of the dialect spike; not part of automatic test collection. Run this file with CH_MIGRATE_SPIKE_PYTHON pointing to the clean 3.10 environment containing clickhouse-connect[alembic]==1.9.0 and clickhouse-sqlalchemy==0.3.2. diff --git a/tests/integration/grant_rights.py b/tests/integration/grant_rights.py new file mode 100644 index 0000000..43542f6 --- /dev/null +++ b/tests/integration/grant_rights.py @@ -0,0 +1,232 @@ +"""Leaf expansion: the read-only grant comparison that the access spike tests (U1). + +ClickHouse folds what it stores in `system.grants`. A group may be stored as itself or as +its children, a narrower grant is absorbed by a broader one, and an alias is stored under +its canonical name. So the spike compares *rights* instead: one per privilege flag, scope +and grant option, expanded from `system.privileges` on the server being compared. + +A privilege with a `level` carries a flag of its own; one without is a group. A privilege +means its own flag plus its descendants' flags, keeping only the flags whose level the +target's scope allows. `CREATE ON db.*` therefore means `CREATE DATABASE`, `CREATE TABLE`, +`CREATE VIEW` and `CREATE DICTIONARY`, which is also what the server stores for it. + +This is test code. The spike record, `docs/design/2026-11-11-access-spike.md`, describes +the algorithm for the product code that replaces it. +""" + +from __future__ import annotations + +import re +from collections import defaultdict +from dataclasses import dataclass + +# Levels a flag may have and still be granted on a database target, or on a table target. +_DATABASE_LEVELS = frozenset({"DATABASE", "TABLE", "DICTIONARY", "VIEW", "COLUMN"}) +_TABLE_LEVELS = frozenset({"TABLE", "DICTIONARY", "VIEW", "COLUMN"}) + +# `[GRANT] [CURRENT GRANTS(] ON [)] [TO ] [WITH GRANT OPTION]` +_GRANT = re.compile( + r"^(?:GRANT\s+)?(?PCURRENT\s+GRANTS\s*\()?\s*(?P.+?)\s+ON\s+" + r"(?P[\w*]+(?:\.[\w*]+)?)\s*\)?(?:\s+TO\s+\w+)?(?P
` for the project's users and roles, in a stable order.""" + columns = ("name",) if table in ("users", "roles") else ("user_name", "role_name") + where = " OR ".join(f"startsWith({column}, {{p:String}})" for column in columns) + rows = project.client.query( + f"SELECT * FROM system.{table} WHERE {where}", parameters={"p": project.name} + ).result_rows + return sorted(repr(row) for row in rows) + + +def cluster_project(cluster, tmp_path, monkeypatch): + """A project on node 1 that declares one role and waits 0.3 s for a replica.""" + name = "it_" + secrets.token_hex(8) + project = AccessProject(tmp_path, cluster.clients[1], name) + initialize_cluster_project(cluster, project, monkeypatch) + project.configure(access_read_timeout=0.3) + write_access(project, "roles: {'{project}_a': {}}\n") + return project diff --git a/tests/integration/test_access_privilege_list.py b/tests/integration/test_access_privilege_list.py new file mode 100644 index 0000000..16e5239 --- /dev/null +++ b/tests/integration/test_access_privilege_list.py @@ -0,0 +1,30 @@ +"""Pin the bundled privilege list to the ClickHouse 26.3 image it came from (Decision 11). + +`access validate` checks names offline against `ch_migrate/access/privileges_26_3.json`. +This records the list again from the test server, the way `scripts/bundle_privileges.py` +does, and fails when the two differ. When the floating `26.3` tag changes the list, run the +script and review the diff. Other server versions skip: the list is 26.3's by design. +""" + +import json +import secrets + +import pytest + +from ch_migrate.access.bundle import record_privileges +from ch_migrate.access.privileges import BUNDLED_LIST + +pytestmark = pytest.mark.integration + + +def test_the_bundled_list_matches_the_26_3_image(clickhouse_server): + client = clickhouse_server.connect() + try: + if not client.server_version.startswith("26.3."): + pytest.skip(f"the bundled list is 26.3's; this server is {client.server_version}") + recorded = record_privileges(client, "it_" + secrets.token_hex(8) + "_scratch") + finally: + client.close() + bundled = json.loads(BUNDLED_LIST.read_text()) + assert recorded["privileges"] == bundled["privileges"] + assert recorded["source_spellings"] == bundled["source_spellings"] diff --git a/tests/integration/test_access_spike.py b/tests/integration/test_access_spike.py new file mode 100644 index 0000000..49bdbbd --- /dev/null +++ b/tests/integration/test_access_spike.py @@ -0,0 +1,1190 @@ +"""The access spike: how ClickHouse stores and checks grants (U1–U10 in the design note). + +Each test pins one answer recorded in `docs/design/2026-11-11-access-spike.md`. A test about a +feature that some images lack asserts what those images do instead; it never skips. +`CH_MIGRATE_IT_IMAGE` picks the image. The u5 and u8 tests hold expectations for 24.8, 25.8 +and 26.3, and fail on any other image until someone records what that image does. + +The core profile below is the design note's draft (2.4), written out by hand: there is no +product code for it yet. Users and roles a test creates start with the project's `it_` +name, so the access fixtures' finalizer drops them. Cluster tests drop theirs on every node. +""" + +import hashlib +import secrets +import statistics +import threading +import time +from dataclasses import dataclass, replace + +import pytest +from access_fixtures import AccessProject, initialize_cluster_project, query_log +from clickhouse_connect.driver.exceptions import DatabaseError, OperationalError +from grant_rights import ( + PrivilegeTree, + Right, + Scope, + admin_rights, + compare, + desired_rights, + gives_in_full, + held_in_full, + live_rights, + parse_grant, +) + +from ch_migrate.bootstrap import build_bootstrap_sql + +pytestmark = pytest.mark.integration + +# The design note's draft core profile (2.4), with `{db}` for the project database. +CORE_REQUIRED = ( + "CREATE TABLE, DROP TABLE, UNDROP TABLE, ALTER ON {db}.*", + "CREATE VIEW, DROP VIEW, CREATE DICTIONARY, DROP DICTIONARY ON {db}.*", + "SELECT, INSERT, DELETE, TRUNCATE, OPTIMIZE ON {db}.*", + "SHOW TABLES, SHOW COLUMNS, SHOW DICTIONARIES ON {db}.*", + "SELECT ON system.databases", + "SELECT ON system.tables", + "SELECT ON system.mutations", + "SELECT ON system.dictionaries", +) +CORE_BEST_EFFORT = ( + "SELECT ON system.parts", + "SELECT ON system.replicas", + "SYSTEM SYNC REPLICA, SYSTEM SYNC DATABASE REPLICA ON {db}.*", + "CLUSTER ON *.*", + "READ ON REMOTE", + "CREATE TEMPORARY TABLE ON *.*", +) +# U6: the smallest admin that runs a core-only bootstrap. Every entry is needed. The admin +# needs no SHOW grants: ClickHouse implies SHOW TABLES, SHOW COLUMNS and SHOW DICTIONARIES, +# with grant option, from its other rights on the database. +SMALLEST_ADMIN = ( + "CREATE DATABASE ON {db}.*", + "CREATE ROLE ON *.*", + "CREATE USER ON *.*", + "ROLE ADMIN ON *.*", + *(grant + " WITH GRANT OPTION" for grant in CORE_REQUIRED if not grant.startswith("SHOW")), +) +# U1: grants ClickHouse stores in another shape, and the rows it writes for them. +# Each row is (access_type, database, table, access_object). +STORED_SHAPES = { + "a narrower privilege folds into its group": ( + ("ALTER, DELETE ON {db}.*",), + {("ALTER", "{db}", None, "")}, + ), + "an alias is stored under its canonical name": ( + ("DELETE ON {db}.*",), + {("ALTER DELETE", "{db}", None, "")}, + ), + "a parent is stored as the children its scope allows": ( + ("CREATE ON {db}.*",), + {(name, "{db}", None, "") for name in ("CREATE DATABASE", "CREATE TABLE")} + | {(name, "{db}", None, "") for name in ("CREATE VIEW", "CREATE DICTIONARY")}, + ), + "a database-scoped ACCESS MANAGEMENT keeps only its row-policy children": ( + ("ACCESS MANAGEMENT ON {db}.*",), + { + (name, "{db}", None, "") + for name in ( + "CREATE ROW POLICY", + "ALTER ROW POLICY", + "DROP ROW POLICY", + "SHOW ROW POLICIES", + ) + }, + ), + "a table-scoped ALTER drops ALTER DATABASE": ( + ("ALTER ON {db}.events",), + {("ALTER TABLE", "{db}", "events", ""), ("ALTER VIEW", "{db}", "events", "")}, + ), + # On a database the admin holds all of: ClickHouse Cloud's admin can't give SELECT on all + # of `system.*`, which takes in `system.zookeeper`. + "a narrower grant is absorbed by a broader one": ( + ("SELECT ON {db}.events", "SELECT ON {db}.*"), + {("SELECT", "{db}", None, "")}, + ), + "a grant without option is absorbed by the same grant with it": ( + ("SELECT ON {db}.* WITH GRANT OPTION", "SELECT ON {db}.events"), + {("SELECT", "{db}", None, "")}, + ), + "READ ON REMOTE is a source grant": ( + ("READ ON REMOTE",), + {("READ", None, None, "REMOTE")}, + ), +} +# Expectations per image (major.minor). An image with no entry fails the u5 and u8 tests. +IMAGES = { + "24.8": {"check_grant": False, "source_grants": False, "create_user_level": "GLOBAL"}, + "25.8": {"check_grant": True, "source_grants": True, "create_user_level": "USER_NAME"}, + "26.3": {"check_grant": True, "source_grants": True, "create_user_level": "USER_NAME"}, +} +# How SHOW GRANTS prints `READ ON REMOTE` on each image, as it starts, with +# `access_control_improvements.enable_read_write_grants` off. ClickHouse Cloud turns it on, +# and prints the grant as written. +SHOWN_READ_ON_REMOTE = {"25.8": "GRANT REMOTE ON *.*", "26.3": "GRANT REMOTE ON *.*"} +# U7: a migration that uses each core database right ch-migrate's own paths don't. The +# dictionary reads its source as the migration user, as `create_dictionary` names a user: +# ClickHouse Cloud refuses a ClickHouse source with no USER from any login but `default`. +U7_UPGRADE = """ +CREATE TABLE IF NOT EXISTS {db}.events (id UInt64, status String) ENGINE = MergeTree ORDER BY id; +-- ch-migrate: allow-non-idempotent The spike's fixture table starts empty +INSERT INTO {db}.events VALUES (1, 'new'), (2, 'old'); +ALTER TABLE {db}.events ADD COLUMN IF NOT EXISTS note String DEFAULT ''; +-- ch-migrate: allow-non-idempotent A second run writes the same value +ALTER TABLE {db}.events UPDATE status = 'seen' WHERE id = 1; +-- ch-migrate: allow-non-idempotent Deleting an absent row again is harmless +DELETE FROM {db}.events WHERE id = 2; +CREATE VIEW IF NOT EXISTS {db}.recent AS SELECT id, status FROM {db}.events; +CREATE DICTIONARY IF NOT EXISTS {db}.statuses (id UInt64, status String) PRIMARY KEY id +SOURCE(CLICKHOUSE(DB '{db}' TABLE 'events' USER '' PASSWORD '')) +LIFETIME(0) LAYOUT(FLAT()); +OPTIMIZE TABLE {db}.events FINAL; +""" +U7_DOWNGRADE = """ +DROP DICTIONARY IF EXISTS {db}.statuses; +DROP VIEW IF EXISTS {db}.recent; +TRUNCATE TABLE IF EXISTS {db}.events; +DROP TABLE IF EXISTS {db}.events; +""" +U7_CLUSTER_UPGRADE = """ +CREATE TABLE IF NOT EXISTS {db}.events ON CLUSTER it_cluster (id UInt64, status String) +ENGINE = ReplicatedMergeTree('/clickhouse/tables/{db}/events', '{replica}') ORDER BY id; +-- ch-migrate: allow-non-idempotent A second run writes the same value +ALTER TABLE {db}.events ON CLUSTER it_cluster UPDATE status = 'seen' WHERE id = 1; +""" +U7_CLUSTER_DOWNGRADE = "DROP TABLE IF EXISTS {db}.events ON CLUSTER it_cluster SYNC;" +U7_HELD_UPGRADE = """ +-- ch-migrate: allow-non-idempotent A second run writes the same value +ALTER TABLE {db}.events ON CLUSTER it_cluster UPDATE status = 'seen' WHERE id = 1; +""" + + +@dataclass(frozen=True) +class Identity: + """A role, and a user holding it, made for one test.""" + + database: str + role: str + user: str + password: str + + +# U1. Read-only comparison: leaf expansion from system.privileges. + + +def test_u1_every_privilege_on_every_target(access_project): + """Grant each privilege on `*.*`, `db.*` and `db.t`, and compare by leaf expansion. + + Every accepted grant matches, except the old source privileges (`REMOTE ON *.*` and + the like), which servers with `READ ON ` store as READ and WRITE on that source. + The server rejects a grant only when the expansion is empty, or when the admin's own + rights don't cover it with grant option. More grants are accepted than there are + privileges: a stock server's admin can give them all, and Cloud's most. + """ + client, tree = access_project.client, PrivilegeTree.read(access_project.client) + _create_events_table(access_project) + held_by_admin = admin_rights(client, tree) + role = access_project.name + "_sweep" + accepted = 0 + for privilege in sorted(tree.levels): + for target in ("*.*", "{db}.*", "{db}.events"): + grant = parse_grant(f"{privilege} ON {target.format(db=access_project.database)}") + desired = desired_rights(tree, [grant]) + error = _grant_to_fresh_role(client, grant, role) + if error: + _assert_rejection_explained(error, desired, held_by_admin) + continue + accepted += 1 + difference = compare(desired, live_rights(tree, _grant_rows(client, "role", role))) + if not difference.in_sync: + _assert_source_rewrite(grant, difference) + assert accepted > len(tree.levels) + + +def test_u1_profiles_match_one_grant_at_a_time_and_together(access_project): + """Both profiles: each statement alone, then the whole profile on one role.""" + client = access_project.client + role = access_project.name + "_migration_role" + for profile in (_legacy_grants(access_project), _core_grants(access_project)): + profile = _given_in_full(client, profile) + for statement in profile: + _reset_role(client, role) + client.command(_as_written(statement, role)) + _assert_in_sync(client, role, [statement]) + _reset_role(client, role) + for statement in profile: + client.command(_as_written(statement, role)) + _assert_in_sync(client, role, profile) + + +@pytest.mark.parametrize("case", sorted(STORED_SHAPES)) +def test_u1_folded_grants_still_match(access_project, case): + """ClickHouse stores these in another shape; leaf expansion still finds them equal.""" + statements, stored = STORED_SHAPES[case] + client = access_project.client + role = access_project.name + "_folded" + db = access_project.database + statements = [statement.format(db=db) for statement in statements] + _reset_role(client, role) + for statement in statements: + client.command(_grant_sql(parse_grant(statement), role)) + rows = _grant_rows(client, "role", role) + expected = {(t, d if d != "{db}" else db, table, o) for t, d, table, o in stored} + assert {_row_key(row) for row in rows} == expected + _assert_in_sync(client, role, statements) + + +def test_u1_show_grants_text_differs_from_what_is_stored(access_project): + """Why a text diff of SHOW GRANTS fails: READ ON REMOTE reads back as REMOTE ON *.*.""" + client = access_project.client + shown = SHOWN_READ_ON_REMOTE.get(_image_version(client)) + if shown is None: + pytest.skip( + "No recorded SHOW GRANTS text for this image; record it in SHOWN_READ_ON_REMOTE" + ) + role = access_project.name + "_text" + _reset_role(client, role) + client.command(f"GRANT READ ON REMOTE TO {role}") + assert client.command(f"SHOW GRANTS FOR {role}") == f"{shown} TO {role}" + assert [_row_key(row) for row in _grant_rows(client, "role", role)] == [ + ("READ", None, None, "REMOTE") + ] + + +def test_u1_narrowing_revokes_only_the_difference(access_project): + """From ALTER to ALTER UPDATE: revoke the extra leaves; never "grant new, revoke old".""" + client = access_project.client + db, role = access_project.database, access_project.name + "_narrow" + _reset_role(client, role) + client.command(f"GRANT ALTER ON {db}.* TO {role}") + desired = [f"ALTER UPDATE ON {db}.*"] + difference = _difference(client, role, desired) + assert not difference.missing and len(difference.extra) > 10 + flags = ", ".join(sorted(right.privilege for right in difference.extra)) + client.command(f"REVOKE {flags} ON {db}.* FROM {role}") + _assert_in_sync(client, role, desired) + assert [_row_key(row) for row in _grant_rows(client, "role", role)] == [ + ("ALTER UPDATE", db, None, "") + ] + _reset_role(client, role) + client.command(f"GRANT ALTER ON {db}.* TO {role}") + client.command(f"GRANT ALTER UPDATE ON {db}.* TO {role}") + client.command(f"REVOKE ALTER ON {db}.* FROM {role}") + assert _grant_rows(client, "role", role) == [] + + +def test_u1_grant_option_is_part_of_each_right(access_project): + """A grant option the YAML doesn't ask for is extra; one it asks for and lacks is missing.""" + client = access_project.client + db, role = access_project.database, access_project.name + "_option" + _reset_role(client, role) + client.command(f"GRANT SELECT ON {db}.* TO {role} WITH GRANT OPTION") + plain = _difference(client, role, [f"SELECT ON {db}.*"]) + assert not plain.missing + assert plain.extra == {Right("SELECT", Scope(db), True)} + client.command(f"REVOKE GRANT OPTION FOR SELECT ON {db}.* FROM {role}") + _assert_in_sync(client, role, [f"SELECT ON {db}.*"]) + with_option = _difference(client, role, [f"SELECT ON {db}.* WITH GRANT OPTION"]) + assert with_option.missing == {Right("SELECT", Scope(db), True)} + + +def test_u1_narrowing_a_scope_cannot_grant_first(access_project): + """From `db.*` to `db.events`: the narrower grant is absorbed, so the revoke takes it too. + + Revoking first converges, with a moment of no access in between. One + `GRANT ... WITH REPLACE OPTION` converges in a single statement and keeps memberships. + """ + client = access_project.client + db, role = access_project.database, access_project.name + "_scope" + desired = [f"SELECT ON {db}.events"] + _reset_role(client, role) + client.command(f"GRANT SELECT ON {db}.* TO {role}") + difference = _difference(client, role, desired) + assert not difference.missing + assert difference.extra == {Right("SELECT", Scope(db), False)} + client.command(f"GRANT SELECT ON {db}.events TO {role}") + client.command(f"REVOKE SELECT ON {db}.* FROM {role}") + assert _grant_rows(client, "role", role) == [] + client.command(f"GRANT SELECT ON {db}.* TO {role}") + client.command(f"REVOKE SELECT ON {db}.* FROM {role}") + client.command(f"GRANT SELECT ON {db}.events TO {role}") + _assert_in_sync(client, role, desired) + _assert_replace_converges(access_project, role, desired) + + +def test_u1_replace_needs_every_current_right_with_grant_option( + access_project, clickhouse_server, request +): + """An admin that can't pass on one right the role holds can't replace; nothing changes.""" + client, db = access_project.client, access_project.database + role = access_project.name + "_replaced" + _reset_role(client, role) + client.command(f"GRANT SELECT ON {db}.* TO {role}") + client.command(f"GRANT SELECT ON {db}_elsewhere.* TO {role}") + grants = (f"CURRENT GRANTS(ALL ON {db}.*) WITH GRANT OPTION",) # as much as the admin has + admin = _admin_login(access_project, clickhouse_server, grants).connect() + request.addfinalizer(admin.close) + before = _flagged_rows(client, role) + with pytest.raises(DatabaseError, match="ACCESS_DENIED"): + admin.command(f"GRANT SELECT ON {db}.events TO {role} WITH REPLACE OPTION") + assert _flagged_rows(client, role) == before + + +def test_u1_column_grant_is_narrower_than_a_table_grant(access_project): + """A live column grant doesn't satisfy a table grant; the table grant then absorbs it.""" + client = access_project.client + db, role = access_project.database, access_project.name + "_column" + _create_events_table(access_project) + _reset_role(client, role) + client.command(f"GRANT SELECT(id) ON {db}.events TO {role}") + difference = _difference(client, role, [f"SELECT ON {db}.events"]) + assert difference.missing == {Right("SELECT", Scope(db, "events"), False)} + assert not difference.extra + client.command(f"GRANT SELECT ON {db}.events TO {role}") + assert [_row_key(row) for row in _grant_rows(client, "role", role)] == [ + ("SELECT", db, "events", "") + ] + + +# U2. Partial revokes. + + +def test_u2_partial_revoke_is_a_row_and_granting_again_clears_it(access_project): + client = access_project.client + db, role = access_project.database, access_project.name + "_partial" + _reset_role(client, role) + client.command(f"GRANT SELECT ON {db}.* TO {role}") + client.command(f"REVOKE SELECT ON {db}.events FROM {role}") + assert _flagged_rows(client, role) == { + ("SELECT", db, None, 0, 0), + ("SELECT", db, "events", 0, 1), + } + difference = _difference(client, role, [f"SELECT ON {db}.*"]) + assert not difference.missing and not difference.extra + assert difference.partial_revokes == {Right("SELECT", Scope(db, "events"), False)} + client.command(f"GRANT SELECT ON {db}.* TO {role}") + assert _flagged_rows(client, role) == {("SELECT", db, None, 0, 0)} + _assert_in_sync(client, role, [f"SELECT ON {db}.*"]) + + +def test_u2_revoking_a_child_at_the_same_scope_leaves_no_partial_revoke(access_project): + client = access_project.client + db, role = access_project.database, access_project.name + "_child" + _reset_role(client, role) + client.command(f"GRANT ALTER ON {db}.* TO {role}") + client.command(f"REVOKE ALTER DELETE ON {db}.* FROM {role}") + rows = _flagged_rows(client, role) + assert all(partial == 0 for *_, partial in rows) + assert {name for name, *_ in rows}.isdisjoint({"ALTER", "ALTER TABLE", "ALTER DELETE"}) + assert ("ALTER UPDATE", db, None, 0, 0) in rows + + +def test_u2_revoking_only_the_grant_option_is_a_partial_revoke_row(access_project): + client = access_project.client + db, role = access_project.database, access_project.name + "_option_revoke" + _reset_role(client, role) + client.command(f"GRANT SELECT ON {db}.* TO {role} WITH GRANT OPTION") + client.command(f"REVOKE GRANT OPTION FOR SELECT ON {db}.events FROM {role}") + assert _flagged_rows(client, role) == { + ("SELECT", db, None, 1, 0), + ("SELECT", db, "events", 1, 1), + } + client.command(f"GRANT SELECT ON {db}.* TO {role} WITH GRANT OPTION") + assert _flagged_rows(client, role) == {("SELECT", db, None, 1, 0)} + + +# U3. Grants on objects that don't exist yet. + + +def test_u3_grants_on_missing_objects_are_kept_and_work_later( + access_project, clickhouse_server, request +): + client = access_project.client + later = access_project.name + "_later_db" + request.addfinalizer(lambda: client.command(f"DROP DATABASE IF EXISTS {later} SYNC")) + identity = _identity(access_project, "u3") + _create_user(client, identity) + client.command(f"GRANT CREATE TABLE, SELECT, INSERT ON {later}.* TO {identity.user}") + client.command(f"GRANT SELECT ON {access_project.database}.missing TO {identity.user}") + assert {_row_key(row)[:3] for row in _grant_rows(client, "user", identity.user)} == { + ("CREATE TABLE", later, None), + ("SELECT", later, None), + ("INSERT", later, None), + ("SELECT", access_project.database, "missing"), + } + client.command(f"CREATE DATABASE {later}") + user = _connect(clickhouse_server, identity, request) + user.command(f"CREATE TABLE {later}.t (id UInt64) ENGINE = MergeTree ORDER BY id") + user.command(f"INSERT INTO {later}.t VALUES (1)") + assert user.command(f"SELECT count() FROM {later}.t") == 1 + client.command(f"DROP DATABASE {later} SYNC") + assert len(_grant_rows(client, "user", identity.user)) == 4 + + +# U4. Passwords. + + +@pytest.mark.parametrize( + "method", + ["", "sha256_password", "double_sha1_password", "bcrypt_password"], + ids=["default", "sha256", "double_sha1", "bcrypt"], +) +def test_u4_nothing_the_admin_reads_shows_a_password_or_hash(access_project, method): + """The password goes in as a literal, as bootstrap sends it, so the query log could hold it.""" + client = access_project.client + identity = _identity(access_project, "u4") + with_method = f" WITH {method}" if method else "" + client.command(f"CREATE USER {identity.user} IDENTIFIED{with_method} BY '{identity.password}'") + texts = _admin_views(client, identity.user) + secrets_ = _password_forms(identity.password) + for text in texts: + assert not any(secret in text.lower() for secret in secrets_), text + assert "$2" not in "".join(texts) # no bcrypt hash + + +# U5. CHECK GRANT. + + +def test_u5_check_grant_on_this_image(access_project, clickhouse_server, request): + """Supported images answer 1 or 0, and 0 for a partly held group; 24.8 has no CHECK GRANT.""" + client, db = access_project.client, access_project.database + identity = _identity(access_project, "u5") + _create_user(client, identity) + for grant in ("SELECT, ALTER UPDATE ON {db}.*", "SELECT ON {db}_missing.*"): + client.command(f"GRANT {grant.format(db=db)} TO {identity.user}") + user = _connect(clickhouse_server, identity, request) + if not _image(client)["check_grant"]: + with pytest.raises(DatabaseError, match="SYNTAX_ERROR"): + user.command(f"CHECK GRANT SELECT ON {db}.*") + _assert_shows_own_grants(client, user, identity) + return + answers = { + f"SELECT ON {db}.events": 1, + f"ALTER UPDATE ON {db}.*": 1, + f"ALTER ON {db}.*": 0, + f"INSERT ON {db}.*": 0, + f"SELECT ON {db}_missing.events": 1, + } + assert {grant: user.command(f"CHECK GRANT {grant}") for grant in answers} == answers + with pytest.raises(DatabaseError, match="SYNTAX_ERROR"): + user.command(f"CHECK GRANT SELECT ON {db}.* WITH GRANT OPTION") + + +def _assert_shows_own_grants(client, user, identity): + """Without CHECK GRANT, a user can still read its own grants and its roles'.""" + db = identity.database + shown = [line for (line,) in user.query("SHOW GRANTS").result_rows] + assert f"GRANT SELECT, ALTER UPDATE ON {db}.* TO {identity.user}" in shown + client.command(f"CREATE ROLE {identity.role}") + client.command(f"GRANT INSERT ON {db}.* TO {identity.role}") + client.command(f"GRANT {identity.role} TO {identity.user}") + shown = [line for (line,) in user.query(f"SHOW GRANTS FOR {identity.role}").result_rows] + assert shown == [f"GRANT INSERT ON {db}.* TO {identity.role}"] + with pytest.raises(DatabaseError, match="ACCESS_DENIED"): + user.command("SELECT count() FROM system.grants") + + +# U6. The smallest admin. + + +def test_u6_smallest_admin_runs_a_core_bootstrap(access_project, clickhouse_server, request): + """Every required grant lands; no best-effort grant does, and none raises.""" + client, tree = access_project.client, PrivilegeTree.read(access_project.client) + admin = _admin_login(access_project, clickhouse_server, SMALLEST_ADMIN).connect() + request.addfinalizer(admin.close) + identity = _identity(access_project, "core") + _core_bootstrap(admin, identity) + difference = _difference(client, identity.role, _core_grants(access_project)) + best_effort = desired_rights( + tree, [parse_grant(g) for g in _render(access_project, CORE_BEST_EFFORT)] + ) + assert difference.missing == best_effort + assert not difference.extra + assert client.command(f"EXISTS DATABASE {identity.database}") == 1 + + +@pytest.mark.parametrize("left_out", range(len(SMALLEST_ADMIN))) +def test_u6_each_smallest_admin_grant_is_needed( + access_project, clickhouse_server, request, left_out +): + grants = SMALLEST_ADMIN[:left_out] + SMALLEST_ADMIN[left_out + 1 :] + admin = _admin_login(access_project, clickhouse_server, grants).connect() + request.addfinalizer(admin.close) + with pytest.raises(DatabaseError, match="ACCESS_DENIED"): + _core_bootstrap(admin, _identity(access_project, "core")) + + +def test_u6_create_database_if_not_exists_needs_the_grant_when_it_exists( + access_project, clickhouse_server, request +): + """So a bootstrap against an existing database still needs CREATE DATABASE.""" + access_project.client.command(f"CREATE DATABASE {access_project.database}") + grants = tuple(g for g in SMALLEST_ADMIN if not g.startswith("CREATE DATABASE")) + admin = _admin_login(access_project, clickhouse_server, grants).connect() + request.addfinalizer(admin.close) + with pytest.raises(DatabaseError, match="ACCESS_DENIED"): + admin.command(f"CREATE DATABASE IF NOT EXISTS {access_project.database}") + + +def test_u6_the_t1_limited_admin_cannot_give_three_best_effort_grants( + access_project, limited_admin, request +): + client, tree = access_project.client, PrivilegeTree.read(access_project.client) + admin = limited_admin.connect() + request.addfinalizer(admin.close) + identity = _identity(access_project, "core") + _core_bootstrap(admin, identity) + difference = _difference(client, identity.role, _core_grants(access_project)) + unreachable = ("CLUSTER ON *.*", "READ ON REMOTE", "CREATE TEMPORARY TABLE ON *.*") + assert difference.missing == desired_rights(tree, [parse_grant(g) for g in unreachable]) + assert not difference.extra + + +# U7. What ch-migrate's own paths need. + + +def test_u7_core_required_alone_runs_these_paths(access_project, monkeypatch): + """new, up (with a mutation to wait on), status, history, lint, snapshot, diff, + new --table and down. rebase and deps are not run.""" + identity = _core_migration_user(access_project, CORE_REQUIRED, monkeypatch) + _write_migration(access_project, _u7_upgrade(identity), U7_DOWNGRADE) + for command in (["up", "it"], ["status", "it"], ["history", "it"], ["lint", "it"]): + _assert_runs(access_project, *command) + _assert_runs(access_project, "snapshot", "it") + _assert_runs(access_project, "diff", "it") + _assert_runs(access_project, "new", "it", "scaffold", "--table", "events") + _assert_runs(access_project, "down", "it") + assert access_project.client.command(f"EXISTS TABLE {identity.database}.events") == 0 + + +@pytest.mark.parametrize( + "dropped, command, denied", + [ + ("SELECT ON system.mutations", "up", "system.mutations"), + ("SELECT ON system.dictionaries", "snapshot", "system.dictionaries"), + ], +) +def test_u7_these_system_grants_are_needed(access_project, monkeypatch, dropped, command, denied): + kept = tuple(g for g in CORE_REQUIRED if g != dropped) + identity = _core_migration_user(access_project, kept, monkeypatch) + _write_migration(access_project, _u7_upgrade(identity), U7_DOWNGRADE) + result = access_project.run(command, "it") + assert result.exit_code != 0, result.output + assert "ACCESS_DENIED" in result.output or "Not enough privileges" in result.output + assert denied in result.output, result.output + + +def test_u7_system_databases_and_tables_are_readable_without_a_grant(access_project, monkeypatch): + """ClickHouse grants them implicitly on self-hosted servers, so revoking changes nothing.""" + implicit = ("SELECT ON system.databases", "SELECT ON system.tables") + kept = tuple(g for g in CORE_REQUIRED if g not in implicit) + identity = _core_migration_user(access_project, kept, monkeypatch) + _write_migration(access_project, _u7_upgrade(identity), U7_DOWNGRADE) + _assert_runs(access_project, "up", "it") + _assert_runs(access_project, "down", "it") + + +@pytest.mark.cluster +@pytest.mark.parametrize( + "dropped, named", + [ + ("CLUSTER ON *.*", "CLUSTER"), + ("READ ON REMOTE", "READ ON REMOTE"), + ("SYSTEM SYNC REPLICA, SYSTEM SYNC DATABASE REPLICA ON {db}.*", "SYSTEM SYNC REPLICA"), + ], +) +def test_u7_cluster_up_needs_these_best_effort_grants( + cluster_access_project, monkeypatch, dropped, named +): + """With `cluster` set, `up` fails without each of these, and the error names it.""" + project = cluster_access_project + grants = CORE_REQUIRED + tuple(g for g in CORE_BEST_EFFORT if g != dropped) + _cluster_migration_user(project, grants, monkeypatch) + _write_migration(project, U7_CLUSTER_UPGRADE, U7_CLUSTER_DOWNGRADE) + result = project.run("up", "it") + assert result.exit_code != 0, result.output + assert "ACCESS_DENIED" in result.output and named in result.output, result.output + + +@pytest.mark.cluster +@pytest.mark.parametrize("dropped", [None, "CREATE TEMPORARY TABLE ON *.*"]) +def test_u7_cluster_up_runs_without_create_temporary_table( + cluster_access_project, monkeypatch, dropped +): + project = cluster_access_project + grants = CORE_REQUIRED + tuple(g for g in CORE_BEST_EFFORT if g != dropped) + _cluster_migration_user(project, grants, monkeypatch) + _write_migration(project, U7_CLUSTER_UPGRADE, U7_CLUSTER_DOWNGRADE) + _assert_runs(project, "up", "it") + _assert_runs(project, "down", "it") + + +@pytest.mark.cluster +@pytest.mark.parametrize( + "dropped, expected", + [ + (None, "Timed out"), + ("SELECT ON system.parts", "Timed out"), + ("SELECT ON system.replicas", "system.replicas"), + ], +) +def test_u7_cluster_waiting_on_a_held_mutation( + cluster_access_project, clickhouse_cluster, monkeypatch, dropped, expected +): + """The waiter reads system.replicas, and maybe system.parts, only while a mutation is pending. + + Without system.parts it still waits; without system.replicas it fails. Merges stay + stopped, so a waiter that works ends at `up`'s timeout. + """ + project = cluster_access_project + grants = CORE_REQUIRED + tuple(g for g in CORE_BEST_EFFORT if g != dropped) + _cluster_migration_user(project, grants, monkeypatch) + _hold_cluster_mutations(project, clickhouse_cluster) + _write_migration(project, U7_HELD_UPGRADE, U7_CLUSTER_DOWNGRADE) + result = project.run("up", "it", "--timeout", "2") + assert result.exit_code == 1 and expected in result.output, result.output + if dropped == "SELECT ON system.replicas": + assert "ACCESS_DENIED" in result.output and "Timed out" not in result.output + + +# U8. system.privileges on each image. + + +def test_u8_system_privileges_shape_on_this_image(access_project): + client = access_project.client + image = _image(client) + columns = client.query("SELECT * FROM system.privileges LIMIT 0").column_names + assert list(columns) == ["privilege", "aliases", "level", "parent_group"] + tree = PrivilegeTree.read(client) + assert len(tree.levels) > 150 + assert tree.levels["CREATE USER"] == image["create_user_level"] + assert tree.canonical("DELETE") == "ALTER DELETE" + assert ("READ" in tree.levels) == image["source_grants"] + grant_columns = client.query("SELECT * FROM system.grants LIMIT 0").column_names + assert ("access_object" in grant_columns) == image["source_grants"] + + +def test_u8_leaf_expansion_matches_both_profiles_on_this_image(access_project): + """U1's mechanism on this image, without READ ON REMOTE where the image can't parse it.""" + client = access_project.client + role = access_project.name + "_migration_role" + for profile in (_legacy_grants(access_project), _core_grants(access_project)): + profile = _given_in_full(client, profile) + _reset_role(client, role) + kept = [] + for statement in profile: + error = _try(client, _as_written(statement, role)) + if error: + assert not _source_grants(client) and "REMOTE" in statement, error + assert "SYNTAX_ERROR" in error + continue + kept.append(statement) + _assert_in_sync(client, role, kept) + + +def test_u8_legacy_bootstrap_on_this_image(access_project): + """0.8's bootstrap ended at READ ON REMOTE, which 24.8 can't parse, before any user existed. + + T6 changed that on purpose (design note, Decision 6): the user is created before any + grant, and READ ON REMOTE is best-effort, so on 24.8 its SYNTAX_ERROR is only a warning. + """ + result = access_project.run("bootstrap", "it") + users = access_project.client.command( + "SELECT count() FROM system.users WHERE name = {name:String}", + parameters={"name": access_project.migration_user}, + ) + assert result.exit_code == 0 and users == 1, result.output + if not _source_grants(access_project.client): + assert "READ ON REMOTE" in result.stderr and "SYNTAX_ERROR" in result.stderr + + +# U9 and U10. Where users and roles are stored, and when other nodes see them. + + +@pytest.mark.cluster +def test_u9_local_storage_is_detected_and_needs_on_cluster(clickhouse_cluster, request): + cluster = clickhouse_cluster + name = "it_" + secrets.token_hex(8) + request.addfinalizer(lambda: _drop_everywhere(cluster, name)) + assert _writable_storage(cluster.clients[1]) == "local_directory" + cluster.clients[1].command(f"CREATE ROLE {name}_here") + cluster.clients[1].command(f"CREATE ROLE {name}_everywhere ON CLUSTER {cluster.name}") + cluster.clients[1].command( + f"GRANT ON CLUSTER {cluster.name} SELECT ON system.one TO {name}_everywhere" + ) + assert _role_storage(cluster.clients[1], f"{name}_here") == "local_directory" + assert _roles_on(cluster.clients[2], name) == {f"{name}_everywhere"} + assert _grant_rows(cluster.clients[2], "role", f"{name}_everywhere") + cluster.clients[1].command(f"GRANT SELECT ON system.numbers TO {name}_everywhere") + node2 = {row["table"] for row in _grant_rows(cluster.clients[2], "role", f"{name}_everywhere")} + assert node2 == {"one"} + + +@pytest.mark.cluster +def test_u9_replicated_storage_is_detected_and_reaches_every_node( + clickhouse_cluster_keeper, request +): + cluster = clickhouse_cluster_keeper + name = "it_" + secrets.token_hex(8) + request.addfinalizer(lambda: _drop_everywhere(cluster, name)) + for client in cluster.clients.values(): + assert _writable_storage(client) == "replicated" + cluster.clients[1].command(f"CREATE ROLE {name}_here") + assert _role_storage(cluster.clients[1], f"{name}_here") == "replicated" + _wait_until(lambda: _roles_on(cluster.clients[2], name) == {f"{name}_here"}) + with pytest.raises(DatabaseError) as raised: + cluster.clients[1].command( + f"CREATE ROLE {name}_twice ON CLUSTER {cluster.name}", + # Buffered, so the error keeps its code (see the next test). + settings={"distributed_ddl_task_timeout": 30, "wait_end_of_query": 1}, + ) + assert (raised.value.code, raised.value.name) == (493, "ACCESS_ENTITY_ALREADY_EXISTS") + + +@pytest.mark.cluster +@pytest.mark.parametrize("buffered", [False, True]) +def test_u9_on_cluster_error_after_a_host_answered_needs_wait_end_of_query( + clickhouse_cluster_keeper, request, buffered +): + """Node 2 starts late, so node 1's status row is sent before node 2's error. + + Unbuffered, the server has already answered 200: it appends the error and cuts the + response, and the client sees a broken stream with no code. `wait_end_of_query=1` turns + the same error into an HTTP 500 with its code. + """ + cluster = clickhouse_cluster_keeper + name = "it_" + secrets.token_hex(8) + request.addfinalizer(lambda: _drop_everywhere(cluster, name)) + error = _create_role_on_cluster_with_node_2_late(cluster, name, buffered) + if buffered: + assert (error.code, error.name) == (493, "ACCESS_ENTITY_ALREADY_EXISTS"), error + else: + assert isinstance(error, OperationalError) and error.code is None, error + assert "Connection broken" in str(error), error + + +@pytest.mark.cluster +def test_u10_replicated_grant_reaches_the_other_node_within_the_retry_limit( + clickhouse_cluster_keeper, request +): + """Measured on Docker: printed for the spike record; asserted only against 30 s.""" + cluster = clickhouse_cluster_keeper + name = "it_" + secrets.token_hex(8) + request.addfinalizer(lambda: _drop_everywhere(cluster, name)) + cluster.clients[1].command(f"CREATE ROLE {name}_role") + _wait_until(lambda: _roles_on(cluster.clients[2], name) == {f"{name}_role"}) + delays = [] + for table in ("one", "numbers", "tables", "databases", "columns") * 4: + cluster.clients[1].command(f"GRANT SELECT ON system.{table} TO {name}_role") + delays.append(_time_until_visible(cluster.clients[2], f"{name}_role", table)) + cluster.clients[1].command(f"REVOKE SELECT ON system.{table} FROM {name}_role") + print(f"U10 delays (s): max {max(delays):.3f}, median {statistics.median(delays):.3f}") + assert max(delays) < 30 + + +@pytest.fixture +def cluster_access_project(clickhouse_cluster, tmp_path, monkeypatch, request): + """A project on the local-storage cluster whose migration user is made by the test.""" + cluster = clickhouse_cluster + project = _cluster_project(cluster, tmp_path, monkeypatch) + request.addfinalizer(lambda: _drop_everywhere(cluster, project.name)) + request.addfinalizer( + lambda: cluster.clients[1].command( + f"DROP DATABASE IF EXISTS {project.database} ON CLUSTER {cluster.name} SYNC" + ) + ) + cluster.clients[1].command(f"CREATE DATABASE {project.database} ON CLUSTER {cluster.name}") + return project + + +# Helpers. + + +def _grant_to_fresh_role(client, grant, role): + """Grant to an empty role; return the server's error text, or None.""" + _reset_role(client, role) + return _try(client, _grant_sql(grant, role)) + + +def _reset_role(client, role): + client.command(f"DROP ROLE IF EXISTS {role}") + client.command(f"CREATE ROLE {role}") + + +def _grant_sql(grant, role, on_cluster=""): + """`GRANT [ON CLUSTER c] [CURRENT GRANTS(]... ON target[)] TO role [WITH GRANT OPTION]`.""" + what = f"{', '.join(grant.privileges)} ON {_target_sql(grant.scope)}" + if grant.best_effort: + what = f"CURRENT GRANTS({what})" + cluster = f" ON CLUSTER {on_cluster}" if on_cluster else "" + option = " WITH GRANT OPTION" if grant.grant_option else "" + return f"GRANT{cluster} {what} TO {role}{option}" + + +def _as_written(statement, role): + """0.8's statements already name the role; a core grant is ` ON `.""" + return statement if statement.startswith("GRANT") else f"GRANT {statement} TO {role}" + + +def _target_sql(scope): + if scope.source: + return scope.source + return f"{scope.database or '*'}.{scope.table or '*'}" + + +def _try(client, sql): + try: + client.command(sql) + except DatabaseError as error: + return str(error) + return None + + +def _grant_rows(client, kind, name): + column = "user_name" if kind in ("user", "user_name") else "role_name" + result = client.query( + f"SELECT * FROM system.grants WHERE {column} = {{name:String}}", + parameters={"name": name}, + ) + return [dict(zip(result.column_names, row)) for row in result.result_rows] + + +def _row_key(row): + return (row["access_type"], row["database"], row["table"], row.get("access_object", "")) + + +def _flagged_rows(client, role): + return { + ( + row["access_type"], + row["database"], + row["table"], + row["grant_option"], + row["is_partial_revoke"], + ) + for row in _grant_rows(client, "role", role) + } + + +def _assert_replace_converges(project, role, desired): + """Back to `db.*` plus a membership, then one REPLACE statement to the desired set.""" + client, db = project.client, project.database + member = project.name + "_member" + client.command(f"CREATE ROLE IF NOT EXISTS {member}") + client.command(f"GRANT {member} TO {role}") + client.command(f"REVOKE ALL ON *.* FROM {role}") + client.command(f"GRANT SELECT ON {db}.* TO {role}") + client.command(f"GRANT {', '.join(desired)} TO {role} WITH REPLACE OPTION") + _assert_in_sync(client, role, desired) + memberships = client.query( + "SELECT granted_role_name FROM system.role_grants WHERE role_name = {r:String}", + parameters={"r": role}, + ).result_rows + assert memberships == [(member,)] + + +def _difference(client, role, statements): + tree = PrivilegeTree.read(client) + desired = desired_rights(tree, [parse_grant(statement) for statement in statements]) + return compare(desired, live_rights(tree, _grant_rows(client, "role", role))) + + +def _assert_in_sync(client, role, statements): + difference = _difference(client, role, statements) + assert difference.in_sync, (statements, difference) + + +def _assert_rejection_explained(error, desired, held_by_admin): + """A rejected grant expands to nothing, or asks for rights the admin can't pass on: not + held with grant option, or with part of it revoked, as ClickHouse Cloud's admin has + `SELECT ON system.zookeeper` revoked inside `SELECT ON *.*`.""" + if "ACCESS_DENIED" in error: + held, revoked = held_by_admin + assert any(not held_in_full(r, held, revoked) for r in desired) + return + assert "INVALID_GRANT" in error or "SYNTAX_ERROR" in error, error + assert not desired, error + + +def _assert_source_rewrite(grant, difference): + """` ON *.*` is stored as READ and WRITE on that source (SOURCES: on all).""" + [privilege] = grant.privileges + assert grant.scope == Scope() and not difference.partial_revokes, (grant, difference) + assert difference.missing == {Right(privilege, Scope(), False)}, (grant, difference) + source = Scope() if privilege == "SOURCES" else Scope(source=privilege) + expected = {Right("READ", source, False), Right("WRITE", source, False)} + assert difference.extra == expected, (grant, difference) + + +def _create_events_table(project): + project.client.command(f"CREATE DATABASE IF NOT EXISTS {project.database}") + project.client.command( + f"CREATE TABLE IF NOT EXISTS {project.database}.events (id UInt64) " + "ENGINE = MergeTree ORDER BY id" + ) + + +def _given_in_full(client, statements): + """The statements whose rights the admin can give in full: all of them on a stock server. + + A best-effort `CURRENT GRANTS` lands only what the admin holds with grant option, so it + is compared only where that is all of it. ClickHouse Cloud's admin holds neither + `SELECT ON system.zookeeper` nor a CLUSTER grant: Cloud grants CLUSTER to every login. + """ + return [s for s in statements if not parse_grant(s).best_effort or gives_in_full(client, s)] + + +def _legacy_grants(project): + """The privilege grants in 0.8's bootstrap SQL, for the project's role and database.""" + sql = build_bootstrap_sql( + project=project.name, + db=project.database, + migration_user=project.migration_user, + migration_password="unused", + ) + lines = [line for line in sql.splitlines() if not line.strip().startswith("--")] + statements = [" ".join(s.split()) for s in "\n".join(lines).split(";")] + return [s for s in statements if s.startswith("GRANT") and " ON " in s] + + +def _core_grants(project): + return _render(project, CORE_REQUIRED + CORE_BEST_EFFORT) + + +def _render(project, grants): + return [grant.format(db=project.database) for grant in grants] + + +def _identity(project, tag): + name = f"{project.name}_{tag}" + return Identity(project.database, name + "_role", name, AccessProject.new_password()) + + +def _create_user(client, identity): + client.command( + f"CREATE USER {identity.user} IDENTIFIED BY {{password:String}}", + parameters={"password": identity.password}, + ) + + +def _connect(server, identity, request): + client = replace(server, user=identity.user, password=identity.password).connect() + request.addfinalizer(client.close) + return client + + +def _admin_views(client, user): + """Everything an admin reads by default that could carry a user's password.""" + secrets_shown = {"format_display_secrets_in_show_and_select": 1} + texts = [ + _text(client, f"SHOW CREATE USER {user}", None), + _text(client, f"SHOW CREATE USER {user}", secrets_shown), + _text(client, f"SELECT * FROM system.users WHERE name = '{user}'", None), + ] + if client.command("CHECK GRANT SHOW ACCESS ON *.*"): # ClickHouse Cloud's admin can't + texts.append(_text(client, "SHOW ACCESS", None)) + logged = client.query( + f"SELECT query FROM {query_log(client)} WHERE position(query, {{user:String}}) > 0", + parameters={"user": user}, + ).result_rows + assert logged, "the CREATE USER statement should be in the query log" + return texts + [str(row) for row in logged] + + +def _text(client, sql, settings): + return repr(client.query(sql, settings=settings).result_rows) + + +def _password_forms(password): + """The password and the digests ClickHouse can store for it, in lowercase hex.""" + sha1 = hashlib.sha1(hashlib.sha1(password.encode()).digest()).hexdigest() + return [password.lower(), hashlib.sha256(password.encode()).hexdigest(), sha1] + + +def _image(client): + version = _image_version(client) + if version not in IMAGES: + pytest.skip(f"No spike expectations for ClickHouse {version}; record them in IMAGES") + return IMAGES[version] + + +def _image_version(client): + return ".".join(client.command("SELECT version()").split(".")[:2]) + + +def _source_grants(client): + """Whether the server takes `READ ON `: `READ` is one of its privileges (U8).""" + return "READ" in PrivilegeTree.read(client).levels + + +def _admin_login(project, server, grants): + """A login holding only `grants`.""" + login = replace(server, user=project.name + "_admin", password=project.new_password()) + project.client.command(f"DROP USER IF EXISTS {login.user}") + project.client.command( + f"CREATE USER {login.user} IDENTIFIED BY {{password:String}}", + parameters={"password": login.password}, + ) + for grant in grants: + grant = parse_grant(grant.format(db=project.database)) + project.client.command(_grant_sql(grant, login.user)) + return login + + +def _core_bootstrap(admin, identity): + """What a core-only bootstrap runs, by hand: there is no product code for it yet.""" + admin.command(f"CREATE DATABASE IF NOT EXISTS {identity.database}") + admin.command(f"CREATE ROLE IF NOT EXISTS {identity.role}") + for grant in CORE_REQUIRED: + admin.command(f"GRANT {grant.format(db=identity.database)} TO {identity.role}") + for grant in CORE_BEST_EFFORT: + rendered = grant.format(db=identity.database) + admin.command(f"GRANT CURRENT GRANTS({rendered}) TO {identity.role}") + admin.command( + f"CREATE USER IF NOT EXISTS {identity.user} IDENTIFIED BY {{password:String}}", + parameters={"password": identity.password}, + ) + admin.command(f"GRANT {identity.role} TO {identity.user}") + + +def _core_migration_user(project, grants, monkeypatch): + """The project's migration user, holding a role with exactly `grants`.""" + client = project.client + identity = _identity(project, "migration") + client.command(f"CREATE DATABASE IF NOT EXISTS {identity.database}") + client.command(f"CREATE ROLE {identity.role}") + for grant in grants: + client.command(_grant_sql(parse_grant(grant.format(db=identity.database)), identity.role)) + _create_user(client, identity) + client.command(f"GRANT {identity.role} TO {identity.user}") + monkeypatch.setenv("CH_IT_MIGRATION_PASSWORD", identity.password) + return identity + + +def _u7_upgrade(identity): + """U7's migration, its dictionary reading as `identity`'s user.""" + return U7_UPGRADE.replace("", identity.user).replace("", identity.password) + + +def _write_migration(project, upgrade, downgrade): + result = project.run("new", "it", "spike") + assert result.exit_code == 0, result.output + [up] = list((project.root / "migrations" / "sql").rglob("*.up.sql")) + [down] = list((project.root / "migrations" / "sql").rglob("*.down.sql")) + up.write_text(upgrade) + down.write_text(downgrade) + + +def _assert_runs(project, *args): + result = project.run(*args) + assert result.exit_code == 0, (args, result.output) + return result + + +def _cluster_project(cluster, tmp_path, monkeypatch): + name = "it_" + secrets.token_hex(8) + project = AccessProject(tmp_path, cluster.clients[1], name) + initialize_cluster_project(cluster, project, monkeypatch) + return project + + +def _cluster_migration_user(project, grants, monkeypatch): + """Like `_core_migration_user`, with every statement ON CLUSTER so both nodes hold it.""" + client, cluster = project.client, "it_cluster" + identity = _identity(project, "migration") + client.command(f"CREATE ROLE {identity.role} ON CLUSTER {cluster}") + for grant in grants: + grant = parse_grant(grant.format(db=identity.database)) + client.command(_grant_sql(grant, identity.role, cluster)) + client.command( + f"CREATE USER {identity.user} ON CLUSTER {cluster} IDENTIFIED BY {{password:String}}", + parameters={"password": identity.password}, + ) + client.command(f"GRANT ON CLUSTER {cluster} {identity.role} TO {identity.user}") + monkeypatch.setenv("CH_IT_MIGRATION_PASSWORD", identity.password) + return identity + + +def _hold_cluster_mutations(project, cluster): + """A replicated table with one row, and merges stopped on both nodes.""" + table = f"{project.database}.events" + project.client.command( + f"CREATE TABLE {table} ON CLUSTER {cluster.name} (id UInt64, status String) " + f"ENGINE = ReplicatedMergeTree('/clickhouse/tables/{project.database}/events', " + "'{replica}') ORDER BY id" + ) + project.client.command(f"INSERT INTO {table} VALUES (1, 'new')") + for client in cluster.clients.values(): + client.command(f"SYSTEM STOP MERGES {table}") + + +def _drop_everywhere(cluster, prefix): + for client in cluster.clients.values(): + for kind, table in (("USER", "system.users"), ("ROLE", "system.roles")): + for (name,) in client.query( + f"SELECT name FROM {table} WHERE startsWith(name, {{p:String}})", + parameters={"p": prefix}, + ).result_rows: + client.command(f"DROP {kind} IF EXISTS {name}") + + +def _writable_storage(client): + """The first storage CREATE ROLE writes to: users.xml is read-only.""" + return client.command( + "SELECT type FROM system.user_directories WHERE type != 'users_xml' " + "ORDER BY precedence LIMIT 1" + ) + + +def _role_storage(client, role): + return client.command( + "SELECT storage FROM system.roles WHERE name = {r:String}", parameters={"r": role} + ) + + +def _roles_on(client, prefix): + rows = client.query( + "SELECT name FROM system.roles WHERE startsWith(name, {p:String})", + parameters={"p": prefix}, + ).result_rows + return {name for (name,) in rows} + + +def _create_role_on_cluster_with_node_2_late(cluster, name, buffered): + """`CREATE ROLE ... ON CLUSTER` on node 1 while node 2 is down for 3 s; return its error.""" + settings = {"distributed_ddl_task_timeout": 60, "wait_end_of_query": int(buffered)} + client = cluster.servers[1].connect() + errors = [] + + def create(): + try: + client.command(f"CREATE ROLE {name} ON CLUSTER {cluster.name}", settings=settings) + except DatabaseError as error: + errors.append(error) + + creating = threading.Thread(target=create) + cluster.stop_node(2) + try: + creating.start() + time.sleep(3) + finally: + cluster.start_node(2) + creating.join(60) + client.close() + assert len(errors) == 1, "node 2 should fail the create: node 1 already wrote the role" + return errors[0] + + +def _wait_until(condition, seconds=30): + deadline = time.monotonic() + seconds + while not condition(): + if time.monotonic() > deadline: + pytest.fail(f"Not true within {seconds} seconds") + time.sleep(0.01) + + +def _time_until_visible(client, role, table): + started = time.monotonic() + _wait_until(lambda: any(row["table"] == table for row in _grant_rows(client, "role", role))) + return time.monotonic() - started diff --git a/tests/integration/test_access_validate_sql.py b/tests/integration/test_access_validate_sql.py new file mode 100644 index 0000000..e4fc00a --- /dev/null +++ b/tests/integration/test_access_validate_sql.py @@ -0,0 +1,44 @@ +"""`access validate --sql` fails closed: an unedited password placeholder doesn't parse. + +Each password is printed unquoted, `IDENTIFIED BY `. Run as printed, the server +rejects the statement with SYNTAX_ERROR and creates no user, instead of setting the +placeholder text as the password. Filled in with the quoted secret, as the header says, it runs. +""" + +import pytest +from clickhouse_connect.driver.exceptions import DatabaseError + +from ch_migrate.sql import split_statements + +pytestmark = pytest.mark.integration + +ACCESS_YAML = """\ +users: + '{project}_etl': {password: {secret: etl_password}} +""" + + +def test_unedited_placeholders_fail_to_parse_and_create_no_user(access_project): + (access_project.root / "access.yaml").write_text(ACCESS_YAML) + result = access_project.run("access", "validate", "it", "--sql") + assert result.exit_code == 0, result.output + sql = [statement.sql for statement in split_statements(result.stdout)] + creates = [statement for statement in sql if statement.startswith("CREATE USER")] + assert len(creates) == 2, result.stdout + for statement in creates: + with pytest.raises(DatabaseError, match="SYNTAX_ERROR"): + access_project.client.command(statement) + assert _users(access_project) == [] + + (etl,) = [statement for statement in creates if "" in statement] + password = access_project.new_password() + access_project.client.command(etl.replace("", f"'{password}'")) + assert _users(access_project) == [access_project.name + "_etl"] + + +def _users(project): + result = project.client.query( + "SELECT name FROM system.users WHERE startsWith(name, {prefix:String}) ORDER BY name", + parameters={"prefix": project.name}, + ) + return [name for (name,) in result.result_rows] diff --git a/tests/integration/test_cloud.py b/tests/integration/test_cloud.py index 15dcae5..05f9020 100644 --- a/tests/integration/test_cloud.py +++ b/tests/integration/test_cloud.py @@ -1,4 +1,4 @@ -"""ClickHouse Cloud-only checks; they skip on self-hosted servers (DRY-1413).""" +"""ClickHouse Cloud-only checks; they skip on self-hosted servers.""" import subprocess import sys diff --git a/tests/integration/test_mutation_waiting.py b/tests/integration/test_mutation_waiting.py index 3029298..70b1cad 100644 --- a/tests/integration/test_mutation_waiting.py +++ b/tests/integration/test_mutation_waiting.py @@ -152,7 +152,7 @@ def test_failed_mutation_is_not_recorded_and_names_its_kill(project): def test_killed_mutation_then_fixed_sql_runs_again(project): - """DRY-1604: after the kill, fixing the file and running `up` is the whole recovery.""" + """After the kill, fixing the file and running `up` is the whole recovery.""" db = project.database project.client.command( f"CREATE TABLE {db}.orders (id UInt64, raw String, qty UInt64) ENGINE=MergeTree ORDER BY id" @@ -183,7 +183,7 @@ def test_killed_mutation_then_fixed_sql_runs_again(project): def test_rejected_statement_can_be_fixed_and_run_again(project): - """DRY-1604: ClickHouse refuses a sorting-key change; the corrected file then applies.""" + """ClickHouse refuses a sorting-key change; the corrected file then applies.""" _seed(project) path = _upgrade_sql(project, "ALTER TABLE {db}.counter MODIFY COLUMN id String") rejected = project.run("up", "it") diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index 1fe611c..4e16476 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -1,11 +1,18 @@ """Tests for bootstrap module.""" +import json import sys from pathlib import Path +from types import SimpleNamespace from unittest.mock import MagicMock, patch +# The stand-in below replaces the `clickhouse_connect` module only; its driver stays real. +import clickhouse_connect.driver.exceptions # noqa: F401 import pytest +import yaml +from ch_migrate.access.privileges import BUNDLED_LIST +from ch_migrate.access.templates import statement from ch_migrate.bootstrap import ( build_bootstrap_sql, escape_sql_string, @@ -13,6 +20,10 @@ validate_identifier, ) +# What 0.8's `build_bootstrap_sql` returned, recorded before it became a wrapper around the +# `legacy` profile: one statement per line, comments dropped and whitespace collapsed. +RECORDED_0_8 = Path(__file__).parent / "fixtures" / "access" / "build_bootstrap_sql_0_8.json" + class TestEscapeSqlString: def test_escapes_single_quotes(self): @@ -179,6 +190,38 @@ def test_rejects_invalid_project_name(self): migration_password="secret", ) + @pytest.mark.parametrize("case", sorted(json.loads(RECORDED_0_8.read_text()))) + def test_returns_0_8_statements(self, case): + """The same statements as 0.8, password escaping included, in any order.""" + recorded = json.loads(RECORDED_0_8.read_text())[case] + mcp, dict_reader = "mcp" in case, "dict_reader" in case + sql = build_bootstrap_sql( + project="shop", + db="shop_dev", + migration_user="shop_migrator", + migration_password="pw'one\\x", + mcp_user_name="shop_mcp" if mcp else None, + mcp_password="pw-mcp" if mcp else None, + dict_reader_name="shop_dict" if dict_reader else None, + dict_reader_password="pw-dict" if dict_reader else None, + ) + assert sorted(_statements(sql)) == sorted(recorded) + + def test_creates_roles_and_users_before_any_grant(self): + """Decision 6: 0.8 created the migration user last, after every grant.""" + sql = build_bootstrap_sql( + project="myproject", + db="myproject_dev", + migration_user="migration_dev", + migration_password="secret123", + mcp_user_name="mcp_reader", + mcp_password="mcppass", + ) + kinds = [" ".join(statement.split()[:2]) for statement in _statements(sql)] + # The migration and read-only roles, then the migration and MCP users. + assert kinds[:5] == ["CREATE DATABASE"] + ["CREATE ROLE"] * 2 + ["CREATE USER"] * 2 + assert all(kind.startswith("GRANT") for kind in kinds[5:]) + def test_rejects_invalid_migration_user(self): with pytest.raises(ValueError, match="Invalid migration user"): build_bootstrap_sql( @@ -190,7 +233,11 @@ def test_rejects_invalid_migration_user(self): class TestRunBootstrap: - """Integration tests for run_bootstrap() with mocked connections.""" + """run_bootstrap() in legacy mode, against a stand-in for clickhouse_connect. + + The stand-in answers like a 26.3 server holding nothing yet, so bootstrap reads back what + it granted and then checks, logged in as the migration user (design note, 2.5). + """ @pytest.fixture def mock_env_config(self): @@ -208,113 +255,159 @@ def mock_env_config(self): def mock_clickhouse_connect(self): """Mock clickhouse_connect module for lazy import.""" mock_module = MagicMock() - mock_client = MagicMock() + mock_client = _FakeClient() mock_module.get_client.return_value = mock_client return mock_module, mock_client - @patch("ch_migrate.bootstrap.get_secret") - @patch("ch_migrate.bootstrap.get_env_config") - def test_executes_sql_statements( - self, mock_get_env_config, mock_get_secret, mock_env_config, mock_clickhouse_connect - ): + @pytest.fixture(autouse=True) + def secrets(self, monkeypatch): + for name in ("ADMIN", "MIGRATION", "DICT_READER", "MCP"): + monkeypatch.delenv(f"CH_DEV_{name}_PASSWORD", raising=False) + monkeypatch.setenv("CH_DEV_ADMIN_PASSWORD", "adminpass") + monkeypatch.setenv("CH_DEV_MIGRATION_PASSWORD", "migrationpass") + + def test_executes_sql_statements(self, tmp_path, mock_env_config, mock_clickhouse_connect): """Test that run_bootstrap executes SQL statements on the client.""" mock_module, mock_client = mock_clickhouse_connect - mock_get_env_config.return_value = mock_env_config - mock_get_secret.side_effect = lambda env, key, **kwargs: { - "admin_password": "adminpass", - "migration_password": "migrationpass", - }.get(key) + config_path = _write_config(tmp_path, mock_env_config) with patch.dict(sys.modules, {"clickhouse_connect": mock_module}): - run_bootstrap("dev", config_path=Path("/fake/config.yaml")) + run_bootstrap("dev", config_path=config_path) - # Verify client was created with correct params - mock_module.get_client.assert_called_once() - call_kwargs = mock_module.get_client.call_args[1] - assert call_kwargs["host"] == "localhost" - assert call_kwargs["username"] == "default" - assert call_kwargs["password"] == "adminpass" + # The admin logs in first; then the migration user, to check its grants (2.5). + admin, migration = mock_module.get_client.call_args_list + assert admin.kwargs["host"] == "localhost" + assert admin.kwargs["username"] == "default" + assert admin.kwargs["password"] == "adminpass" + assert migration.kwargs["host"] == "localhost" + assert migration.kwargs["username"] == "migration_dev" + assert migration.kwargs["password"] == "migrationpass" # Verify SQL was executed - assert mock_client.command.call_count > 0 + assert len(mock_client.commands) > 0 - @patch("ch_migrate.bootstrap.get_secret") - @patch("ch_migrate.bootstrap.get_env_config") def test_dry_run_does_not_execute( - self, mock_get_env_config, mock_get_secret, mock_env_config, mock_clickhouse_connect + self, tmp_path, mock_env_config, mock_clickhouse_connect, monkeypatch ): - """Test that dry_run=True prints SQL without executing.""" + """Test that dry_run=True prints SQL without executing, or reading a secret.""" mock_module, mock_client = mock_clickhouse_connect - mock_get_env_config.return_value = mock_env_config - mock_get_secret.side_effect = lambda env, key, **kwargs: { - "admin_password": "adminpass", - "migration_password": "migrationpass", - }.get(key) + monkeypatch.delenv("CH_DEV_ADMIN_PASSWORD") + monkeypatch.delenv("CH_DEV_MIGRATION_PASSWORD") + config_path = _write_config(tmp_path, mock_env_config) - run_bootstrap("dev", config_path=Path("/fake/config.yaml"), dry_run=True) + with patch.dict(sys.modules, {"clickhouse_connect": mock_module}): + run_bootstrap("dev", config_path=config_path, dry_run=True) - # Client should not be created in dry run (import never happens) + # Client should not be created in dry run mock_module.get_client.assert_not_called() - @patch("ch_migrate.bootstrap.get_secret") - @patch("ch_migrate.bootstrap.get_env_config") - def test_raises_without_migration_user(self, mock_get_env_config, mock_get_secret): + def test_raises_without_migration_user(self, tmp_path): """Test that missing migration_user raises ValueError.""" - mock_get_env_config.return_value = { - "host": "localhost", - "database": "myproject_dev", - # No migration_user or user field - } - mock_get_secret.side_effect = lambda env, key, **kwargs: "password" + config_path = _write_config( + tmp_path, + { + "host": "localhost", + "database": "myproject_dev", + # No migration_user or user field + }, + ) with pytest.raises(ValueError, match="migration_user is required"): - run_bootstrap("dev", config_path=Path("/fake/config.yaml")) + run_bootstrap("dev", config_path=config_path) - @patch("ch_migrate.bootstrap.get_secret") - @patch("ch_migrate.bootstrap.get_env_config") - def test_supports_legacy_user_field( - self, mock_get_env_config, mock_get_secret, mock_clickhouse_connect - ): + def test_supports_legacy_user_field(self, tmp_path, mock_clickhouse_connect): """Test that legacy 'user' field is supported.""" mock_module, mock_client = mock_clickhouse_connect - mock_get_env_config.return_value = { - "host": "localhost", - "database": "myproject_dev", - "user": "migration_dev", # Legacy field - "project": "myproject", - "secure": False, - } - mock_get_secret.side_effect = lambda env, key, **kwargs: "password" + config_path = _write_config( + tmp_path, + { + "host": "localhost", + "database": "myproject_dev", + "user": "migration_dev", # Legacy field + "project": "myproject", + "secure": False, + }, + ) with patch.dict(sys.modules, {"clickhouse_connect": mock_module}): - run_bootstrap("dev", config_path=Path("/fake/config.yaml")) + run_bootstrap("dev", config_path=config_path) - # Should work without error - mock_module.get_client.assert_called_once() + # Should work without error: the admin, then the legacy field's user + logins = [call.kwargs["username"] for call in mock_module.get_client.call_args_list] + assert logins == ["default", "migration_dev"] - @patch("ch_migrate.bootstrap.get_secret") - @patch("ch_migrate.bootstrap.get_env_config") def test_includes_optional_users_when_configured( - self, mock_get_env_config, mock_get_secret, mock_clickhouse_connect + self, tmp_path, mock_clickhouse_connect, monkeypatch ): """Test that dict_reader and mcp_user are included when configured.""" mock_module, mock_client = mock_clickhouse_connect - mock_get_env_config.return_value = { - "host": "localhost", - "database": "myproject_dev", - "migration_user": "migration_dev", - "project": "myproject", - "dict_reader_name": "dict_reader", - "mcp_user_name": "mcp_user", - "secure": False, - } - mock_get_secret.side_effect = lambda env, key, **kwargs: f"{key}_value" + monkeypatch.setenv("CH_DEV_DICT_READER_PASSWORD", "dict_reader_password_value") + monkeypatch.setenv("CH_DEV_MCP_PASSWORD", "mcp_password_value") + config_path = _write_config( + tmp_path, + { + "host": "localhost", + "database": "myproject_dev", + "migration_user": "migration_dev", + "project": "myproject", + "dict_reader_name": "dict_reader", + "mcp_user_name": "mcp_user", + "secure": False, + }, + ) with patch.dict(sys.modules, {"clickhouse_connect": mock_module}): - run_bootstrap("dev", config_path=Path("/fake/config.yaml")) + run_bootstrap("dev", config_path=config_path) # Get all executed SQL - executed_sql = " ".join(str(call[0][0]) for call in mock_client.command.call_args_list) + executed_sql = " ".join(mock_client.commands) assert "dict_reader" in executed_sql assert "mcp_user" in executed_sql + + +class _FakeClient: + """A 26.3 server holding no user or role yet, on its own disk; it records each command. + + Every CHECK GRANT answers 1. + """ + + server_version = "26.3.1.1" + + def __init__(self): + self.commands = [] + self.rows = { + statement("live", "privileges"): json.loads(BUNDLED_LIST.read_text())["privileges"], + statement("live", "storage"): [{"type": "local_directory"}], + } + + def command(self, sql, parameters=None, settings=None): + self.commands.append(sql) + return 1 if sql.startswith("CHECK GRANT") else None + + def raw_query(self, sql, parameters=None, settings=None): + """A statement with a bound password, sent form-encoded in the request body.""" + return self.command(sql, parameters, settings) + + def query(self, sql, parameters=None, settings=None): + rows = self.rows.get(sql, []) + return SimpleNamespace(named_results=lambda: iter(rows)) + + def close(self): + pass + + +def _write_config(tmp_path, environment): + """config.yaml with one environment, `dev`, as written; `project` goes under `project`.""" + environment = dict(environment) + config = {"environments": {"dev": environment}} + if "project" in environment: + config["project"] = {"name": environment.pop("project")} + path = tmp_path / "config.yaml" + path.write_text(yaml.safe_dump(config)) + return path + + +def _statements(sql): + lines = [line for line in sql.splitlines() if not line.strip().startswith("--")] + return [" ".join(part.split()) for part in "\n".join(lines).split(";") if part.strip()] diff --git a/tests/test_helpers.py b/tests/test_helpers.py index f6e61dd..d81bdec 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -1,11 +1,15 @@ """Tests for migration helpers.""" from pathlib import Path +from types import SimpleNamespace +import alembic import pytest from ch_migrate.helpers import ( + DICT_READER_PASSWORD_ATTRIBUTE, _parse_source_table, + create_dictionary, get_cluster, get_db, on_cluster, @@ -133,3 +137,75 @@ def test_handles_multiline_query(self): ')) """ assert _parse_source_table(sql) == "customers" + + +DICTIONARY_SQL = ( + "CREATE DICTIONARY IF NOT EXISTS {db}.statuses (id UInt64, status String) PRIMARY KEY id " + "SOURCE(CLICKHOUSE(TABLE 'events' USER 'dict_reader' PASSWORD '{password}')) " + "LAYOUT(FLAT()) LIFETIME(0)" +) + + +class TestCreateDictionary: + @pytest.fixture + def executed(self, tmp_path: Path, monkeypatch): + """Statements create_dictionary sends, in a project whose environment holds a secret.""" + sql_dir = tmp_path / "migrations" / "sql" + sql_dir.mkdir(parents=True) + (sql_dir / "dict.sql").write_text(DICTIONARY_SQL) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("CH_DATABASE", "mydb") + monkeypatch.delenv("DICT_READER_PASSWORD", raising=False) + statements: list[str] = [] + monkeypatch.setattr(alembic, "op", SimpleNamespace(execute=statements.append)) + attributes = {DICT_READER_PASSWORD_ATTRIBUTE: "from-environment"} + monkeypatch.setattr( + alembic, "context", SimpleNamespace(config=SimpleNamespace(attributes=attributes)) + ) + return statements + + def test_grants_then_creates_without_access_yaml(self, executed): + create_dictionary("dict.sql") + assert executed[0] == "GRANT SELECT ON mydb.events TO dict_reader" + assert executed[1].startswith("CREATE DICTIONARY IF NOT EXISTS mydb.statuses") + assert len(executed) == 2 + + def test_only_creates_with_access_yaml(self, executed, tmp_path: Path): + (tmp_path / "access.yaml").write_text("migration_role:\n profile: core\n") + create_dictionary("dict.sql") + assert len(executed) == 1 + assert executed[0].startswith("CREATE DICTIONARY IF NOT EXISTS mydb.statuses") + + def test_an_empty_access_yaml_is_an_error_not_legacy_mode(self, executed, tmp_path: Path): + """The access commands' rule, so up can't skip the grant.""" + (tmp_path / "access.yaml").write_text("# nothing yet\n") + with pytest.raises(ValueError, match="access.yaml is empty"): + create_dictionary("dict.sql") + assert executed == [] + + def test_reads_the_environment_secret(self, executed): + create_dictionary("dict.sql") + assert "PASSWORD 'from-environment'" in executed[-1] + + def test_dict_reader_password_wins_over_the_environment_secret(self, executed, monkeypatch): + monkeypatch.setenv("DICT_READER_PASSWORD", "from-variable") + create_dictionary("dict.sql") + assert "PASSWORD 'from-variable'" in executed[-1] + + def test_an_explicit_password_wins(self, executed, monkeypatch): + monkeypatch.setenv("DICT_READER_PASSWORD", "from-variable") + create_dictionary("dict.sql", password="explicit") + assert "PASSWORD 'explicit'" in executed[-1] + + def test_a_colon_reaches_sqlalchemy_escaped(self, executed): + """SQLAlchemy reads `:name` as a bind parameter.""" + create_dictionary("dict.sql", password=":lead") + assert "PASSWORD '\\:lead'" in executed[-1] + + def test_no_password_anywhere_names_where_to_set_it(self, executed, monkeypatch): + monkeypatch.setattr( + alembic, "context", SimpleNamespace(config=SimpleNamespace(attributes={})) + ) + with pytest.raises(ValueError, match="CH__DICT_READER_PASSWORD"): + create_dictionary("dict.sql") + assert executed == [] diff --git a/tests/test_waiting_display.py b/tests/test_waiting_display.py index 0275674..3457f74 100644 --- a/tests/test_waiting_display.py +++ b/tests/test_waiting_display.py @@ -137,6 +137,26 @@ def test_interrupted_step_names_what_it_cannot_vouch_for(capsys): assert "ch-migrate up dev --rerun-interrupted 3f9c2a1b" in err +def test_interrupted_step_and_mutation_reports_hide_secrets(capsys, monkeypatch): + """Both quote SQL, which can carry a password.""" + monkeypatch.setattr("ch_migrate.secrets._SEEN", {"Probe!pw"}) + statement = MigrationStatement( + "CREATE DICTIONARY d SOURCE(CLICKHOUSE(PASSWORD 'Probe!pw'))", + "migrations/sql/d.up.sql", + 1, + (), + "upgrade", + ) + stop = InterruptedStep(Step("3f9c2a1b5d6e", "upgrade", None), [Unvouched(statement, "why")]) + _report_failure(Upgrade("dev"), _current("3f9c2a1b d"), stop) + failure = FailedMutation("d.t", "mutation_7.txt", "h1", "near 'Probe!pw'", "KILL MUTATION") + error = _statement_error(MutationFailed("failed", failure)) + _report_failure(Upgrade("dev"), _current("3f9c2a1b d"), error) + err = capsys.readouterr().err + assert "Probe!pw" not in err + assert "PASSWORD '[hidden]'" in err and "near '[hidden]'" in err + + def test_interrupt_says_the_work_continues(capsys): _report_interrupt("dev", _current("3f9c2a1b backfill")) err = capsys.readouterr().err