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

Ouverte
#630 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 1 jour

Personne n'a encore pris cette issue.

Évaluation

Difficulté
4/5
Temps estimé
3-5 jours
Accessibilité débutants
35/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Active
Stack technique
cpp
Domaine
database

Piste de recherche

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.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

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

Langage dominant
C
Étoiles
388
Forks
220
Merge moyen
1 j 25 min
PR mergées (30 j)
16

Préparer son environnement

Ce projet ne fournit ni conteneur de développement, ni Dockerfile, ni guide de contribution : l'installation est à votre charge. Commencez par son README, et consultez notre guide de la première contribution pour les étapes générales.

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de ClickHouse/clickhouse-cpp

Toutes les issues de ClickHouse/clickhouse-cpp

Issues similaires

Plus d'issues C

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.