Skip to content

Support per-authentication-method GRANTS clause in CREATE USER and ALTER USER - #110144

Merged
alexey-milovidov merged 102 commits into
masterfrom
credential-grants
Aug 26, 2026
Merged

alexey-milovidov merged 102 commits into
masterfrom
credential-grants

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 12, 2026 •

Copy link
Copy Markdown
Member

Closes: #109117

Implements per-authentication-method grant limits, the first part of the linked issue:

ALTER USER vasya
ADD IDENTIFIED WITH password BY 'WYmdFyas8PftrHbHQQo8'
VALID UNTIL '2026-12-31'
GRANTS (SELECT ON db.table)

When a user logs in with such a method, the access rights of the session are the intersection of the user's access rights (including granted roles) with the listed elements. The clause never adds rights: a listed privilege that is not granted to the user stays unavailable. This provides a way to create tokens for applications: an additional credential with an expiration date and a limited set of grants, which is tied to the user — it is displayed in query_log and processlist as the user, stops working if the user is deleted, and is narrowed when the user loses grants.

Details:

  • The clause is parsed after the per-method VALID UNTIL, works with CREATE USER, ALTER USER [ADD] IDENTIFIED, and NOT IDENTIFIED, is shown by SHOW CREATE USER, and persists through the SQL serialization of access entities (and therefore backups). Elements without a database name are bound to the current database when the query is interpreted.
  • The intersection erases all grant options (the clause cannot express them), so such sessions cannot GRANT anything. Role administration is denied entirely (fail-close), including per-role admin option. EXECUTE AS, ALTER USER, CREATE USER and similar escapes require the corresponding rights to be listed explicitly and granted to the user.
  • Reattaching to a named session (session_id) with a different credential re-applies the limit of the credential used by the new connection, so a limited credential cannot pick up the full rights of a session created by an unrestricted one.
  • The limit is captured at login: ALTER USER affects new sessions, not established ones (same as VALID UNTIL).
  • A new auth_grants column in system.users exposes the limit of each authentication method.
  • ContextData's copy constructor now preserves external_roles and the new field: previously a recalculation of access rights on a copied context silently dropped external roles; for the new field that would mean silently widening the rights.
  • EXECUTE AS <user> <statement> now keeps the current database of the caller's session. Context::setUser sets the current database from the target user's DEFAULT DATABASE, so the wrapped statement used to be re-scoped and an unqualified table name resolved in a different database; the session form (EXECUTE AS <user> without a statement) already preserved it. Test 04907_execute_as_preserves_current_database covers both forms.

Known limitations (consistent with VALID UNTIL and external roles): the limit is not propagated to other nodes of a cluster in distributed queries or ON CLUSTER DDL (the query is checked on the initiator), the clause is not available in users.xml, and the query result cache stays shared by all authentication methods of a user (it isolates entries by user and roles, and a cache hit is not re-checked against the clause). The CREATE TOKEN syntactic sugar and the separate grant for self-service ADD IDENTIFIED mentioned in the issue are left for a follow-up.

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Authentication methods in CREATE USER and ALTER USER ... ADD IDENTIFIED support a GRANTS (SELECT ON db.table, ...) clause which limits the access rights of sessions authenticated with that method to the intersection with the listed grants. This allows using additional credentials as tokens for applications: ALTER USER vasya ADD IDENTIFIED WITH password BY '...' VALID UNTIL '2026-12-31' GRANTS (SELECT ON db.table). Closes #109117.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Workflow [PR]
Sync PR [sync-upstream/pr/110144]

…TER USER

Implements a GRANTS clause for authentication methods:

    ALTER USER vasya
    ADD IDENTIFIED WITH password BY 'WYmdFyas8PftrHbHQQo8'
    VALID UNTIL '2026-12-31'
    GRANTS (SELECT ON db.table)

When a user logs in with such a method, the access rights of the session
are the intersection of the user's access rights (including granted roles)
with the elements of the clause. The clause never adds rights. The
intersection also erases all grant options, and such sessions cannot
administer roles (fail-close), create users, or alter themselves unless
those rights are explicitly listed and granted.

This provides a way to create tokens for applications: an additional
credential with an expiration date and a limited set of grants, which is
tied to the user - displayed in query_log and processlist as the user,
revoked if the user is deleted, and narrowed when the user loses grants.

The elements without a database name are bound to the current database
when the query is interpreted. The limit is captured at login: ALTER USER
affects new sessions, not established ones. Reattaching to a named session
with a different credential re-applies the limit of that credential.

Also adds the auth_grants column to system.users and fixes ContextData's
copy constructor to preserve external_roles and the new field on context
copies (otherwise a recalculation of access rights on a copied context
would drop them).

Closes: #109117

Co-Authored-By: Claude Fable 5 <[email protected]>
@mintlify

mintlify Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Jul 12, 2026, 5:36 AM

@clickhouse-gh

clickhouse-gh Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e1fd095]

Summary: ✅


AI Review

Summary

This PR adds per-authentication-method GRANTS limits for CREATE USER / ALTER USER and, in the current tree, most of the earlier correctness holes are fixed: ambiguous credentials are handled fail-close, deferred execution replays the credential identity, ON CLUSTER binding is covered, EXECUTE AS preserves the limit the PR now documents, and role-administration gaps are closed. One blocker still remains, though: the query-result cache is again shared only by user_id and current roles, so a limited credential can read cached results produced by a broader credential of the same user.

Findings

❌ Blockers

  • [src/Interpreters/executeQuery.cpp:3006, src/Planner/Planner.cpp:2505, src/Interpreters/Cache/QueryResultCache.cpp:841-843] [dismissed by author -- https://github.com/Support per-authentication-method GRANTS clause in CREATE USER and ALTER USER #110144#discussion_r3753704719] The auth-method GRANTS clause is supposed to be a per-session access ceiling, but cached reads happen before interpreter construction and QueryResultCacheReader only checks user_id plus current roles. A full credential can populate the cache for SELECT * FROM db.secret, and then a token for the same user whose GRANTS omit SELECT ON db.secret can receive the cached rows with no access check at all. The warning now embedded in the docs (src/Parsers/Access/ParserCreateUserQuery.cpp:1100-1101) acknowledges the bypass, but it does not make the token semantics safe.
    Suggested fix: restore the earlier fail-close behavior for sessions limited by auth-method GRANTS, or make cache accessibility depend on the effective credential limit and invalidate / bypass cached reads when that limit would no longer authorize the query.
Final Verdict

❌ Blocker remains. I would not approve this as a secure token-style feature while query-cache hits can bypass the per-method GRANTS restriction.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.30% +0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.40% +0.10%

Changed lines: Changed C/C++ lines covered: 719/756 (95.11%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 12, 2026
Comment thread src/Access/Common/AccessRightsElement.h Resolved
Comment thread src/Access/AuthenticationData.cpp Resolved
Comment thread src/Access/AuthenticationData.cpp Resolved
Comment thread src/Access/ContextAccess.cpp Resolved
alexey-milovidov and others added 5 commits July 12, 2026 06:42
`AccessRightsElement::toTuple` omitted `filter`, so two grants differing
only by their source filter (e.g. `READ ON S3('a')` vs `READ ON S3('b')`)
compared equal via `operator==` and the new `operator<`. For the per-method
`GRANTS` clause this made `ALTER USER ... GRANTS (READ ON S3('a'))` ->
`...('b')` a silent no-op in `MemoryAccessStorage::updateNoLock` /
`DiskAccessStorage::updateNoLock` (through `AuthenticationData::operator==`),
and let `ContextAccessParams` reuse the wrong `ContextAccess` cache entry for
two tokens on the same user. Include `filter` in the comparison key.

Addresses a finding from the AI code review of #110144.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`AccessRightsElements::empty` is semantic: it returns `true` when the elements
grant no access, so a `GRANTS (USAGE ON *.*)` clause (a deny-everything token)
was treated as if no clause were written. The credential then silently received
the full user rights, and `SHOW CREATE USER` and `system.users.auth_grants`
dropped the clause. This is fail-open and contradicts the intent of the feature.

Distinguish "no clause was written" (structurally empty) from "the clause was
written but grants nothing" (semantically empty): add
`AccessRightsElements::structurallyEmpty` and use it for clause presence in
`AuthenticationData::fromAST`, `Session::getAuthenticationGrants`,
`StorageSystemUsers`, `ASTAuthenticationData::formatImpl` and the trace string.
`formatGrants` now emits the canonical `USAGE ON *.*` for a present-but-empty
clause so the serialization round-trips instead of producing an unparseable
`GRANTS ()`.

Addresses a finding from the AI code review of #110144.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…essions

The fail-close guard added to `ContextAccess::checkAdminOptionImplHelper` only
covers role administration that goes through `checkAdminOption`.
`InterpreterGrantQuery::checkAdminOptionForExecutingOnCluster` authorizes
`GRANT`/`REVOKE role ... ON CLUSTER` through plain `ROLE_ADMIN` checks
(`checkAccess`/`isGranted`), bypassing that guard. A credential whose `GRANTS`
clause explicitly lists `ROLE_ADMIN` (and `CLUSTER`) could therefore still
administer roles cluster-wide, contradicting the documented contract that such
sessions cannot administer roles at all. Repeat the limited-session guard at the
start of `checkAdminOptionForExecutingOnCluster`.

Addresses a finding from the AI code review of #110144.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…USTER

Bare-table grants in an authentication method (e.g. `GRANTS (SELECT ON t1)`)
are bound to the current database in `AuthenticationData::fromAST`, which runs
on every node. For `CREATE USER ... ON CLUSTER` / `ALTER USER ... ON CLUSTER`
the original AST is shipped to each worker, but `AddDefaultDatabaseVisitor`
does not rewrite `ASTAuthenticationData::grants` (they live outside the AST
children), and a DDL worker's current database is not the initiator's. Each
node could therefore rebind the grant to a different database and persist a
divergent limit.

Bind the authentication-method grants to the initiator's current database in
`InterpreterCreateUserQuery::execute` before `executeDDLQueryOnCluster`, so the
shipped query is already qualified and every node persists the same limit
(`replaceEmptyDatabase` on the workers then becomes a no-op).

Addresses a finding from the AI code review of #110144.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…lause

- `gtest_Parser`: round-trip a `GRANTS (USAGE ON *.*)` clause (must survive as
  a deny-all token, not collapse to an unparseable `GRANTS ()`) and a filtered
  source grant `GRANTS (READ ON S3('...'))` (the filter is preserved).
- `04512_authentication_method_grants`: an explicit no-privileges `GRANTS
  (USAGE ON *.*)` method must keep the clause in `SHOW CREATE USER` and
  `system.users.auth_grants` and must deny access even to tables the user can
  otherwise read (the deny-all token is not silently widened).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Access/ContextAccess.cpp Resolved
The per-authentication-method `GRANTS` clause limits a session's access
rights to the intersection with the listed grants, applied via
`AccessRights::makeIntersection`. That intersection treats a source
filter (the regexp in `READ ON S3('...')`) as an opaque string: it
cannot represent the semantic intersection of two different filters.

As a result, a narrowing token such as user `READ ON S3('s3://bucket/.*')`
limited to `READ ON S3('s3://bucket/private/.*')` would silently collapse
to no `READ` access at all unless the two filter strings were
byte-identical, making tokens unusable for filtered source privileges.

Reject filtered source grants in the clause explicitly at CREATE/ALTER
time (fail-close) with `NOT_IMPLEMENTED` instead of silently granting
nothing. Semantic filter intersection can be added later. Non-filtered
source grants (e.g. `READ ON S3`) and all other grants are unaffected.

Addresses the AI review blocker on
#110144

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/Context.h Resolved
Comment thread src/Access/AuthenticationData.cpp Resolved
alexey-milovidov and others added 3 commits July 12, 2026 09:41
…nd-trip test

The unit test `ParserCreateUserQuery/ParserTest.parseQuery/20` (a round trip of
`CREATE USER ... GRANTS (READ ON S3('s3://foo/.*'))`) failed in the `Unit tests`
checks (asan_ubsan, tsan, msan).

`AccessRightsElement::formatONClause` only emits a source filter when
`enable_read_write_grants` is on (`access_control_improvements.enable_read_write_grants`,
`false` by default). The parser gtest cannot set that server setting, and the global
`AccessControl` in the `unit_tests_dbms` binary keeps the default, so the filter is
stripped on format and `READ ON S3('s3://foo/.*')` round-trips to `READ ON S3` — the
expected output was unreachable and depended on global test state.

The test is also inconsistent with the rest of the change: filtered source grants in the
GRANTS clause are rejected at CREATE/ALTER, so such a grant can never be stored. Remove
the fragile case; the rejection is covered by `04512_authentication_method_grants`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110144&sha=b5ea5cd17d90ea745e610ed1ed98c2064dbc1c58&name_0=PR&name_1=Unit%20tests%20%28asan_ubsan%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The rejection of filtered source grants (e.g. `READ ON S3('s3://bucket/private/.*')`)
in the GRANTS clause sat inside the `if (validate)` block of `AuthenticationData::fromAST`.
Since `validate` is `!query.attach`, the check was skipped on every `ATTACH USER` path
(both `InterpreterCreateUserQuery::execute` and `updateUserFromQuery` call
`fromAST(..., !query.attach)`), so `ATTACH USER ... GRANTS (READ ON S3('...'))` — used by
access-storage restore and DDL replication — became a bypass: the filtered grant was
stored and the session limit later went through the same `AccessRights::makeIntersection`
that treats a source filter as an opaque string.

Move the filtered-source rejection out of `if (validate)` so it runs regardless of
`query.attach`. Unlike the generic `AccessRights{grants}` validation (which stays under
`if (validate)` because it is compatibility-sensitive for entities loaded from storage),
this check is safe to run unconditionally: the GRANTS clause is a new feature, so no older
server could have stored a filtered grant that we would now have to accept.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…executors

`authentication_grants` (the GRANTS clause of the authentication method the session logged
in with) is part of the security identity, but deferred executors that re-create a context
for the same session rebuilt it with a plain `setUser` / `setCurrentRoles`, which resets
`authentication_grants` to null. The deferred work then re-ran access checks under the full
user instead of the token intersection, so a limited credential regained full rights:

- `StorageQueryRunner::makeJobContext` in the `INVOKER` case: `write()` recorded only the
  user id and roles, and `makeJobContext()` reset the grant limit before `executeQuery`.
- `AsynchronousInsertQueue::processData`: the async-insert flush restored only the user id
  and roles on the flush context.

Add `Context::getAuthenticationGrants` and replay the limit in both paths (a null limit,
the common unrestricted case, is a no-op). The `DEFINER`/`NONE` `QueryRunner` cases keep a
null limit on purpose, as they run as a different (or no) principal.

For the async-insert queue the limit is also folded into the batching key: the queue is
indexed by `hash` alone, so `authentication_grants` is hashed (by its textual form, when
non-null) so that inserts made under different credential limits are never coalesced into
one flush and replayed under the wrong rights. `InsertQuery::operator==` compares the limit
by content, consistently with the hash. A null limit contributes nothing to the hash, so
existing (unrestricted) keys are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/Session.cpp Resolved
alexey-milovidov and others added 2 commits July 12, 2026 11:11
…ause

The `GRANTS` clause of an authentication method (`CREATE`/`ALTER USER ...
IDENTIFIED WITH ... GRANTS (...)`) narrows a session's access rights to the
intersection with the listed grants, so it is part of the effective privilege
identity. However, `QueryResultCacheReader` isolated cache entries only by
`user_id` and current roles. The same user could populate the cache under the
full credential and then, reconnecting with a more restrictive token, be served
the cached rows without any access check, because a cache hit returns the stored
chunks without building an interpreter (so `ContextAccess` never gets a chance to
deny the restricted token).

Add the serialized `GRANTS` clause to `QueryResultCache::Key` and require it to
match on read, including for shared entries (sharing is meant to cross the
user/roles boundary, not to bypass a token's access limit). Sessions without a
`GRANTS` clause keep an empty value, so the behavior of all existing cache paths
is unchanged. The clause is threaded through both the top-level (`executeQuery`)
and the subquery (`Planner`) cache read/write paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Extends `04512_authentication_method_grants`: the full credential populates the
query cache for a `SELECT` on `t2`, then the token whose `GRANTS` clause omits
`SELECT ON t2` must get a cache miss and be denied, instead of being served the
cached rows produced under the broader credential.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 12, 2026 12:04
The per-authentication-method `GRANTS (...)` clause was rendered through
`AccessRightsElements::formatElementsWithoutOptions`, the backward-compatible
formatter shared with regular `SHOW GRANTS`. That formatter applies two rewrites
that widen a grant for the benefit of older replicas:

- `formatONClause` collapses a precise `USER_NAME` scope to `*.*` when
  `access_control_improvements.enable_user_name_access_type = 0`;
- `makeBackwardCompatible` folds `READ`/`WRITE` sources into the full `SOURCES`
  access type when `enable_read_write_grants = 0`.

Because `AuthenticationData::toAST` feeds both `SHOW CREATE USER` and
`AccessEntityIO::serializeAccessEntity`, a narrow token such as
`GRANTS (ALTER USER ON alice)` round-tripped as `GRANTS (ALTER USER ON *.*)`
after backup, restart, or `ATTACH USER`, and a `GRANTS (READ ON S3)` token
silently gained write access. This broadens a fail-close credential limit,
violating the feature contract. The rewrites also bring no compatibility benefit
here: older replicas do not understand the `GRANTS` clause at all.

Add a `precise` mode to `formatONClause` and `formatElementsWithoutOptions` that
bypasses both rewrites, and render auth-method grants with it in both
`ASTAuthenticationData::formatImpl` (`SHOW CREATE USER` and on-disk
serialization) and `system.users.auth_grants`. The regular `SHOW GRANTS` /
`GRANT` path keeps its backward-compatible behavior (`precise` defaults to
false). The parser does not depend on `enable_user_name_access_type`, so the
precise output round-trips correctly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Stateless test `04512`: with the default `enable_read_write_grants = 0`, a plain
`GRANT READ ON S3` is dumped as the full `S3` source access, but an auth-method
token limited to `READ ON S3` must keep its exact, read-only scope in
`SHOW CREATE USER` and `system.users.auth_grants`.

Integration test `test_enable_user_name_access_type`: with
`enable_user_name_access_type = 0`, a plain `GRANT ALTER USER ON alice` is dumped
as `ALTER USER ON *.*`, but a token limited to `GRANTS (ALTER USER ON alice)`
must keep its precise scope, including across a restart (the `ATTACH USER`
round-trip through the on-disk serialization).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Storages/StorageQueryRunner.cpp Resolved
alexey-milovidov and others added 2 commits July 12, 2026 13:19
The deferred executors that re-create a context for the originating
session (the asynchronous insert flush and the `QueryRunner` invoker)
were fixed earlier to replay the credential grant limit, but they still
rebuilt the principal from `user_id` plus the effective current roles
only. `Context::getCurrentRoles` returns the session's *effective*
current roles, which already include the external (pushed) roles received
over the interserver protocol, and `setCurrentRoles` revalidates every
role against the user's locally granted roles. A role that exists only as
an external role is therefore rejected with `SET_NON_GRANTED_ROLE` (or
silently dropped), so an async insert or an `SQL SECURITY INVOKER`
`QueryRunner` job accepted under a pushed-role session could fail or run
under a different privilege set when the deferred context is rebuilt.

Add `Context::getExternalRoles`, carry the external roles alongside the
credential grant limit in `AsynchronousInsertQueue::InsertQuery` and
`QueryRunnerJobOrigin`, and replay the whole identity in one call via
`setUser(user_id, external_roles, authentication_grants)`. The effective
current roles are then re-applied without the grant check: the external
roles come from `setUser`, and the locally granted current roles are
kept, so the replayed context reproduces the originating role set instead
of failing revalidation. The common (no external roles) case is
unchanged, because the effective current roles equal the locally granted
current roles there.

Follow-up to the AI review of
#110144

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add a deterministic unit test at the `Context` level that reproduces the
exact mechanism the deferred executors rely on: an external (pushed) role
that is not locally granted to the user appears in the session's
effective current roles, the old replay (rebuild from `user_id` plus
those effective roles, re-applied with the grant check) throws
`SET_NON_GRANTED_ROLE`, and the new replay (external roles carried through
`setUser`, effective roles re-applied without the grant check) succeeds
and keeps the external role.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits July 12, 2026 14:35
…ise credential serialization

The per-authentication-method `GRANTS` clause is part of a session's
privilege identity, so it is folded into the asynchronous-insert queue key
(`AsynchronousInsertQueue::InsertQuery`) and the query-result-cache key
(`QueryResultCache::Key`). Both derived that identity via
`AccessRightsElements::toString`, which applies the backward-compatibility
widening that the rest of this feature had to disable for auth-method grants:
under the default `enable_read_write_grants = 0` it drops the source filter and
folds `READ`/`WRITE` sources, and under `enable_user_name_access_type = 0` it
collapses a `USER_NAME`-scoped grant to `*.*`.

As a result two distinct credential limits could share one async-insert flush
bucket or one cache entry, letting a narrower token be replayed under, or read
rows produced by, a broader one.

Add `AccessRightsElements::toStringPrecise` (the same precise serialization used
by `SHOW CREATE USER` and `system.users.auth_grants`) and use it for both keys
so distinct credential limits are never conflated.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…he precise serialization

Add regressions covering the credential-identity serialization used by the
async-insert queue and query-result-cache keys:

- `AccessRightsElementsSerialization.PreciseAvoidsBackwardCompatibleWidening`:
  the backward-compatibility widening collapses `READ ON FILE` and
  `WRITE ON FILE` into one string while `AccessRightsElements::toStringPrecise`
  keeps them distinct.
- `AsyncInsertKey.AuthenticationGrantsUsePreciseSerialization`: two credentials
  differing only by a source filter (which the widening `toString` drops under
  the default `enable_read_write_grants = 0`) never coalesce into one flush; the
  source read/write limits stay distinct too.
- `QueryResultCacheGrants.KeyUsesPreciseAuthGrantSerialization`: two such
  credentials get distinct `QueryResultCache::Key::authentication_grants`, so the
  narrower token cannot read the broader one's cached rows; a session with no
  clause keeps an empty, unchanged identity.

All three assert the widened form collides (proving the hazard) while the precise
form the keys now use keeps the credentials apart. Verified locally
(`unit_tests_dbms`, 6/6 pass).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Interpreters/executeQuery.cpp Resolved
Comment thread src/Planner/Planner.cpp Resolved
…omASTImpl`

The merge with `master` combined two changes to `AuthenticationData::fromAST`: this
branch split its body out into `fromASTImpl` so the `GRANTS` validation wraps it, and
`master` added the `now` parameter that resolves a `VALID FOR` interval against a single
reference time. The parameter stayed on `fromAST` while its only use moved into
`fromASTImpl`, which does not compile.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all the code. LGTM.

@alexey-milovidov alexey-milovidov self-assigned this Aug 23, 2026
# Conflicts:
#	docs/reference/statements/alter/user.mdx
…ruth

Master moved the `CREATE USER` and `ALTER USER` pages into the parser
registration in `src/Parsers/Access/ParserCreateUserQuery.cpp`, so the
`.mdx` pages are now generated between `AUTOGENERATED_START` and
`AUTOGENERATED_END` markers, and direct edits inside those regions are
rejected by the docs check. Move the `GRANTS` clause sections and the
syntax additions from the generated pages into the `description` and
`syntax` fields of the two statements, and revert the generated pages
(including `system.users`, whose `auth_grants` description already lives
in `StorageSystemUsers.cpp`) to their generated content.
…semantics

Review feedback on `InterpreterExecuteAsQuery.cpp`: the impersonated
context is `target_rights ∩ authentication_grants` and does not intersect
with the rights of the user who logged in.

That is the semantics of impersonation: `EXECUTE AS` switches the
principal, so the statement runs with the target's rights, which is the
point of the `IMPERSONATE` privilege. It cannot widen a limited
credential relative to its user, because impersonating requires
`IMPERSONATE ON target` to be both granted to the user and listed in the
authentication method, and the same user's unlimited credential reaches
exactly the same data. The `GRANTS` limit stays a ceiling over the
impersonated principal - it is never shed.

Spell that out in the `GRANTS` clause documentation, which previously
only described the non-impersonating case, and add the symmetric
regression the reviewer asked for: the target holds a privilege listed by
the token but never granted to the user directly. The new test pins that
the token behaves exactly like the user's unlimited credential, that a
privilege of the target which the method does not list stays denied, and
that a method not listing `IMPERSONATE` cannot impersonate at all.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Pass update on e1fd095c8d79:

  • The pull request was CONFLICTING. Merged origin/master (0f7cac9ea103); the only conflict was in docs/reference/statements/alter/user.mdx, where master moved the SQL statement pages into the parser registrations (Docs: Add system.statements with embedded statement docs #115341 / 9253de56a0fc) and wrapped the whole page in AUTOGENERATED_START / AUTOGENERATED_END.
  • Because of that move, this branch's documentation now lived inside a generated region, which the docs check rejects. Moved the GRANTS clause sections and the syntax additions of CREATE USER and ALTER USER into the description and syntax fields in src/Parsers/Access/ParserCreateUserQuery.cpp (the source of truth) and reverted the generated pages, including docs/reference/system-tables/users.mdx — the auth_grants description already lives in StorageSystemUsers.cpp.
  • AI review blocker on InterpreterExecuteAsQuery.cpp (the impersonated context does not intersect with the login user's own rights): answered in the thread and addressed. EXECUTE AS switches the principal, so the statement runs with the target's rights - that is what the IMPERSONATE privilege is for - and impersonating requires IMPERSONATE ON target to be both granted to the user and listed in the method, so a limited credential can never reach further than the same user's unlimited credential. The GRANTS limit is still a ceiling over the impersonated principal. The documentation now says this explicitly, and the symmetric regression the review asked for was added as 05044_authentication_method_grants_execute_as_source_rights.
  • The query-result-cache finding stays as previously dismissed by the author (the cache is shared per user by design; the limitation is documented in the GRANTS clause warning).
  • The only red on the previous head was Stress test (amd_msan), Cannot start clickhouse-server caused by 05024_keeper_map_parenthesized_metadata leaving an unparsable KeeperMap metadata node. It is unrelated (it fired on 19 different pull requests and on master over the last five days) and its fix, Do not let an unparsable KeeperMap metadata node stop the server from starting #115941, merged on 2026-08-24 and is now pulled into this branch by the master merge.
  • Built incrementally (0 warnings, 0 errors) and ran locally against a server built from this branch: 05044_authentication_method_grants_execute_as_source_rights, 04816_authentication_method_grants_execute_as, 04512_authentication_method_grants, 04907_execute_as_preserves_current_database, 04926_system_statements, 04927_system_documentation_statements, 02117_show_create_table_system — all pass.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 26, 2026
Merged via the queue into master with commit 66719fa Aug 26, 2026
178 checks passed
@alexey-milovidov
alexey-milovidov deleted the credential-grants branch August 26, 2026 06:22
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 26, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 6, 2026
Implements the follow-up part of ClickHouse#109117, on top of the per-authentication-method
`GRANTS` clause added in ClickHouse#110144.

`CREATE TOKEN [VALID UNTIL ... | VALID FOR ...] [GRANTS (...)]` makes the server
generate a random secret, add it to the current user as an additional
authentication method and return it as the result of the query. It is a
shorthand for `ALTER USER <current user> ADD IDENTIFIED WITH sha256_password
BY '<random secret>'` with the same clauses.

The secret is 32 alphanumeric characters drawn from `RAND_bytes` with rejection
sampling, and it is hashed with a random salt before it reaches the statement
below, so the plaintext never enters an AST and the password complexity rules -
which constrain passwords chosen by humans - do not get a say over a
server-generated secret.

The new `CREATE TOKEN` privilege authorizes the statement, and the equivalent
`ALTER USER <current user> ADD IDENTIFIED ...`, without authorizing anything
else about the account: every other clause of `ALTER USER` still requires
`ALTER USER`. It is separate from `ALTER USER` because it lets a user lower the
security level of its own account.

A session whose access rights are limited by the `GRANTS` clause of an
authentication method can no longer add an authentication method to an existing
user at all (fail-close, as with role administration): a method's `GRANTS` is
intersected at login with the *user's* full access rights, not with the limit
of the session which created the method, so such a session could otherwise
issue itself a token wider than itself.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 25, 2026
Since ClickHouse#110867 a remote node of a secret interserver query enables the initiator's current roles only as external roles and clears the user's default roles. The `ContextData` copy constructor did not copy `external_roles`, so any copied context that recalculated access (for example, a view with an access-related setting in its `SETTINGS` clause) lost all roles and a user whose grants come from roles got `ACCESS_DENIED` on the remote node.

This is the relevant part of ClickHouse#110144 (master): copy `external_roles` and make `setExternalRolesWithLock` replace the list instead of appending, so that `setUser` on a copied context (e.g. `EXECUTE AS`) does not inherit the pushed roles.
PedroTadim added a commit that referenced this pull request Oct 21, 2026
The expired-method assertions need the fail-close for ambiguous credentials of #110144, which 26.3 does not have:
here a password accepted by any method logs in, on the native protocol too. Keep the part this backport changes:
a user with `double_sha1_password` and a `scram_sha256_password` or `bcrypt_password` method logs in over MySQL
through the `sha256_password` plugin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 21, 2026
The expired-method assertions need the fail-close for ambiguous credentials of #110144, which 26.7 does not have:
here a password accepted by any method logs in, on the native protocol too. Keep the part this backport changes:
a user with `double_sha1_password` and a `scram_sha256_password` or `bcrypt_password` method logs in over MySQL
through the `sha256_password` plugin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
PedroTadim added a commit that referenced this pull request Oct 21, 2026
The expired-method assertions need the fail-close for ambiguous credentials of #110144, which 26.8 does not have:
here a password accepted by any method logs in, on the native protocol too. Keep the part this backport changes:
a user with `double_sha1_password` and a `scram_sha256_password` or `bcrypt_password` method logs in over MySQL
through the `sha256_password` plugin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-autogenerated-docs PR that regenerates docs artifacts from source; exempt from the autogenerated-region edit guard pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Additional user credentials with limited grants

3 participants