]> git.kaiwu.me - haproxy.git/commitdiff
BUG/MEDIUM: mjson: stop the lookup when the matched element ends
authorOlivier Houchard <ohouchard@haproxy.com>
Wed, 25 Nov 2026 14:53:23 +0000 (15:53 +0100)
committerOlivier Houchard <cognet@ci0.org>
Wed, 25 Nov 2026 14:53:20 +0000 (15:53 +0100)
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.

src/mjson.c

index 2123eb433471a9c13a526d8a31596a2c79984917..c8dc61738e0a88b980f0489bbe716ffbc6f0c95c 100644 (file)
@@ -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;