Repository navigation
Add an opt-in access control improvement so that readonly restricts SET ROLE - #118021
alexey-milovidov merged 6 commits into
Conversation
…ET ROLE `readonly > 0` refuses ordinary setting changes but `SET ROLE` succeeds, so a caller that hands out a deliberately confined session (gateway, BI proxy, HTTP `GET`, which implies `readonly = 2`) cannot rely on the session's role set staying put: the client can run `SET ROLE NONE`, `SET ROLE <other granted role>` or `SET ROLE DEFAULT`. Root cause: `InterpreterSetRoleQuery::setRole` performs no access check at all. The readonly gate lives in `ContextAccess::checkAccessImplHelper` and only fires when the query requests a bit in `not_readonly_flags`; `SET ROLE` requests no access flags, so it never reaches that gate. Ordinary `SET` is refused on a different path, `SettingsConstraints::getChecker`, which is why the two diverge. `SET ROLE` is the only identity-changing statement that is not refused under readonly: `SET DEFAULT ROLE` checks `ALTER_USER` and `EXECUTE AS` checks `IMPERSONATE`, both of which sit under `ACCESS_MANAGEMENT`, which is inside `not_readonly_flags` (measured: both return code 164 under `--readonly 1` with the required grant held). The escape is bounded by the existing grant set, not an escalation beyond it (`SET ROLE <non-granted>` still returns code 512), and `readonly` is not cleared afterwards. The consequence is that a restrictive row policy attached to the role being left is dropped with it. Measured: with SELECT granted via `other_role` and a restrictive policy `USING x = 1` on `ro_role`, the default role returns `[1]`, and after `SET ROLE other_role` under `readonly = 1` the same query returns `[1,2,3]`. The check goes in the interpreter that performs none, next to where its two siblings do theirs, behind a new `access_control_improvements` boolean `readonly_restricts_set_role` that defaults to `false`, so no existing deployment changes behaviour on upgrade. `readonly` is read from the query context because the reported repro is the client's `--readonly 1` flag, which raises it there only; a query context inherits session settings, so a mid-session `SET readonly = 1` is covered by the same read. The check precedes the `Kind` branch, so it covers `SET ROLE <role>`, `SET ROLE NONE` and `SET ROLE DEFAULT`, and it is placed after `getSessionContext` so a `SET ROLE` over HTTP without a session keeps returning `THERE_IS_NO_SESSION`. Four statements in the tree asserted unconditionally that `readonly` does not block `SET ROLE`. One of them is the generator source of the published `CREATE HANDLER` page, so they are corrected here. The SQL-defined-handler fence itself is deliberately unchanged: `ASTSetRoleQuery::getQueryKind` and `ASTSetQuery::getQueryKind` both return `QueryKind::Set`, so at that layer `SET ROLE` is not distinguishable from plain `SET`, and the check runs at CREATE/ALTER time with no live `readonly` value. Related: ClickHouse#115691
The suite passed `readonly` only as a per-query setting, so the session half of
the promise ("a session or query whose `readonly` setting is not zero") was
measured by hand but not guarded. If the interpreter later read a context that
does not inherit session settings, every test would have stayed green while the
headline property was gone. No case asserted that a refusal leaves the active
roles alone either, so a variant that threw after `Context::setCurrentRoles`
would also have passed.
Two cases are added, over an HTTP `session_id` because that is the only way to
read the roles back after a refusal: a single `clickhouse-client` invocation
aborts at the first error and separate invocations do not share a session. Both
requests are POST, which contributes no `readonly` of its own, leaving the
session's own value as the only source. Reverting the interpreter check makes
the new refusal case fail with no error at all; moving the `throw` to after the
role assignment leaves the three original refusal cases green and is caught only
by the roles-unchanged assertion.
`queryKindRequiresMutatingMethod` held a fifth unconditional "readonly does not
block SET ROLE" statement, and is the site a reader consults first because its
predicate is the `QueryKind::Set` arm. The `queryKindHasSideEffectsUnderReadonly`
header said both "which `readonly` blocks only when the setting is enabled" and
"none of which `readonly` blocks"; the latter clause now reads "by default".
Neither predicate changes behaviour: `QueryKind::Set` still cannot distinguish
`SET ROLE` from plain `SET`, so the handler fence stays setting-independent.
The refusal message said "This is enabled by ...", which reads as though
`readonly` mode were what the setting enables.
The `CREATE HANDLER` refusal for queries with session side effects said the read-only mode of safe HTTP methods "does not prevent these side effects". With `readonly_restricts_set_role` enabled that is false for a `SET ROLE` handler, since `InterpreterSetRoleQuery` refuses it. Reword to "cannot be relied on to prevent these side effects", matching the wording already used elsewhere in the file, so the sentence holds whether the setting is on or off. The guard itself is unchanged and stays independent of the setting: it runs at `CREATE`/`ALTER` time, where no live `readonly` value exists. In `test_readonly_restricts_set_role`, `http_query_and_get_answer_with_error` returns `None` for the error on success, so `assert "READONLY" in error` raised `TypeError` instead of failing as an assertion when the interpreter check regressed. Guard it with `assert error and ...`. Correction to the earlier message in this branch: `readonly > 0` refusing ordinary setting changes holds for `readonly = 1` only. `readonly = 2` permits changing settings other than `readonly` itself (`SettingsConstraints.cpp`). Neither mode refuses `SET ROLE`.
Internal second-model review (click to expand)Three rounds of pre-publication review by an independent model, plus my own cold read of the Three deliberate omissions, listed because each is a judgement a maintainer may want to overturn:
Session id: cron:clickhouse-review-slot-9:20260904-082300 |
|
Workflow [PR], commit [da1549e] Summary: ✅
AI ReviewSummaryThis PR adds the opt-in Final Verdict
|
|
cc @pufit, could you say whether this should land at all? |
`docs/concepts/features/interfaces/http.mdx` calls the `role` query parameter "the equivalent of executing `SET ROLE` before the statement". With `access_control_improvements.readonly_restricts_set_role` enabled that equivalence no longer holds, so the page and the setting's own description now say which carrier the setting covers. The parameter itself stays ungated here, and not because its per-request scope protects anything. Measured on master, whose `HTTPHandler.cpp` role handling is byte-identical to this branch: a user with a restrictive row policy on its default role and `readonly = 1 CONST` in its profile reads `[1]` without the parameter and `[1,2,3]` with `?role=`, so one request is enough to leave an administrator's confinement. On that same URL `readonly=0` and `max_threads=2` are refused with `Code: 164 READONLY` while `role=` is accepted. Gating it is a separate decision rather than a copy of the same check. The parameter is applied in `HTTPHandler` before `setReadOnlyIfHTTPMethodIdempotent` and before the URL settings are checked, so a `readonly` read at that point sees `0` both for a `GET` request that then runs at `readonly = 2` and for `?readonly=1&role=`, and the ordering there carries an explicit rationale in the code: the roles decide which settings profile and constraints apply. `PrometheusRequestHandler` applies the two in the opposite order, so the same request shape would gate differently on the two interfaces.
`ClickHouseCluster` copies `programs/server/config.xml` into every instance, and this branch adds `readonly_restricts_set_role` to that file, so `node_off` was running with an explicit `false` rather than with the element absent. The `getBool` fallback that an upgraded deployment relies on was therefore not exercised: had it been written `true`, every off-arm assertion would still have passed. `node_off` now removes the element. The new HTTP case pins the scope the two documentation pages state. A restriction moved into `Context::setCurrentRoles` would keep every statement test green while making both pages false; this case fails in that situation. Its last two requests are the control that the parameter, not the session, is what changed the roles.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units85 translation units recompiled, 569 s compile time in total, 85 of them have a recent master baseline. |
|
@groenai from the pr draft
This seems reasonable at face value. The idea is to stop the session swapping roles. Discuss how the This restriction is intended to stop a readonly=1 or readonly=2 user escaping their role to a more-privileged role and (once #115551 is fixed) to stop them escaping settings profiles. |
|
Measured on master 1. How
|
| request | readonly in effect | currentRoles() |
rows |
|---|---|---|---|
POST ?user=u2 |
0 | ['r_locked'] |
[1] |
POST ?user=u2&readonly=1&role=r_free |
1 | ['r_free'] |
[1,2,3] |
POST ?user=u&role=r_free |
1 | ['r_free'] |
[1,2,3] |
POST ?user=u&readonly=0 |
Code: 164 READONLY |
||
POST ?user=u&role=r_ungranted |
Code: 512 SET_NON_GRANTED_ROLE |
The parameter is never an escalation: the role must already be granted. But for the same user, lowering readonly is refused while the role switch is accepted, and it takes effect for a request that then runs at readonly = 1.
2. GET, where the transport applies readonly = 2
All as u2, which has no readonly of its own:
| GET | result |
|---|---|
SELECT getSetting('readonly') |
2 (same request over POST: 0) |
?role=r_free |
readonly 2, ['r_free'], [1,2,3] |
?query=SET ROLE r_free with session_id |
accepted, and the role persists into the next request of that session |
Two things follow. With the flag on, that last line is refused for every user, since the gate reads exactly the value in the first line (InterpreterSetRoleQuery.cpp:44-45); that one is derived from the measured value plus the gate condition, not measured with the flag on. readonly = 2 there is transport-imposed, not admin-imposed, and the same caller can send the same statement over POST at readonly = 0, so nothing was confined but GET-based SET ROLE stops working. The mirror case is the one you quoted: a user whose profile pins readonly = 1 still switches roles per request through the parameter.
One ordering note if the parameter is to be gated: at :462 the only readonly in effect is the profile-imposed one, i.e. exactly the value a caller cannot lift. PrometheusRequestHandler applies the two in the opposite order (:206, then :208-210), so the same one-line check dropped at both call sites would refuse a GET ?role= on the Prometheus endpoint and accept it on /.
3. Least surprise against the confinement goal
readonly reaches a query from three places, and they are not equally binding:
- profile or constraint (
readonly = 1 CONST): admin-imposed, cannot be lifted (?readonly=0refused above). - session state (
SET readonly = 1under asession_id): persists, and a laterSET readonly = 0in that session is refusedCode: 164, so it is sticky. Imposed by whoever composes the URL, which in a middleware deployment is the proxy and not the SQL author. - transport (GET): per request, and the same caller can simply POST.
On that reading the statement is the half worth gating, being the only one of the two that changes state outliving the request, and role= is a URL-authoring capability whose holder is the same party that supplied readonly. The exception worth naming is a proxy that pins readonly=1 and forwards unrecognised client query parameters: there role= is reachable by the confined party, and that is the strongest argument for gating it too.
4. Stateful HTTP sessions
SET ROLE writes to the session context (InterpreterSetRoleQuery.cpp:52-54). The parameter writes to the query context, which is a fresh copy of the session context made per request (Session.cpp:732). Measured in one session that has confined itself with SET readonly = 1:
step in session s2 |
readonly | currentRoles() |
rows |
|---|---|---|---|
after SET readonly = 1 |
1 | ['r_locked'] |
[1] |
same session, &role=r_free |
1 | ['r_free'] |
[1,2,3] |
| next request, no parameter | 1 | ['r_locked'] |
[1] |
same session, SET ROLE r_free (accepted on master) |
1 | ['r_free'] |
[1,2,3] |
So the statement is the persistent escape and the flag closes it, including inside a session already sitting at readonly = 1; the parameter escapes one request and leaves the session's own roles untouched. Sessions are keyed on (user id, session name) (Session.cpp:55), which matches the measurement: the same session_id sent with a different user neither reads nor changes the first session's roles or readonly. For #115551 the same asymmetry decides it, and in the same direction: a session that switched role keeps the new profile for every later request, while a parameter-switched request gives it up when the request ends.
I have not widened the diff for this. The docs on both carriers were narrowed in 6ca3a05, and whether the parameter should also be gated is the RBAC owner's call, together with the still-open question of whether the statement gate lands at all. If that call is to gate it, I will implement it.
|
@groeneai That was a huge wall of text that didn't say a lot. Succinctly get to the point in natural language. |
|
Short version. The two carriers differ in lifetime, not in power: both are confined to roles the user already holds.
On least surprise the current keying is uneven in both directions. With the flag on, a GET Stateful sessions are where the flag earns its keep. A session can confine itself, since Both calls are the RBAC owner's (@ pufit): whether the statement gate lands at all, and whether |
That's a "don't do that" situation that can be handled with appropriate documentation.
This might be a decent argument for restricting There will be a gap where it is possible to then possible for a Confining Do "you" see strong objections to this? |
|
One objection, yes. All of this is measured on master 26.10.1.1 (618a561). A correction first, and it helps your proposal: the caveat you want to document is not reachable. The objection is about what That Your Both are one-predicate changes and I will push either. Which of them, and whether the statement gate lands at all, is the RBAC owner's call, so I am not changing the diff on my own judgement. |
|
@groeneai I want to fix the ineffectiveness of SET ROLE for applying profile changes in #115551; I don't think the current state should be relied upon for that. I'm hesitant about playing games about enforcement based on where a setting came from (GET vs session/profile). Decent argument re |
|
Agreed on both points, and the first one changes my answer rather than yours. On provenance: dropping that candidate. Keying the gate on where On #115551: you are right that I should not lean on today's behaviour, and once you fix it my "the caveat is unreachable" finding inverts into an argument for keeping the gate at any non-zero value. Profile application deliberately skips constraint checking. The two changes also compose the way step 4 of #115551 wants: a gateway at Both variants remain a one-predicate change and I will push whichever the RBAC owner prefers. The diff stays as it is until then. |
|
📊 Cloud Performance Report ✅ AI verdict: The PR adds the access_control_improvements.readonly_restricts_set_role server setting, which is off by default, and a readonly check that runs only when a SET ROLE statement executes. The rest of the diff is documentation, comments, an error-message rewording for SQL-defined HTTP handlers, and tests, so none of it touches the SELECT execution path the benchmarks use. The only flagged row, clickbench Q28 (+5.4%, 1016 ms to 1071 ms), is already not_sure: the two tests gave mixed signals, CPU time is flat, and the measurements were noisy on both sides. No performance impact can be attributed to this change. clickbenchFlagged queries (1 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
Depending on the outcome of #115695 (comment), this might want to be re-visited in favour of a separate enhancement for session-level control over / irrevoccable application of |
|
Agreed. I'll keep this PR open and unchanged until the direction on #115695 is settled, and if a session-level role lock is chosen there, I'll replace this PR with one for the lock rather than keep both. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the cherry-pick of #118021 to 26.9. The conflict in `InterpreterSetRoleQuery.cpp` comes from #118429, which is not on 26.9 and has no backport label: on master `setRole` also refuses a context without a user, next to the new `readonly` check. Only the `readonly` check is added. The new integration test merges cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #118021 to 26.9: Add an opt-in access control improvement so that readonly restricts SET ROLE
… that readonly restricts SET ROLE
Resolve the cherry-pick of #118021 to 26.8. The conflict in `InterpreterSetRoleQuery.cpp` comes from #118429, which is not on 26.8 and has no backport label: on master `setRole` also refuses a context without a user, next to the new `readonly` check. Only the `readonly` check is added. `ParserCreateHandlerQuery.cpp` has no `getDocumentation` on 26.8, so its documentation change is dropped. The new integration test merges cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve conflicts for the 26.7 backport of #118021: - `InterpreterSetRoleQuery.cpp`: keep only the `readonly` check; the missing-user check comes from #118429, which is not on 26.7. - `SQLDefinedHandlerFromAST.cpp`, `ParserCreateHandlerQuery.cpp`, `04824_handler_safe_method_session_state.sh`: removed, 26.7 has no SQL-defined handlers. Resolution matches the one proposed by @groeneai in #125310 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the cherry-pick of #118021 to 26.3. The conflict in `InterpreterSetRoleQuery.cpp` comes from #118429, which is not on 26.3 and has no backport label: on master `setRole` also refuses a context without a user, next to the new `readonly` check. Only the `readonly` check is added. `docs/concepts/features/interfaces/http.mdx` and the SQL-defined handler files (`SQLDefinedHandlerFromAST.cpp`, `ParserCreateHandlerQuery.cpp`, `04824_handler_safe_method_session_state.sh`) do not exist on 26.3, so their comment and documentation changes are dropped. The server setting row is added to 26.3's `_server_settings_outside_source.md`. The new integration test merges cleanly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cherry pick #118021 to 26.3: Add an opt-in access control improvement so that readonly restricts SET ROLE
… that readonly restricts SET ROLE
Cherry pick #118021 to 26.7: Add an opt-in access control improvement so that readonly restricts SET ROLE
… that readonly restricts SET ROLE
Cherry pick #118021 to 26.8: Add an opt-in access control improvement so that readonly restricts SET ROLE
… that readonly restricts SET ROLE
Backport #118021 to 26.9: Add an opt-in access control improvement so that readonly restricts SET ROLE
Backport #118021 to 26.8: Add an opt-in access control improvement so that readonly restricts SET ROLE
Backport #118021 to 26.7: Add an opt-in access control improvement so that readonly restricts SET ROLE
Backport #118021 to 26.3: Add an opt-in access control improvement so that readonly restricts SET ROLE
Related: #115691
Related: #115697
Related: #115551
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a server setting
access_control_improvements.readonly_restricts_set_role,falseby default. When enabled,SET ROLEis refused with error codeREADONLYin a session or query whosereadonlysetting is not zero. PreviouslySET ROLEwas the only identity-changing statement thatreadonlydid not refuse.Description
@ ringerc asked for a concrete draft as decision-making input: #115691 (comment). @ pufit's ruling on whether to do it is still open, so this is not a merge request. @ PedroTadim confirmed the report, not this shape.
readonlyrefuses ordinary setting changes at1, and onlyreadonlyitself at2; neither refusesSET ROLE:InterpreterSetRoleQuery::setRoleperforms no access check, and the readonly gate inContextAccess::checkAccessImplHelperonly fires for a query requesting anot_readonly_flagsbit, whichSET ROLEnever does.SET DEFAULT ROLEandEXECUTE ASrequestACCESS_MANAGEMENTflags; I measured both at 164.The escape stays inside the granted set (
SET ROLE <non-granted>still returns 512), so it is confinement escape, not escalation. It matters because a restrictive row policy on the role being left is dropped with it: measured, a query returning[1]under the default role returns[1,2,3]afterSET ROLE other_roleunderreadonly = 1.The check goes in that interpreter, behind the new flag, so nothing changes on upgrade; flipping the default is a separate backward-incompatible decision. The integration test covers both flag states. Two SQL-defined-handler files and one test comment are in the diff only because they assert that
readonlycannot blockSET ROLE; the fence itself is unchanged.Not covered: the HTTP
rolequery parameter,clickhouse-localandembedded.xml(not wired, likethrow_on_unmatched_row_policies), and theSET profilehole. Theroleparameter reaches the same escape, measured; the docs now state the setting's scope and a test pins it. This should land before or with a fix for #115551, whose session-start path would reintroduce the bypass.Workflow [PR]
Sync PR [sync-upstream/pr/118021]
Version info
26.10.1.2178-master(included in26.10and later)26.9.18.9,26.8.26.9,26.7.29.14