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

Open
#630 1 comment 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
cpp
Domain
database

Research direction

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.

Written by the indexing model from the issue text.

Description

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

Dominant language
C
Stars
388
Forks
220
Avg merge
1d 25m
Merged PRs (30d)
16

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ClickHouse/clickhouse-cpp

All issues in ClickHouse/clickhouse-cpp

Similar issues

More C issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.