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

Offen
#630 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Maintainer antworten meist innerhalb von 1 Tag

Dieses Issue hat noch niemand übernommen.

Bewertung

Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Anfängerfreundlichkeit
35/100
Issue-Typ
Bug
Klarheit
Klar beschrieben
Aktivitätsstatus
Aktiv
Tech-Stack
cpp
Bereich
database

Rechercherichtung

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.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Beschreibung

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

Vorherrschende Sprache
C
Sterne
388
Forks
220
Ø Merge
1 T. 25 Min.
Gemergte PRs (30 T.)
16

Entwicklungsumgebung

Dieses Projekt bietet weder Dev-Container noch Dockerfile noch Beitragsleitfaden – die Einrichtung liegt bei Ihnen. Beginnen Sie mit der README; die allgemeinen Schritte stehen in unserem Leitfaden für den ersten Beitrag.

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus ClickHouse/clickhouse-cpp

Alle Issues in ClickHouse/clickhouse-cpp

Ähnliche Issues

Weitere Issues zu C

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.