Identifier query parameters containing backslash, tab or newline get an extra escape level and name the wrong identifier

オープン
#630 コメント 1 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
35/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
cpp
領域
database

調査の方向性

Start in WireFormat::WriteQuotedString in clickhouse/base/wire_format.cpp, which double-escapes backslash, tab and newline, and at the call site in clickhouse/client.cpp around lines 1109-1119 where parameters are written as CUSTOM settings. Because QueryParams in clickhouse/query.h carries no type information, the first design question is how an Identifier parameter gets marked or detected. Done means the new gtest IdentifierQueryParameterEscaping in ut/client_ut.cpp passes for backslash, tab and newline, and the existing QueryParameters test still passes for String values.

索引モデルが issue の本文から書いたものです。

説明

bug native-protocol queries

Description

Query::SetParam values are sent over the native protocol by WireFormat::WriteQuotedString (clickhouse/base/wire_format.cpp:112, called from clickhouse/client.cpp:1115). That function escapes \, tab and newline with two levels of escaping — the unconditional WriteAll(output, "\\", 1) at wire_format.cpp:139 plus the per-character branches that themselves start with a backslash (R"(\\\)", R"(\\t)", R"(\\n)" at lines 147–157).

This double-escaping is deliberate and is correct for ordinary typed parameters: the server decodes a parameter value twice — once when parsing the custom-setting value as a quoted SQL field, and again via deserializeTextEscaped when converting the parameter text to the declared type. That is why issue #539 was closed as not-a-bug: {p:String} does round-trip correctly.

Identifier is the exception. The server handles {p:Identifier} specially and uses the parameter text as-is, without the second deserializeTextEscaped pass. So for Identifier only one decode happens, one escape level survives, and the identifier the query actually names is not the one that was bound:

value passed        e\f                   (one backslash)
client sends        'e\\\\f'              (four backslashes inside the literal)
server decode #1    e\\f                  (two backslashes)
{p:String}          decode #2 -> e\f      correct
{p:Identifier}      no decode #2 -> e\\f  WRONG — a different identifier

The characters escaped with \xNN forms (\0, \b, ') and characters that are not escaped at all (backtick) are unaffected, so plain names and even names containing ` or ' work — which makes this easy to miss. Only \, tab and newline are affected.

Consequences are silent: an alias comes back with an extra backslash, and reading a JSON subcolumn by a key that contains a backslash returns NULL because that key does not exist. No error is raised.

This is the clickhouse-cpp manifestation of ClickHouse/clickhouse-connect#1243 (same root-cause class: the client escapes every string parameter identically regardless of the declared parameter type). It is not a duplicate of #539 — that issue was about String values, which are fine; Identifier values are not.

ClickHouse server version

26.10.4.207 (native protocol, port 9000). Verified against a running server.

Reproduction

Standalone program linked against the library (this is what I ran):

#include <clickhouse/client.h>
#include <clickhouse/columns/string.h>
#include <iostream>

using namespace clickhouse;

static std::string show(const std::string& s) {
    std::string out;
    for (char c : s) {
        switch (c) {
            case '\\': out += "\\\\"; break;
            case '\t': out += "\\t"; break;
            case '\n': out += "\\n"; break;
            default: out += c;
        }
    }
    return out;
}

int main() {
    Client client(ClientOptions().SetHost("localhost").SetPort(9000));

    const std::vector<std::pair<std::string, std::string>> names = {
        {"plain", "plain"}, {"backtick", "a`b"}, {"quote", "it's"},
        {"backslash", "e\\f"}, {"tab", "a\tb"}, {"newline", "a\nb"},
    };

    std::cout << "--- {p:Identifier} used as an alias ---\n";
    for (const auto& [label, name] : names) {
        Query q("SELECT 1 AS {p:Identifier}");
        q.SetParam("p", name);
        std::string alias;
        q.OnData([&](const Block& block) {
            if (block.GetColumnCount() > 0) alias = block.GetColumnName(0);
        });
        client.Execute(q);
        std::cout << label << ": sent=[" << show(name) << "] got=[" << show(alias) << "] "
                  << (alias == name ? "OK" : "MISMATCH") << "\n";
    }

    std::cout << "--- {p:String} round-trip ---\n";
    for (const auto& [label, name] : names) {
        Query q("SELECT {p:String}");
        q.SetParam("p", name);
        std::string got;
        q.OnData([&](const Block& block) {
            if (block.GetRowCount() > 0) got = std::string(block[0]->As<ColumnString>()->At(0));
        });
        client.Execute(q);
        std::cout << label << ": sent=[" << show(name) << "] got=[" << show(got) << "] "
                  << (got == name ? "OK" : "MISMATCH") << "\n";
    }
    return 0;
}

The printed strings render \, tab and newline as \\, \t, \n.

Actual output:

--- {p:Identifier} used as an alias ---
plain: sent=[plain] got=[plain] OK
backtick: sent=[a`b] got=[a`b] OK
quote: sent=[it's] got=[it's] OK
backslash: sent=[e\\f] got=[e\\\\f] MISMATCH
tab: sent=[a\tb] got=[a\\\tb] MISMATCH
newline: sent=[a\nb] got=[a\\\nb] MISMATCH
--- {p:String} round-trip ---
plain: sent=[plain] got=[plain] OK
backtick: sent=[a`b] got=[a`b] OK
quote: sent=[it's] got=[it's] OK
backslash: sent=[e\\f] got=[e\\f] OK
tab: sent=[a\tb] got=[a\tb] OK
newline: sent=[a\nb] got=[a\nb] OK

Expected: every line reports OK — the alias returned for an Identifier placeholder should equal the value bound with SetParam, exactly as it already does for a String placeholder.

The same check as a gtest, next to the existing TEST_P(ClientCase, QueryParameters) (ut/client_ut.cpp:1856), which does not cover Identifier:

TEST_P(ClientCase, IdentifierQueryParameterEscaping) {
    for (const std::string name : {"plain", "a`b", "it's", "e\\f", "a\tb", "a\nb"}) {
        Query query("SELECT 1 AS {p:Identifier}");
        query.SetParam("p", name);
        std::string alias;
        query.OnData([&](const Block& block) {
            if (block.GetColumnCount() > 0) alias = block.GetColumnName(0);
        });
        client_->Execute(query);
        EXPECT_EQ(name, alias);   // fails for "e\f", "a\tb", "a\nb"
    }
}

Suggested fix

The escaping in WireFormat::WriteQuotedString cannot simply be reduced to one level — that would break every other parameter type and produce BAD_QUERY_PARAMETER, as established in #539. The fix has to be type-aware, like the one proposed for clickhouse-connect: the client needs to know that a parameter is bound to an Identifier placeholder and emit a plain single-escaped SQL literal for it (escaping ' and \ once each) instead of the double-escaped form.

Relevant code:

  • clickhouse/client.cpp:1109-1119 — where parameters are written as CUSTOM settings
  • clickhouse/base/wire_format.cpp:112-168 — WriteQuotedString, the double-escaping
  • clickhouse/query.h:29-30 and clickhouse/query.h:120-130 — QueryParams / SetParam, which currently carry no type information

Since QueryParams has no notion of the declared placeholder type, this needs either a way to mark a parameter as an identifier at SetParam time, or scanning the query text for the name:Identifier placeholder to decide the escaping per parameter.

Link

Relayed from https://github.com/ClickHouse/clickhouse-connect/issues/1243
Related (closed, String-only): https://github.com/ClickHouse/clickhouse-cpp/issues/539

主要言語
C
スター
388
フォーク
220
平均マージ
1日 25分
マージ済み PR(30日)
16

環境構築

このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

ClickHouse/clickhouse-cpp のほかの issue

ClickHouse/clickhouse-cpp の issue をすべて見る

似ている issue

C の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。