Skip to content

Add web terminal interface to clickhouse-server - #100277

Merged
alexey-milovidov merged 144 commits into
masterfrom
webterminal
May 15, 2026
Merged

alexey-milovidov merged 144 commits into
masterfrom
webterminal

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Mar 21, 2026 •

Copy link
Copy Markdown
Member

Add a WebSocket-based terminal protocol (webterminal) that runs a pseudoterminal with embedded clickhouse-client functionality, accessible via a browser at /webterminal.

The implementation reuses the same PtyClientDescriptorSet and ClientEmbeddedRunner infrastructure as the SSH protocol, but connects via WebSocket instead of SSH. The user is authenticated through the same Session machinery as the HTTP protocol, but credentials are sent in-band over the established WebSocket connection (in the first JSON message) instead of as part of the upgrade request, so they never appear in URLs, access logs, or browser history.

The HTML page uses xterm.js for terminal emulation and connects to the server via WebSocket, bridging data bidirectionally between the browser and the PTY.

Changelog category (leave one):

  • Experimental Feature

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

Added an experimental web terminal interface at /webterminal that provides an interactive clickhouse-client session in the browser over WebSocket. Disabled by default; enable with the allow_experimental_webterminal server setting.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Navigate to /webterminal on any ClickHouse HTTP port to open an interactive terminal session in the browser. Authenticate with ClickHouse user credentials. The terminal supports the full clickhouse-client experience including syntax highlighting, autocompletion, and multi-line queries.

Companion docs sidebar PR: ClickHouse/clickhouse-docs#6118

Version info

  • Merged into: 26.5.1.684

Add a WebSocket-based terminal protocol (webterminal) that runs
a pseudoterminal with embedded clickhouse-client functionality,
accessible via a browser at /webterminal.

The implementation reuses the same `PtyClientDescriptorSet` and
`ClientEmbeddedRunner` infrastructure as the SSH protocol, but
connects via WebSocket instead of SSH. Authentication works the
same way as in the HTTP protocol (URL params, Basic auth,
X-ClickHouse headers).

The HTML page uses xterm.js for terminal emulation and connects
to the server via WebSocket, bridging data bidirectionally
between the browser and the PTY.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [8ac8ddb]

Summary: ✅


AI Review

Summary

The PR adds an experimental browser webterminal endpoint with a WebSocket-to-PTY bridge, UI integration in /play, settings, and tests. Most protocol/security hardening is solid, but there is one blocker: the HTML response sets anti-framing headers that prevent the terminal from being embedded in /play, which contradicts the feature contract and breaks the new integration path.

Findings

❌ Blockers

  • src/Server/WebTerminalRequestHandler.cpp:341
    The response sets Content-Security-Policy: frame-ancestors 'none' and X-Frame-Options: DENY, which forbids all iframe embedding, including same-origin. /play embeds /webterminal via an iframe, so browsers will block rendering the terminal panel.
    Suggested fix: allow same-origin embedding (frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN) or rework /play to avoid iframe embedding.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Fix framing policy vs /play integration so the embedded terminal actually works while keeping cross-origin framing protection.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label Mar 21, 2026
Comment thread src/Server/HTTPHandlerFactory.cpp Resolved
- Remove the overlay login form; the terminal fills the entire page
- Auto-connect with default credentials (or credentials from URL params)
- On auth failure, prompt for username/password directly in the terminal
- If user was provided in the URL, only prompt for password
- After session ends, prompt for credentials again to reconnect
- Hide the scrollbar while keeping the terminal scrollable

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread programs/server/webterminal.html Resolved
Comment thread programs/server/webterminal.html Resolved
The C++ `#embed` directive includes file contents at compile time,
but the build system does not automatically track these as
dependencies. When an embedded file (e.g., `play.html`) changes,
the .cpp file that embeds it is not recompiled.

Fix this by adding `OBJECT_DEPENDS` properties to all source files
that use `#embed`, covering: HTML pages, JavaScript files, XML
configs, and NLP data files.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits March 21, 2026 14:15
Erase the "Connecting..." line before PTY output starts, so the
terminal content renders from a clean line. Also erase it on
auth failure before showing the error prompt.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits March 21, 2026 14:28
Embed xterm.js 5.5.0, addon-fit 0.10.0, and addon-web-links 0.11.0
(minified JS and CSS) into the server binary, served at /js/*.
This removes the dependency on CDN and makes the web terminal
page fully self-contained, like the dashboard.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/Server/HTTPHandlerFactory.cpp Resolved
When the `query` URL parameter is present (e.g.,
`/webterminal?query=SELECT 1`), paste it into the terminal
after a successful connection, similar to how `play.html`
handles the query parameter.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
ccache's direct mode uses its own source parser to find included
files, but it does not recognize C23 `#embed` directives. This
means changes to files included via `#embed` (HTML pages, JS
libraries, XML configs) do not invalidate the ccache, leading to
stale build artifacts.

Enable depend mode (available since ccache 4.0), which uses the
compiler's dependency file (.d) instead. The compiler correctly
lists `#embed` files in its dependency output.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Handle continuation frames and fragmented messages per RFC 6455
  Section 5.4, with proper reassembly buffer
- Handle interleaved control frames (ping/pong/close) between
  data fragments
- Fix integer overflow in resize message parser by clamping values
  to a maximum of 500
- Combine WebSocket frame header and payload into a single
  sendBytes call to prevent partial frame writes
- Keep socket in blocking mode throughout the I/O loop instead of
  toggling, eliminating exception-safety issues
- Validate Sec-WebSocket-Version: 13 per RFC 6455 and respond
  with the supported version if mismatched
- Check for Upgrade: websocket (case-insensitive) in handleRequest
  before entering the WebSocket path

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Comment thread src/CMakeLists.txt Resolved
alexey-milovidov and others added 5 commits March 21, 2026 15:35
Add a Quake-style drop-down terminal panel to the play.html query
interface:

- Shell icon (>_) in the left sidebar, above the GitHub icon
- Click the icon or press ~ (backtick) to toggle the terminal
- Terminal appears as an iframe occupying the top 40% of the main area
- Bottom border is draggable to resize (same UX as the textarea resizer)
- Dragging below one line height deactivates the terminal
- Authentication parameters (user/password) are passed from the
  play.html inputs to the /webterminal iframe URL
- The ~ key only triggers when not focused on input/textarea elements

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Move the terminal panel out of #main into its own grid row that
spans both the menu and main columns, so it occupies the full
page width like a Quake-style drop-down console.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
When the embedded client exits inside the iframe, webterminal.html
sends a postMessage to the parent window instead of redirecting.
play.html listens for this message and deactivates the terminal
panel. When opened standalone (not in an iframe), the redirect
to the ClickHouse GitHub repo is preserved.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Toggling the terminal (icon click, ~ key, or resize-to-close) now
only hides the panel while keeping the iframe and its WebSocket
session alive. Re-opening shows the same session.

Quitting from the client (exit, Ctrl-D) still fully destroys the
iframe via the postMessage handler.

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
…minal tests

Two reviewer-requested strengthenings of `tests/integration/test_webterminal`:

1. `test_invalid_auth_rejects_session` no longer accepts EOF (`1006` on the
   client side) as success. The handler explicitly sends `1008` on a failed
   `Session::authenticate`, and the test now asserts that exact close code.
   A regression to ungraceful close would have silently passed before.

2. New `test_origin_match_accepted_same_origin` exercises the default-allow
   branch of the `Origin` check: a non-empty `Origin` whose scheme + host
   matches the request's `Host` must reach the `101` upgrade. The existing
   negative tests would still pass against an over-zealous CSWSH check that
   rejects every non-empty origin; this test locks in the positive case.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100277&sha=5e956ab02379b6fca74430a22413b07a95340104&name_0=PR&name_1=libFuzzer%20tests and provide a fix in a separate PR. If the fix is already in progress, link it here.

The select_parser_fuzzer libFuzzer test timed out after 23 seconds on input timeout-56080df9401372c2436939d89f52a25d923ea453 while running deeply recursive parser code (ParserCompoundIdentifier, ParserFunctionName, ParserSubquery, ParserUnionList, ParserExpressionImpl::tryParseOperand). This PR doesn't touch any parser code (only programs/server/*, src/Server/WebTerminal*, src/Server/ClientEmbedded/Pty*, src/Core/ServerSettings.cpp). The same fuzzer timeout reproduces on 24 unrelated PRs on 2026-05-13, confirming it's a master regression. The symptom matches previously closed issue #92282 (select_parser_fuzzer times out when parsing deeply nested parentheses).

@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the 01721_join_implicit_cast_long_oldanalyzer timeout in Stateless tests (amd_msan, WasmEdge, parallel, 1/2) is tracked by the open issue #104874. This is a long-running join test that times out in the WasmEdge variant of the msan build, unrelated to this PR's changes (WebTerminal, PtyClientDescriptorSet, WebSocket). Please investigate and provide a fix in a separate PR. If a fix is already in progress, link it here.

The 03809_time64_not_monotonic timeout in the same shard is already fixed on master by #103718 (marking the test as long); the fix is being picked up by the latest merge from master.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov — addressing all three CI failures on this PR. None are caused by this PR; all are tracked chronic trunk issues:

  1. AggregateFunctionArray: parameters mismatch (AST fuzzer, amd_debug, Client: keep pasted multi-line query under a single prompt #104299 directive) — fix is in PR Fix LOGICAL_ERROR in AggregateFunctionArray for timeSeries*ToGrid family #104769 (groeneai). The wrapper-layer fix forwards nested_->getParameters() to the AggregateFunctionArray base, eliminating the divergence between user-supplied UInt64 and timeSeries* normalized Decimal64 parameters. AI Review: Approve. Awaiting human review from @alexey-milovidov / @vitlibar / @Avogar.

  2. Tests/04221_dictgetordefault_arrayjoin_80703 — agreed, fixed by PR Tag 04221_dictgetordefault_arrayjoin_80703 as no-parallel-replicas #104778 (merged 2026-05-13). Master now picks it up after the merge in fb8187e8c79. No action needed.

  3. select_parser_fuzzer libFuzzer tests timeout — tracked as issue libFuzzer tests are flaky #93438 ("libFuzzer tests are flaky"). Chronic libFuzzer flake hitting 7+ PRs/day on select_parser_fuzzer; the underlying parser path occasionally exceeds the libFuzzer 60s slowest-input budget on adversarial deeply-nested parenthesized inputs. Not caused by this PR. We're tracking via that issue.

  4. 01721_join_implicit_cast_long_oldanalyzer timeout on Stateless tests (amd_msan, WasmEdge, parallel, 1/2) — tracked as issue Flaky test: 01721_join_implicit_cast_long_oldanalyzer #104874 (@Algunenano filed it, asked us to look at it). Chronic MSan+WasmEdge timeout family — runner overhead under MSan + WasmEdge translation slows SYSTEM FLUSH LOGS and other system DDL past the 180s tail of the parallel-mode shard budget. Not caused by this PR; multiple sibling tests in the family (Enable clang-tidy check for uninitialized variables #100399, Add leader election for non-replicated MergeTree on shared storage #101039, ThreadPool: wake most recently idle worker thread (LIFO) when scheduling a job to reduce memory fragmentation #100177, Flaky test: 04039_merge_tree_snapshot_teardown_race #104866). We're tracking.

Both select_parser_fuzzer and 01721_join_implicit_cast_long_oldanalyzer are already in our active monitoring queue. PR #104769 is the only one with a concrete fix in flight.

@Algunenano Algunenano left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Some notes from AI review. I did not check them, but I think it's good input:

  • Most important (Medium): /webterminal registration via addCommonDefaultHandlersFactory ends up registered on the interserver HTTP port as well as the user-facing port, because createInterserverHTTPHandlerFactory (src/Server/HTTPHandlerFactory.cpp:287-296) also calls the common factory. Once allow_experimental_webterminal=true, an interactive PTY shell becomes reachable on the interserver port — a port with a different (HMAC) trust model and typically less-firewalled inside the cluster. Suggested fix: register only in addDefaultHandlersFactory, or skip when building the interserver factory.
  • Other mediums: Origin check is skipped when the Origin header is missing (if (!origin.empty()) guard); no CORS / X-Frame-Options framing on the WebSocket-HTML page.
  • Lows: 16 MiB pre-auth JSON parse per WebSocket connection (DoS amplifier — first-frame cap should be a few KiB since auth JSON is small); brittle Connection: upgrade substring match; ClientEmbedded::run builds CLI flags from an envs map (currently empty for webterminal, but a forward-compat hazard).

…minal frames

Reviewer noted that `readWebSocketFrame` previously treated
`payload_len > MAX_FRAME_SIZE` as an invalid frame (`valid = false`)
without flagging a size error, so the main loop just terminated the
session and the epilogue sent a normal `1000 Session ended` close. A
client sending a single oversized non-fragmented frame would see a
success-looking close instead of the required `1009` size error,
weakening the protocol contract and hiding the path from clients/tests.

Add an explicit `message_too_big` state to `WebSocketFrame`, set it
when the advertised payload length exceeds `MAX_FRAME_SIZE`, and emit
a dedicated `1009 Message too big` close from both the auth path and
the main read loop. The integration test exercises the new contract
by sending only the 14-byte frame header advertising a `17 MiB`
payload and asserting the server closes with code `1009`.
# Conflicts:
#	ci/jobs/scripts/check_style/aspell-ignore/en/aspell-dict.txt
The handler was registered via `addCommonDefaultHandlersFactory`, which
is also called from `createInterserverHTTPHandlerFactory`. Once
`allow_experimental_webterminal=true`, the interactive PTY shell would
become reachable on the interserver HTTP port as well. The interserver
port has a different (HMAC) trust model and is typically less-firewalled
inside the cluster, so this would punch a hole through that boundary.

Move the registration into `addDefaultHandlersFactory` so the route is
only mounted on the user-facing HTTP port.

See: #100277
* Add `Content-Security-Policy: frame-ancestors 'none'` and
  `X-Frame-Options: DENY` headers to the served HTML page so a malicious
  embedding page cannot frame the terminal and trick a logged-in user
  into typing into an invisible PTY.
* Reject a missing `Origin` header on the WebSocket upgrade with `403`
  rather than allowing the connection through. Browsers always send
  `Origin` on a WebSocket upgrade, so an unattributed upgrade is either
  a non-browser client or a forged request — accepting either is too
  risky for an interactive shell.
* Update the integration test helper to default to a same-origin
  `Origin` header (matching browser behaviour) and add an explicit test
  for the missing-`Origin` rejection.

See: #100277
…ction parsing

* Apply a 4 KiB cap on the first (auth) WebSocket frame, separate from
  the 16 MiB post-auth cap. The auth JSON is small and the user/password
  field limits already cap content to ~1.3 KiB, so 4 KiB is comfortably
  above any legitimate first frame and removes the DoS amplifier where
  an unauthenticated peer could force a 16 MiB allocation per connection.
* Parse the `Connection` header as RFC 7230 tokens rather than a
  substring `find("upgrade")`, which would also match future values like
  `upgrade-something`.
* Add integration tests for the pre-auth size cap and for the
  clickjacking response headers on the HTML page.

See: #100277
The map is unused in WebTerminal today, but `ClientEmbedded::run` turns
each entry into a `--key value` CLI flag for the embedded
`clickhouse-client`. Add a comment so a future change that wires
browser-supplied data into this map does not silently introduce
CLI-flag injection.

See: #100277
@alexey-milovidov

Copy link
Copy Markdown
Member Author

@groeneai, the two CI failures on the latest run are both unrelated to this PR:

  1. AST fuzzer (amd_msan) — MemorySanitizer: use-of-uninitialized-value in StringSearcher: The stack trace is fully inside FunctionStartsEndsWith<NameStartsWithCaseInsensitiveUTF8>::executeCaseInsensitive -> DB::impl::StringSearcher<false, false>::StringSearcher, with 'u_seq' reported as the uninitialized stack allocation in src/Common/StringSearcher.h. No webterminal code is on the trace. CIDB shows the broader FunctionStartsEndsWith fuzzer fingerprint is hitting master in the last two days (4 + 2 hits on 2026-05-14 and 2026-05-15). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100277&sha=8129e4e5aceb00b524c6b0332aa2b67c7bd45e02&name_0=PR&name_1=AST%20fuzzer%20%28amd_msan%29

  2. Stress test (amd_debug) — Hung check failed, possible deadlock found: The hung threads are in TCPHandler::runImpl -> executeQueryImpl -> InterpreterSelectQueryAnalyzer, triggered by the 03356_tables_with_binary_identifiers_invalid_utf8.sql test (creating tables with binary identifiers). Not related to webterminal (no TCPHandler or analyzer changes here). CIDB shows the Hung check failed fingerprint failing recurrently on master (7 hits on 2026-05-14 and 5 on 2026-05-13). Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100277&sha=8129e4e5aceb00b524c6b0332aa2b67c7bd45e02&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

Please investigate both and provide fixes in separate PRs. If fixes are already in progress, link them here.

/// invisible terminal. `frame-ancestors 'none'` (CSP) is the modern check
/// honoured by current browsers, and `X-Frame-Options: DENY` is the legacy
/// fallback for older browsers / proxies that ignore CSP.
response.set("Content-Security-Policy", "frame-ancestors 'none'");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

❌ frame-ancestors 'none' + X-Frame-Options: DENY forbids all embedding, including same-origin.

This breaks the new /play integration added in this PR, because /play loads /webterminal in an <iframe> (programs/server/play.html). With these headers the browser will refuse to render the terminal frame, so the terminal button appears but cannot actually embed the terminal.

Could we scope this to same-origin framing instead (for example Content-Security-Policy: frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN), or otherwise make /play use a non-iframe flow? The current combination violates the feature contract described in docs (/play dockable panel).

@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.60% 76.50% -0.10%

Changed lines: 64.98% (334/514) | lost baseline coverage: 3 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov merged commit 3ef3c3b into master May 15, 2026
166 of 167 checks passed
@alexey-milovidov
alexey-milovidov deleted the webterminal branch May 15, 2026 15:54
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Other mediums: Origin check is skipped when the Origin header is missing (if (!origin.empty()) guard); no CORS / X-Frame-Options framing on the WebSocket-HTML page.

@Algunenano, how is it supposed to work then? This comment totally missed the point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-experimental Experimental 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.

6 participants