From: Olivier Houchard Date: Wed, 25 Nov 2026 14:53:23 +0000 (+0100) Subject: BUG/MEDIUM: mjson: stop the lookup when the matched element ends X-Git-Url: https://git.kaiwu.me/web//%22%22?a=commitdiff_plain;h=24e1f81bee94de8bf6336f2d4b5fbc363d46d100;p=haproxy.git BUG/MEDIUM: mjson: stop the lookup when the matched element ends When a JSON path component matches, mjson_find() does not detect that the matching element ends without containing the rest of the path, and keeps matching the remaining components against what follows. A value may then be returned for a path which does not exist: $.a[0].b on {"a":[{"x":1},{"b":"other"}]} returns "other" $.a[0] on {"a":[],"b":["other"]} returns "other" $.a.b.c on {"a":{"b":1},"x":[{"c":"evil"}]} returns "evil" This affects json_query(), jwt_header_query() and jwt_payload_query(), and can be reproduced with req.body,json_query('$.a[0].b') and the first document above. Let's stop the lookup when a scalar matches a component while the path is not finished, when a comma follows the matching element, and when the container holding it is closed. Commas are also only counted as array separators when an index is expected. The library fixed part of this after it was imported, in its commit d2d9e4658 ("Fix #32 - fail search if value not found in the requested array elem"). This exists since the library was imported in 2.4-dev17 by commit 41007a683 ("MINOR: sample: converter: Add mjson library."). It must be backported to all supported versions. --- diff --git a/src/mjson.c b/src/mjson.c index 2123eb433..c8dc61738 100644 --- a/src/mjson.c +++ b/src/mjson.c @@ -233,7 +233,9 @@ static int mjson_get_cb(int tok, const char *s, int off, int len, void *ud) { if (!data->path[data->pos] && data->d1 == data->d2) data->obj = off; data->d1++; } else if (tok == ',') { - if (data->d1 == data->d2 + 1) { + // the matched element ended without the rest of the path + if (data->d1 == data->d2 && data->d2 > 0) return 1; + if (data->d1 == data->d2 + 1 && data->path[data->pos] == '[') { data->i1++; if (data->i1 == data->i2 && skip_idx(data->path, &data->pos)) data->d2++; @@ -256,9 +258,13 @@ static int mjson_get_cb(int tok, const char *s, int off, int len, void *ud) { if (data->toklen) *data->toklen = off - data->obj + 1; return 1; } + // leaving the container holding the matched element + if (data->d1 < data->d2) return 1; } else if (MJSON_TOK_IS_VALUE(tok)) { // printf("TOK --> %d\n", tok); - if (data->d1 == data->d2 && !data->path[data->pos]) { + if (data->d1 == data->d2) { + // a scalar cannot hold the rest of the path + if (data->path[data->pos]) return 1; data->tok = tok; if (data->tokptr) *data->tokptr = s + off; if (data->toklen) *data->toklen = len;