On Thu, 29 Dec 2016 02:46:34 GMT, Carl Sturtivant wrote:

Is this a do-it-yourself situation, or is there some canned machinery to sanitize client-communicated text for use as string values in mongodb queries. In fact, what's the best way to do this?

In the usual case, where you'd construct the MongoDB command as either a Bson value, or as a struct that then gets serialized, there is usually nothing to worry about, except getting the command/query structure right in the first place. The rest mostly means restricting the user value to a known type/structure, such as a simple string, in places where extended selectors or modifiers are allowed.

The only situation in which there really can be an issue is when a user input is directly treated as Json and passed verbatim to MongoDB as a value. There is currently no built-in way to sanitize such input, but for the sake of security, AFAICT, it should be sufficient to disallow any key names beginning with "$":

Json sanitizeForMongoDB(Json j)
{
    switch (j.type) {
        default: break;
        case Json.Type.array:
            foreach (size_t i, v; j)
                j[i] = sanitizeForMongoDB(v);
            break;
        case Json.Type.object:
            Json[string] newobj;
            foreach (string k, v; j)
                if (!k.startsWith('$'))
                    newobj[k] = sanitizeForMongoDB(v);
                // else throw new Exception(...);
            return Json(newobj);
    }
    return j;
}