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

未关闭
#630 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
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 分钟
30 天内合并 PR
16

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

ClickHouse/clickhouse-cpp 的其他 Issue

查看 ClickHouse/clickhouse-cpp 的全部 Issue

相似的 Issue

更多 C Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。