diff --git a/modules-contrib/cachedb_nats/README.md b/modules-contrib/cachedb_nats/README.md index a8e11809c14..825b2f67ede 100644 --- a/modules-contrib/cachedb_nats/README.md +++ b/modules-contrib/cachedb_nats/README.md @@ -314,6 +314,16 @@ module is loaded, JSON documents stored under keys that begin with [fts_json_prefix](#fts_json_prefix-string) are indexed in shared memory: every top-level *string* field becomes a *field:value* entry pointing at the document key. Numbers, booleans and nested values are not indexed. +Values are indexed decoded, and a malformed document, or one over the +*cachedb_nats_fts* +[json_max_depth](../cachedb_nats_fts/README.md#json_max_depth-integer) or +[json_max_bytes](../cachedb_nats_fts/README.md#json_max_bytes-integer) +limits, is not indexed (see the +[cachedb_nats_fts overview](../cachedb_nats_fts/README.md#overview)). +These are separate from this module's own +[json_max_depth](#json_max_depth-integer) and +[json_max_bytes](#json_max_bytes-integer), which apply to the documents +it reads. The index answers the CacheDB `query()` and `update()` calls that @@ -795,8 +805,11 @@ ignored.** Only usrloc rows expire. and `.` `_` `-` `/` `\` `=` (see [KV Key Validation](#kv-key-validation)). - **Values:** usrloc rows are limited by [max_value_size](#max_value_size-integer) (1 MiB by -default); JSON documents over 1 MiB or nested deeper than 64 levels are -rejected. +default) when written. A JSON document read back that is larger than +[json_max_bytes](#json_max_bytes-integer) (1 MiB by default), nested +deeper than [json_max_depth](#json_max_depth-integer) (64 levels by +default) or holding a NUL byte is refused: a query skips it and logs +an error. - **Revisions are 32-bit in the script.** [nats_kv_update()](#nats_kv_updatebucket-key-value-expected_rev) compares against a revision truncated to 32 bits, so a compare-and-swap fails @@ -1668,7 +1681,10 @@ oversize row is detected before the CAS write and the offending contact's save fails cleanly — never a silent truncation or corruption. Set this to the deployment's real per-message cap (and no larger than the stream's `max_msg_size`). -A value **<= 0** disables the guard. +A value **<= 0** disables the guard. Keep +[json_max_bytes](#json_max_bytes-integer) at or above this value: a +larger row is written, then refused on every read (a warning is logged +at startup). *Default value is "1048576" (1 MiB, the @@ -1682,6 +1698,67 @@ modparam("cachedb_nats", "max_value_size", 65536) ``` +#### json_max_depth (integer) + + +Maximum nesting depth, counting the top-level object as 1, of a JSON +document read from the bucket (usrloc rows and documents returned by +CacheDB queries, and the +[nats_reg_show](#cachedb_natsnats_reg_show) MI command). A deeper +document is refused before it is parsed: a query skips it and logs an +error. The JSON parser recurses once per level, so this bounds the +stack a document written to the bucket can use. The value must be +between 1 and 1024; any other value is an error in the configuration, +reported when it is read (`opensips -C` included), and OpenSIPS does +not start. + + +This limit applies to what *cachedb_nats* reads. The +[cachedb_nats_fts](../cachedb_nats_fts/README.md) module has its own +[json_max_depth](../cachedb_nats_fts/README.md#json_max_depth-integer) +for the documents it indexes. + + +*Default value is "64".* + + +```opensips title="Set json_max_depth parameter" +... +modparam("cachedb_nats", "json_max_depth", 16) +... +``` + + +#### json_max_bytes (integer) + + +Maximum size, in bytes, of a JSON document read from the bucket (as +for [json_max_depth](#json_max_depth-integer)). A larger document is +refused before it is parsed: a query skips it and logs an error. The +value must be at least 2 (the size of `{}`); a smaller value is an +error in the configuration, reported when it is read (`opensips -C` +included), and OpenSIPS does not start. Keep it at or above +[max_value_size](#max_value_size-integer); otherwise a warning is +logged at startup. + + +This limit applies to what *cachedb_nats* reads. The +[cachedb_nats_fts](../cachedb_nats_fts/README.md) module has its own +[json_max_bytes](../cachedb_nats_fts/README.md#json_max_bytes-integer) +for the documents it indexes. + + +*Default value is "1048576" (1 MiB, the NATS `max_payload` +default).* + + +```opensips title="Set json_max_bytes parameter" +... +modparam("cachedb_nats", "json_max_bytes", 2097152) +... +``` + + #### kv_op_timeout_ms (integer) diff --git a/modules-contrib/cachedb_nats/cachedb_nats.c b/modules-contrib/cachedb_nats/cachedb_nats.c index 344c31b552f..798ed0e2c56 100644 --- a/modules-contrib/cachedb_nats/cachedb_nats.c +++ b/modules-contrib/cachedb_nats/cachedb_nats.c @@ -71,6 +71,7 @@ #include "cachedb_nats.h" #include "cachedb_nats_dbase.h" #include "cachedb_nats_json.h" +#include "cachedb_nats_json_internal.h" /* json_max_* modparams */ #include "../cachedb_nats_fts/cachedb_nats_fts_api.h" #include "cachedb_nats_watch.h" #include "cachedb_nats_native.h" @@ -352,6 +353,10 @@ static const param_export_t params[] = { {"reap_interval", INT_PARAM, &nats_reap_interval}, {"expired_linger", INT_PARAM, &nats_expired_linger}, {"max_value_size", INT_PARAM, &nats_max_value_size}, + {"json_max_depth", INT_PARAM|USE_FUNC_PARAM, + (void *)cdbn_json_set_max_depth}, + {"json_max_bytes", INT_PARAM|USE_FUNC_PARAM, + (void *)cdbn_json_set_max_bytes}, {"kv_watch", STR_PARAM|USE_FUNC_PARAM, (void *)&set_watch_pattern}, {"reconnect_wait_ms", INT_PARAM, &nats_cdb_reconnect_wait_ms}, {"max_reconnect", INT_PARAM, &nats_cdb_max_reconnect}, @@ -502,10 +507,10 @@ struct module_exports exports = { "cachedb_nats", /* module name */ MOD_TYPE_CACHEDB, /* class of this module */ MODULE_VERSION, - RTLD_NOW | RTLD_GLOBAL, /* dlopen flags: GLOBAL so the optional - * cachedb_nats_fts module (loaded after - * us) resolves the shared JSON walkers - * this module defines */ + DEFAULT_DLFLAGS, /* dlopen flags: never RTLD_GLOBAL, which + * would let this module's symbols, its + * exports included, stand in for those + * of modules loaded after it */ 0, /* load function */ &deps, /* OpenSIPS module dependencies */ cmds, /* exported functions */ @@ -562,6 +567,10 @@ static int init_check_params(void) * every usrloc read/write, watch event and reap pass). */ fts_json_prefix_len = fts_json_prefix ? (int)strlen(fts_json_prefix) : 0; + if (cdbn_json_check_limits() < 0) + return -1; + cdbn_json_check_row_size(nats_max_value_size); + /* Kv_ttl becomes the KV bucket's * MaxAge (nats_pool.c: kvCfg.TTL). Stream MaxAge takes precedence over * per-message TTL and would SILENTLY EXPIRE PERMANENT CONTACTS diff --git a/modules-contrib/cachedb_nats/cachedb_nats_json_internal.h b/modules-contrib/cachedb_nats/cachedb_nats_json_internal.h index 64bf713a794..eeec3e43b90 100644 --- a/modules-contrib/cachedb_nats/cachedb_nats_json_internal.h +++ b/modules-contrib/cachedb_nats/cachedb_nats_json_internal.h @@ -33,6 +33,7 @@ #include #include "../../cachedb/cachedb.h" +#include "../../sr_module.h" /* modparam_t */ #include "cachedb_nats_json.h" #include "../../locking.h" @@ -140,6 +141,46 @@ const char *cdbn_parse_json_string(const char *p, const char *end, */ int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out); +/* + * Limits json_parse_guard() applies before cJSON parses a broker-supplied + * document (modparams json_max_depth and json_max_bytes): a document + * nested deeper, or larger, is refused. cJSON recurses once per nesting + * level, hence the depth ceiling. + */ +#define CDBN_JSON_DEFAULT_MAX_DEPTH 64 +#define CDBN_JSON_DEFAULT_MAX_BYTES (1 * 1024 * 1024) +#define CDBN_JSON_DEPTH_CEILING 1024 +extern int cdbn_json_max_depth; +extern int cdbn_json_max_bytes; + +/* + * The json_max_depth / json_max_bytes modparam setters (INT_PARAM): check + * the value as the config is read, so that "opensips -C" reports a bad + * one, and store it. + * + * @return 0 when stored; -1, with an error logged and the value + * unchanged, when out of range (depth 1..CDBN_JSON_DEPTH_CEILING, + * bytes at least 2, the size of "{}"). + */ +int cdbn_json_set_max_depth(modparam_t type, void *val); +int cdbn_json_set_max_bytes(modparam_t type, void *val); + +/* + * Check both limits again (mod_init). + * + * @return 0 when valid; -1, with an error logged, otherwise. + */ +int cdbn_json_check_limits(void); + +/* + * Warn when json_max_bytes is below @max_value_size (the usrloc row write + * cap; <= 0 means none): such a row is written, then refused on every + * read. + * + * @return 1 when it warned, 0 otherwise. + */ +int cdbn_json_check_row_size(int max_value_size); + /* --- JSON sink / serializer (cachedb_nats_json_ser.c) -------------- */ typedef struct { diff --git a/modules-contrib/cachedb_nats/cachedb_nats_json_walk.c b/modules-contrib/cachedb_nats/cachedb_nats_json_walk.c index 6a7b7216781..0af2b81b0d4 100644 --- a/modules-contrib/cachedb_nats/cachedb_nats_json_walk.c +++ b/modules-contrib/cachedb_nats/cachedb_nats_json_walk.c @@ -20,12 +20,11 @@ */ /* - * cachedb_nats_json_walk.c — the shared, dependency-free JSON walkers + * cachedb_nats_json_walk.c — the dependency-free JSON walkers * (cdbn_skip_ws, cdbn_parse_json_string, cdbn_skip_json_value, cdbn_safe_json_to_dict) - * used by this module's JSON layer AND by the optional cachedb_nats_fts - * module (declared in cachedb_nats_json_internal.h). Split into their - * own TU so unit tests can link them without dragging either module's - * full dependency graph. + * used by this module's JSON layer (declared in + * cachedb_nats_json_internal.h). Split into their own TU so unit tests + * can link them without dragging the module's full dependency graph. */ #include @@ -43,12 +42,68 @@ * the recursive cJSON_Parse() (see json_parse_guard). cJSON recurses * one C stack frame per nesting level with no internal cap, so an * attacker who can publish to the KV bucket could otherwise crash a SIP - * worker with a deeply nested value. Depth 64 is far beyond any real - * usrloc/cachedb document; the byte cap matches NATS's default - * max_payload (1 MiB). + * worker with a deeply nested value. The json_max_depth / json_max_bytes + * modparams; the defaults (depth 64, NATS's default max_payload of 1 MiB) + * are far beyond any real usrloc/cachedb document. */ -#define NATS_JSON_MAX_DEPTH 64 -#define NATS_JSON_MAX_BYTES (1 * 1024 * 1024) +int cdbn_json_max_depth = CDBN_JSON_DEFAULT_MAX_DEPTH; +int cdbn_json_max_bytes = CDBN_JSON_DEFAULT_MAX_BYTES; + +static int valid_max_depth(int v) +{ + if (v < 1 || v > CDBN_JSON_DEPTH_CEILING) { + LM_ERR("json_max_depth %d out of range: 1 (the top-level object) " + "to %d (deeper risks the stack in the recursive parser)\n", + v, CDBN_JSON_DEPTH_CEILING); + return 0; + } + return 1; +} + +static int valid_max_bytes(int v) +{ + if (v < 2) { + LM_ERR("json_max_bytes %d out of range: at least 2 (\"{}\")\n", v); + return 0; + } + return 1; +} + +int cdbn_json_set_max_depth(modparam_t type, void *val) +{ + int v = (int)(long)val; + + if (!valid_max_depth(v)) + return -1; + cdbn_json_max_depth = v; + return 0; +} + +int cdbn_json_set_max_bytes(modparam_t type, void *val) +{ + int v = (int)(long)val; + + if (!valid_max_bytes(v)) + return -1; + cdbn_json_max_bytes = v; + return 0; +} + +int cdbn_json_check_limits(void) +{ + return valid_max_depth(cdbn_json_max_depth) + && valid_max_bytes(cdbn_json_max_bytes) ? 0 : -1; +} + +int cdbn_json_check_row_size(int max_value_size) +{ + if (max_value_size <= 0 || cdbn_json_max_bytes >= max_value_size) + return 0; + LM_WARN("json_max_bytes (%d) is below max_value_size (%d): a usrloc " + "row larger than json_max_bytes is written, then refused on " + "every read\n", cdbn_json_max_bytes, max_value_size); + return 1; +} /** * cdbn_skip_ws() — Advance past JSON whitespace characters. @@ -236,7 +291,7 @@ int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out) int rc; if (json_parse_guard(data, data_len, - NATS_JSON_MAX_DEPTH, NATS_JSON_MAX_BYTES) != 0) { + cdbn_json_max_depth, cdbn_json_max_bytes) != 0) { LM_WARN("rejecting broker JSON document (%d bytes): failed " "depth/size/NUL guard before parse\n", data_len); return -1; @@ -245,7 +300,7 @@ int cdbn_safe_json_to_dict(const char *data, int data_len, cdb_dict_t *out) if (data_len < (int)sizeof(stackbuf)) { buf = stackbuf; } else { - buf = pkg_malloc(data_len + 1); + buf = pkg_malloc((size_t)data_len + 1); if (!buf) { LM_ERR("no pkg memory for %d-byte JSON parse copy\n", data_len); diff --git a/modules-contrib/cachedb_nats/test/cn_ut.h b/modules-contrib/cachedb_nats/test/cn_ut.h index cd0fdff5179..9a2d92c9fba 100644 --- a/modules-contrib/cachedb_nats/test/cn_ut.h +++ b/modules-contrib/cachedb_nats/test/cn_ut.h @@ -23,10 +23,12 @@ void cn_ut_doc_filter(void); void cn_ut_emit_rows(void); void cn_ut_fmt_table(void); void cn_ut_fts_optional(void); +void cn_ut_global_scope(void); void cn_ut_index_stale_recovery(void); void cn_ut_insecure_url_warn(void); void cn_ut_json_escape(void); void cn_ut_json_foreach(void); +void cn_ut_json_limits(void); void cn_ut_json_name_passthrough(void); void cn_ut_json_parse_guard(void); void cn_ut_kv_epoch_refresh(void); diff --git a/modules-contrib/cachedb_nats/test/test_all.c b/modules-contrib/cachedb_nats/test/test_all.c index 1649d8e2d19..4d38500c987 100644 --- a/modules-contrib/cachedb_nats/test/test_all.c +++ b/modules-contrib/cachedb_nats/test/test_all.c @@ -23,10 +23,12 @@ void cn_ut_all(void) cn_ut_emit_rows(); cn_ut_fmt_table(); cn_ut_fts_optional(); + cn_ut_global_scope(); cn_ut_index_stale_recovery(); cn_ut_insecure_url_warn(); cn_ut_json_escape(); cn_ut_json_foreach(); + cn_ut_json_limits(); cn_ut_json_name_passthrough(); cn_ut_json_parse_guard(); cn_ut_kv_epoch_refresh(); diff --git a/modules-contrib/cachedb_nats/test/test_global_scope.c b/modules-contrib/cachedb_nats/test/test_global_scope.c new file mode 100644 index 00000000000..268330955e5 --- /dev/null +++ b/modules-contrib/cachedb_nats/test/test_global_scope.c @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2026 OpenSIPS Solutions + * + * This file is part of opensips, a free SIP server. + * + * opensips is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * opensips is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * No symbol of cachedb_nats reaches the global scope (GitHub #4501): with + * RTLD_GLOBAL, its "exports" took the place of the "exports" of every + * module loaded after it (rtpengine's notification_sock setter wrote + * cachedb_nats's exports.procs, so its process was never forked). + * cachedb_nats_fts parses its documents with the core's cJSON, so this + * module shares no JSON code with it: no symbol, and no bind command. + */ + +#include +#include +#include + +#include "../../../sr_module.h" + +#include "cn_ut.h" + +static struct sr_module *own_module(void) +{ + struct sr_module *m; + + for (m = modules; m; m = m->next) + if (m->exports && m->exports->name + && !strcmp(m->exports->name, "cachedb_nats")) + return m; + return NULL; +} + +/* The symbols of cachedb_nats.so that a global scope would hand out. */ +static const char *const own_symbols[] = { + "exports", + "cdbn_skip_ws", + "cdbn_parse_json_string", + "cdbn_skip_json_value", + "cdbn_safe_json_to_dict", + "cdbn_fts", + "cdbn_fts_on", + "kv_bucket", + "nats_api", + NULL +}; + +static void global_scope(const struct sr_module *m) +{ + const char *const *n; + void *own, *glob, *main_h; + + ok(!(m->exports->dlflags & RTLD_GLOBAL), + "global_scope: dlopen flags carry no RTLD_GLOBAL (0x%x)", + m->exports->dlflags); + + /* The main program's handle searches the global scope only: the + * program, its startup libraries and RTLD_GLOBAL objects. + * RTLD_DEFAULT cannot be used here: it is a GNU extension, and + * glibc searches it from the scope of the caller, which always + * holds cachedb_nats.so itself. */ + main_h = dlopen(NULL, RTLD_NOW); + ok(main_h != NULL, "global_scope: dlopen(NULL) gives the global scope"); + if (!main_h) + return; + + for (n = own_symbols; *n; n++) { + own = dlsym(m->handle, *n); + glob = dlsym(main_h, *n); + ok(own != NULL && glob != own, + "global_scope: %s of cachedb_nats.so (%p) is not the " + "global-scope %s (%p)", *n, own, *n, glob); + } + dlclose(main_h); +} + +void cn_ut_global_scope(void) +{ + struct sr_module *m = own_module(); + + ok(m != NULL && m->handle != NULL, + "global_scope: cachedb_nats is in the core's module list"); + if (!m || !m->handle) + return; + + global_scope(m); + ok(find_export("cdbn_json_bind", 0) == NULL, + "global_scope: no cdbn_json_bind command (nothing to share)"); +} diff --git a/modules-contrib/cachedb_nats/test/test_json_limits.c b/modules-contrib/cachedb_nats/test/test_json_limits.c new file mode 100644 index 00000000000..ab090bb53ff --- /dev/null +++ b/modules-contrib/cachedb_nats/test/test_json_limits.c @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2026 OpenSIPS Solutions + * + * This file is part of opensips, a free SIP server. + * + * opensips is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * opensips is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * The read-path guard's limits (json_parse_guard, before cJSON) are the + * json_max_depth / json_max_bytes modparams: defaults 64 and 1 MiB, the + * setters refuse what cannot work as the config is read (so "opensips + * -C" reports it), the guard applies whatever is set, the depth ceiling + * parses, and the README documents both with their real defaults. + */ + +#include +#include +#include +#include +#include + +#include "../../../sr_module.h" +#include "../../../cachedb/cachedb_dict.h" +#include "../cachedb_nats_json_internal.h" + +#include "cn_ut.h" +#include "cn_ut_fake.h" + +#define CHECK(cond, ...) ok((cond), "json_limits: " __VA_ARGS__) +#define GUARD_LOG "failed depth/size/NUL guard" + +/* {"a":{"a":...{}...}} -- @n objects deep */ +static char *nested(int n) +{ + char *b = malloc((size_t)n * 6 + 1); + int i, w = 0; + + if (!b) + return NULL; + for (i = 0; i < n - 1; i++) { + memcpy(b + w, "{\"a\":", 5); + w += 5; + } + b[w++] = '{'; + for (i = 0; i < n; i++) + b[w++] = '}'; + b[w] = '\0'; + return b; +} + +/* 0 parsed, -1 refused; *guarded: the guard (not the parser) refused */ +static int parse(const char *data, int len, int *guarded) +{ + cdb_dict_t d; + int rc; + + cn_ut_fake_log_clear(); + INIT_LIST_HEAD(&d); + rc = cdbn_safe_json_to_dict(data, len, &d); + if (rc == 0) + cdb_free_entries(&d, NULL); + *guarded = strstr(cn_ut_fake_log(), GUARD_LOG) != NULL; + return rc; +} + +static int parse_nested(int n, int *guarded) +{ + char *doc = nested(n); + int rc; + + if (!doc) + return -2; + rc = parse(doc, (int)strlen(doc), guarded); + free(doc); + return rc; +} + +static void defaults(void) +{ + CHECK(cdbn_json_max_depth == 64 && cdbn_json_max_bytes == 1024 * 1024, + "default limits: depth 64, 1 MiB (%d, %d)", + cdbn_json_max_depth, cdbn_json_max_bytes); + CHECK(cdbn_json_check_limits() == 0, "the default limits are valid"); +} + +static void applied(void) +{ + int depth = cdbn_json_max_depth, bytes = cdbn_json_max_bytes, g; + /* exactly 20 bytes, then 21 */ + static const char b20[] = "{\"a\":\"x\",\"b\":\"1234\"}"; + static const char b21[] = "{\"a\":\"x\",\"b\":\"12345\"}"; + + cdbn_json_max_depth = 3; + CHECK(parse_nested(3, &g) == 0, "json_max_depth 3: 3 levels parse"); + CHECK(parse_nested(4, &g) == -1 && g, + "json_max_depth 3: 4 levels are refused by the guard"); + cdbn_json_max_depth = depth; + CHECK(parse_nested(4, &g) == 0, "back at the default, 4 levels parse"); + + CHECK(sizeof b20 - 1 == 20 && sizeof b21 - 1 == 21, "probe sizes"); + cdbn_json_max_bytes = 20; + CHECK(parse(b20, 20, &g) == 0, "json_max_bytes 20: 20 bytes parse"); + CHECK(parse(b21, 21, &g) == -1 && g, + "json_max_bytes 20: 21 bytes are refused by the guard"); + cdbn_json_max_bytes = bytes; + CHECK(parse(b21, 21, &g) == 0, "back at the default, 21 bytes parse"); + + /* the ceiling is safe: a document that deep parses */ + cdbn_json_max_depth = CDBN_JSON_DEPTH_CEILING; + CHECK(parse_nested(CDBN_JSON_DEPTH_CEILING, &g) == 0, + "json_max_depth %d: a document that deep parses", + CDBN_JSON_DEPTH_CEILING); + CHECK(parse_nested(CDBN_JSON_DEPTH_CEILING + 1, &g) == -1 && g, + "... and one level more is refused by the guard"); + cdbn_json_max_depth = depth; +} + +static void setters(void) +{ + static const struct { int v; int ok; } dc[] = { + { 0, 0 }, { -3, 0 }, { 1025, 0 }, { INT_MIN, 0 }, { INT_MAX, 0 }, + { 1, 1 }, { 16, 1 }, { 1024, 1 }, + }; + static const struct { int v; int ok; } bc[] = { + { 0, 0 }, { 1, 0 }, { -1, 0 }, { INT_MIN, 0 }, + { 2, 1 }, { 4096, 1 }, { INT_MAX, 1 }, + }; + int depth = cdbn_json_max_depth, bytes = cdbn_json_max_bytes; + unsigned i; + int prev, rc; + + for (i = 0; i < sizeof dc / sizeof dc[0]; i++) { + prev = cdbn_json_max_depth; + rc = cdbn_json_set_max_depth(INT_PARAM, (void *)(long)dc[i].v); + CHECK(dc[i].ok ? (rc == 0 && cdbn_json_max_depth == dc[i].v) + : (rc < 0 && cdbn_json_max_depth == prev), + "modparam json_max_depth %d is %s", dc[i].v, + dc[i].ok ? "set" : "refused, the value kept"); + } + for (i = 0; i < sizeof bc / sizeof bc[0]; i++) { + prev = cdbn_json_max_bytes; + rc = cdbn_json_set_max_bytes(INT_PARAM, (void *)(long)bc[i].v); + CHECK(bc[i].ok ? (rc == 0 && cdbn_json_max_bytes == bc[i].v) + : (rc < 0 && cdbn_json_max_bytes == prev), + "modparam json_max_bytes %d is %s", bc[i].v, + bc[i].ok ? "set" : "refused, the value kept"); + } + + /* mod_init's check, on values that bypassed the setters */ + cdbn_json_max_depth = 0; + CHECK(cdbn_json_check_limits() < 0, "mod_init refuses json_max_depth 0"); + cdbn_json_max_depth = depth; + cdbn_json_max_bytes = 1; + CHECK(cdbn_json_check_limits() < 0, "mod_init refuses json_max_bytes 1"); + cdbn_json_max_depth = depth; + cdbn_json_max_bytes = bytes; +} + +/* a usrloc row may be written up to max_value_size bytes: a smaller + * json_max_bytes would refuse it on every read, so startup warns */ +static void vs_max_value_size(void) +{ + int bytes = cdbn_json_max_bytes; + + cn_ut_fake_log_clear(); + CHECK(cdbn_json_check_row_size(1048576) == 0 + && !strstr(cn_ut_fake_log(), "json_max_bytes"), + "defaults: json_max_bytes covers max_value_size, no warning"); + cdbn_json_max_bytes = 65536; + cn_ut_fake_log_clear(); + CHECK(cdbn_json_check_row_size(1048576) == 1 + && strstr(cn_ut_fake_log(), "json_max_bytes"), + "json_max_bytes 65536 < max_value_size 1048576: warned"); + cn_ut_fake_log_clear(); + CHECK(cdbn_json_check_row_size(65536) == 0, + "json_max_bytes equal to max_value_size: no warning"); + CHECK(cdbn_json_check_row_size(0) == 0 + && cdbn_json_check_row_size(-1) == 0, + "max_value_size <= 0 (no write cap): no warning"); + cdbn_json_max_bytes = bytes; +} + +/* "#### (integer)" with "*Default value is "N"" in that section */ +static void readme(void) +{ + static const struct { const char *name; const int *var; } p[] = { + { "json_max_depth", &cdbn_json_max_depth }, + { "json_max_bytes", &cdbn_json_max_bytes }, + }; + static char doc[256 * 1024]; + FILE *f; + size_t n; + unsigned i; + + f = fopen("modules-contrib/cachedb_nats/README.md", "r"); + CHECK(f != NULL, "README.md readable from the source tree"); + if (!f) + return; + n = fread(doc, 1, sizeof doc - 1, f); + fclose(f); + doc[n] = '\0'; + CHECK(n > 0 && n < sizeof doc - 1, "README.md read whole (%zu bytes)", n); + + for (i = 0; i < sizeof p / sizeof p[0]; i++) { + char head[128], want[64]; + const char *h, *d, *next; + + snprintf(head, sizeof head, "\n#### %s (integer)\n", p[i].name); + h = strstr(doc, head); + CHECK(h != NULL, "README documents %s", p[i].name); + if (!h) + continue; + next = strstr(h + strlen(head), "\n#### "); + snprintf(want, sizeof want, "*Default value is \"%d\"", *p[i].var); + d = strstr(h, want); + CHECK(d != NULL && (!next || d < next), + "README gives %s's default as %d", p[i].name, *p[i].var); + } +} + +void cn_ut_json_limits(void) +{ + cn_ut_fake_begin(); + defaults(); + applied(); + setters(); + vs_max_value_size(); + cn_ut_fake_end(); + readme(); +} diff --git a/modules-contrib/cachedb_nats/test/test_json_parse_guard.c b/modules-contrib/cachedb_nats/test/test_json_parse_guard.c index ce3516ee2de..01d6a307ea6 100644 --- a/modules-contrib/cachedb_nats/test/test_json_parse_guard.c +++ b/modules-contrib/cachedb_nats/test/test_json_parse_guard.c @@ -43,9 +43,10 @@ * input that would blow the stack. * * Through the exported read-path parser cdbn_safe_json_to_dict(), which - * runs the static guard (depth 64, 1 MiB, no NUL) with the production - * limits before cdb_json_to_dict; the guard's log line tells a guard - * refusal from a parse failure. The "synced copy" of the guard, the + * runs the static guard (the json_max_depth / json_max_bytes modparams, + * at their defaults here: depth 64, 1 MiB; no NUL) before + * cdb_json_to_dict; the guard's log line tells a guard refusal from a + * parse failure. The "synced copy" of the guard, the * recursion model and the copied limits are gone; nesting is built from * objects (an array is refused by the parser anyway). * "deep nesting rejected" assertions diff --git a/modules-contrib/cachedb_nats_fts/README.md b/modules-contrib/cachedb_nats_fts/README.md index 6f90de733e6..38246bae402 100644 --- a/modules-contrib/cachedb_nats_fts/README.md +++ b/modules-contrib/cachedb_nats_fts/README.md @@ -24,6 +24,16 @@ index lives in shared memory, so all OpenSIPS processes use the same copy. +Documents are parsed with the OpenSIPS core's JSON parser (cJSON). +Field names and values are indexed decoded: `"Foo \"Bar\""` is +matched as `Foo "Bar"` and `"Z\u00fcrich"` as `Zürich`. A document +is not indexed at all, and a warning is logged, when it is not a +single JSON object (trailing text included), when it is malformed or +holds a NUL byte (raw or as `\u0000`), or when it is nested deeper +than [json_max_depth](#json_max_depth-integer) or larger than +[json_max_bytes](#json_max_bytes-integer). + + The index serves the CacheDB `query()` and `update()` calls that OpenSIPS modules make with non-key equality filters. Without this module, *cachedb_nats* accepts only single primary-key filters. @@ -59,8 +69,6 @@ the watcher was disconnected appear after the post-reconnect rebuild ([index_resync_on_reconnect](../cachedb_nats/README.md#index_resync_on_reconnect-integer), on by default); a restore of the bucket from a snapshot appears only after a rebuild or restart. -- The module must be loaded after *cachedb_nats*. Load order is not -enforced. - Under heavy registration churn the default Q_MALLOC shared-memory allocator becomes a point of contention; see the *cachedb_nats* [allocator guidance](../cachedb_nats/README.md#shm-allocator-selection). @@ -133,6 +141,63 @@ A value of 0 or less removes the limit. modparam("cachedb_nats_fts", "fts_max_results", 500) ... ``` + + +#### json_max_depth (integer) + + +Maximum nesting depth of a JSON document, counting the top-level +object as 1; a deeper document is not indexed. The JSON parser +recurses once per level, so this bounds the stack a document +written to the bucket can use. The value must be between 1 and +1024; any other value is an error in the configuration, reported +when it is read (`opensips -C` included), and OpenSIPS does not +start. + + +This limit applies to the documents this module indexes. +*cachedb_nats* has its own +[json_max_depth](../cachedb_nats/README.md#json_max_depth-integer) +for the documents it reads. + + +*Default value is "64".* + + +```opensips title="Set json_max_depth parameter" +... +modparam("cachedb_nats_fts", "json_max_depth", 16) +... +``` + + +#### json_max_bytes (integer) + + +Maximum size, in bytes, of a JSON document; a larger document is +not indexed. The value must be at least 2 (the size of `{}`); a +smaller value is an error in the configuration, reported when it is +read (`opensips -C` included), and OpenSIPS does not start. Keep +it at or above the largest document stored under +[fts_json_prefix](../cachedb_nats/README.md#fts_json_prefix-string), +which NATS bounds by the server's `max_payload`. + + +This limit applies to the documents this module indexes. +*cachedb_nats* has its own +[json_max_bytes](../cachedb_nats/README.md#json_max_bytes-integer) +for the documents it reads. + + +*Default value is "1048576" (1 MiB, the NATS `max_payload` +default).* + + +```opensips title="Set json_max_bytes parameter" +... +modparam("cachedb_nats_fts", "json_max_bytes", 65536) +... +``` ### License diff --git a/modules-contrib/cachedb_nats_fts/cachedb_nats_fts.c b/modules-contrib/cachedb_nats_fts/cachedb_nats_fts.c index 261e2d84c75..c0f36307439 100644 --- a/modules-contrib/cachedb_nats_fts/cachedb_nats_fts.c +++ b/modules-contrib/cachedb_nats_fts/cachedb_nats_fts.c @@ -94,6 +94,10 @@ struct nats_binds nats_api; static const param_export_t params[] = { {"index_buckets", INT_PARAM, &nats_idx_buckets}, {"fts_max_results", INT_PARAM, &fts_max_results}, + {"json_max_depth", INT_PARAM|USE_FUNC_PARAM, + (void *)fts_json_set_max_depth}, + {"json_max_bytes", INT_PARAM|USE_FUNC_PARAM, + (void *)fts_json_set_max_bytes}, {0, 0, 0} }; @@ -135,6 +139,8 @@ static int mod_init(void) { LM_INFO("initializing cachedb_nats_fts (SHM search index)\n"); + if (fts_json_check_limits() < 0) + return -1; if (nats_bind_api("cachedb_nats_fts") < 0) return -1; if (nats_intern_init(nats_idx_buckets) < 0) { diff --git a/modules-contrib/cachedb_nats_fts/fts_index.c b/modules-contrib/cachedb_nats_fts/fts_index.c index dd7a9d6c0c6..37184ad4503 100644 --- a/modules-contrib/cachedb_nats_fts/fts_index.c +++ b/modules-contrib/cachedb_nats_fts/fts_index.c @@ -25,10 +25,10 @@ * Owns the field:value -> document-key search index for JSON documents * stored in NATS JetStream KV buckets: hash table + doc-key reverse map * (revmap) in SHM, sharded lock set, and the index lifecycle - * (init / build / add / remove / rebuild / destroy). Also owns the - * defensive JSON parse helpers (json_parse_guard and friends) used - * before any broker-supplied document reaches the recursive cJSON - * parser. + * (init / build / add / remove / rebuild / destroy). Documents are + * parsed with the core's cJSON, behind fts_json_guard(), which refuses + * what the recursive parser must not see (deep nesting, raw NUL, + * oversize). * * Split out of cachedb_nats_json.c (proc-TU split); the query() / * update() cachedb callbacks live there, the escape/sink/serializer @@ -49,12 +49,12 @@ #include "../nats/nats_bind.h" #include "../nats/nats_dl.h" /* libnats function-pointer table */ +#include "../../lib/cJSON.h" #include "fts_index.h" #include "../cachedb_nats/cachedb_nats.h" #include "../cachedb_nats/cachedb_nats_stats.h" #include "../cachedb_nats/cachedb_nats_dbase.h" #include "fts_intern.h" -#include "../cachedb_nats/cachedb_nats_json_internal.h" /* ------------------------------------------------------------------ */ @@ -109,95 +109,201 @@ unsigned int fts_hash(const char *s, int len) /* Simple JSON field parser */ /* ------------------------------------------------------------------ */ -/* The shared JSON walkers (cdbn_skip_ws, cdbn_parse_json_string, - * cdbn_skip_json_value, cdbn_safe_json_to_dict) stay in cachedb_nats's JSON - * layer (cachedb_nats_json.c) -- both sides use them via - * cachedb_nats_json_internal.h. */ +/* Documents are parsed with the core's cJSON (lib/cJSON.h): this module + * needs no JSON code of cachedb_nats, which is therefore opened without + * RTLD_GLOBAL (GitHub #4501). */ +/* cJSON recurses one C stack frame per nesting level with no cap of its + * own, and anyone able to write to the KV bucket chooses the document: + * refuse deep ones first. The json_max_depth / json_max_bytes modparams; + * the defaults are far beyond any real document, and NATS's default + * max_payload (1 MiB). */ +int fts_json_max_depth = FTS_JSON_DEFAULT_MAX_DEPTH; +int fts_json_max_bytes = FTS_JSON_DEFAULT_MAX_BYTES; + +static int valid_max_depth(int v) +{ + if (v < 1 || v > FTS_JSON_DEPTH_CEILING) { + LM_ERR("json_max_depth %d out of range: 1 (the top-level object) " + "to %d (deeper risks the stack in the recursive parser)\n", + v, FTS_JSON_DEPTH_CEILING); + return 0; + } + return 1; +} + +static int valid_max_bytes(int v) +{ + if (v < 2) { + LM_ERR("json_max_bytes %d out of range: at least 2 (\"{}\")\n", v); + return 0; + } + return 1; +} + +int fts_json_set_max_depth(modparam_t type, void *val) +{ + int v = (int)(long)val; + + if (!valid_max_depth(v)) + return -1; + fts_json_max_depth = v; + return 0; +} + +int fts_json_set_max_bytes(modparam_t type, void *val) +{ + int v = (int)(long)val; + + if (!valid_max_bytes(v)) + return -1; + fts_json_max_bytes = v; + return 0; +} + +int fts_json_check_limits(void) +{ + return valid_max_depth(fts_json_max_depth) + && valid_max_bytes(fts_json_max_bytes) ? 0 : -1; +} + +/* The index is used from threads too (the unit tests' churn; its lists + * use malloc, its locks are per shard), and pkg memory is not + * thread-safe: cJSON allocates with the system malloc here. Its hooks + * are thread-local, so setting them affects this thread only; they are + * set back to the default (pkg) right after, as everywhere else. */ +static cJSON *fts_json_parse(const char *buf) +{ + cJSON *root; + + cJSON_InitHooks(&sys_mem_hooks); + /* require_null_terminated: nothing but whitespace after the value */ + root = cJSON_ParseWithOpts(buf, NULL, 1); + cJSON_InitHooks(NULL); + return root; +} + +/* Free a tree from fts_json_parse(); NULL-safe. */ +static void fts_json_free(cJSON *root) +{ + if (!root) + return; + cJSON_InitHooks(&sys_mem_hooks); + cJSON_Delete(root); + cJSON_InitHooks(NULL); +} + +/** + * fts_json_guard() — Pre-check a broker-supplied document for cJSON. + * + * Iterative, no allocation. Refuses (-1) a NULL or empty buffer, one + * larger than json_max_bytes, any raw NUL byte (cJSON reads a C string: + * a NUL would end the document early and hide what follows it), and + * object/array nesting deeper than json_max_depth. Brackets inside + * strings, escaped quotes included, are not counted. Returns 0 when + * cJSON may parse it. + */ +static int fts_json_guard(const char *json, int len) +{ + int i, depth = 0, in_string = 0; + + if (!json || len <= 0 || len > fts_json_max_bytes) + return -1; + if (memchr(json, '\0', (size_t)len)) + return -1; + + for (i = 0; i < len; i++) { + if (in_string) { + if (json[i] == '\\') + i++; /* the escaped byte */ + else if (json[i] == '"') + in_string = 0; + } else if (json[i] == '"') { + in_string = 1; + } else if (json[i] == '{' || json[i] == '[') { + if (++depth > fts_json_max_depth) + return -1; + } else if (json[i] == '}' || json[i] == ']') { + if (depth > 0) + depth--; + } + } + return 0; +} /** * parse_json_fields() — Extract top-level string fields from a JSON object. * - * Iterates over the top-level key/value pairs of a JSON object. For every - * pair whose value is a JSON string, the user-supplied @callback is invoked - * with the field name, field length, value, value length, and the opaque - * @ctx pointer. Non-string values (numbers, bools, nested objects/arrays) - * are silently skipped. + * Parses @json[0..@len) with cJSON (after fts_json_guard(); the buffer + * need not be NUL-terminated) and, for every top-level member whose value + * is a string, invokes @callback with the decoded field name and value + * and the opaque @ctx. Numbers, bools, null, arrays and nested objects + * are skipped. The whole document is refused (-1, no callback made) if + * it is not one JSON object, with nothing but whitespace after it, or if + * a name or value would not survive decoding (cJSON refuses "\u0000"). * * Callback mechanism: * The callback signature is: * void cb(const char *field, int flen, const char *val, int vlen, void *ctx) - * It is called synchronously for each string field while the JSON buffer - * is still valid. The field/val pointers reference the original @json - * buffer and must not be stored beyond the callback's lifetime. + * The field/val pointers reference the parsed tree. With @tree NULL the + * tree is freed on return, so they must not be kept past the callback. + * With @tree set, the tree is handed to the caller on success, and the + * pointers stay valid until the caller's fts_json_free(*tree). * - * Returns the number of string fields processed, or -1 on parse error. + * Returns the number of string fields processed, or -1 on error. */ static int parse_json_fields(const char *json, int len, void (*callback)(const char *field, int flen, const char *val, int vlen, void *ctx), - void *ctx) + void *ctx, cJSON **tree) { - const char *p = json; - const char *end = json + len; - const char *field, *val; - int flen, vlen; + char stackbuf[1024]; + char *buf; + cJSON *root, *it; int count = 0; - p = cdbn_skip_ws(p, end); - if (p >= end || *p != '{') + if (tree) + *tree = NULL; + if (fts_json_guard(json, len) < 0) return -1; - p++; /* skip '{' */ - while (1) { - p = cdbn_skip_ws(p, end); - if (p >= end) + /* cJSON needs a C string: copy, on the stack when it fits */ + if (len < (int)sizeof stackbuf) { + buf = stackbuf; + } else { + buf = malloc((size_t)len + 1); + if (!buf) { + LM_ERR("no system memory for %d-byte JSON parse copy\n", + len); return -1; - if (*p == '}') - break; - - /* expect comma between pairs (skip it) */ - if (*p == ',') { - p++; - p = cdbn_skip_ws(p, end); - if (p >= end) - return -1; } + } + memcpy(buf, json, len); + buf[len] = '\0'; - /* parse field name */ - p = cdbn_parse_json_string(p, end, &field, &flen); - if (!p) - return -1; - - /* expect colon */ - p = cdbn_skip_ws(p, end); - if (p >= end || *p != ':') - return -1; - p++; - if (p >= end) - return -1; - - /* check if value is a string */ - p = cdbn_skip_ws(p, end); - if (p >= end) - return -1; + root = fts_json_parse(buf); + if (buf != stackbuf) + free(buf); + if (!root) + return -1; + if ((root->type & 0xFF) != cJSON_Object) { + fts_json_free(root); + return -1; + } - if (*p == '"') { - /* string value — parse and invoke the caller's callback - * with field name + value slices from the original buffer */ - p = cdbn_parse_json_string(p, end, &val, &vlen); - if (!p) - return -1; - callback(field, flen, val, vlen, ctx); - count++; - } else { - /* non-string value — skip without invoking callback */ - p = cdbn_skip_json_value(p, end); - if (!p) - return -1; - } + cJSON_ArrayForEach(it, root) { + if ((it->type & 0xFF) != cJSON_String || !it->string + || !it->valuestring) + continue; + callback(it->string, (int)strlen(it->string), + it->valuestring, (int)strlen(it->valuestring), ctx); + count++; } + if (tree) + *tree = root; + else + fts_json_free(root); return count; } @@ -1229,6 +1335,7 @@ int nats_json_index_add(const char *key, int key_len, const char *json_str, int json_len) { _idx_fv_list_t list; + cJSON *doc; /* owns the field/value strings in list */ int rc, i; int was_present; int add_failed = 0; @@ -1249,9 +1356,10 @@ int nats_json_index_add(const char *key, int key_len, * is where the heavy lifting happens; running it unlocked lets * concurrent queries / removes / adds proceed. */ idx_fv_init(&list); - rc = parse_json_fields(json_str, json_len, collect_fv_cb, &list); + rc = parse_json_fields(json_str, json_len, collect_fv_cb, &list, &doc); if (rc < 0 || list.oom) { idx_fv_free(&list); + fts_json_free(doc); LM_WARN("failed to parse JSON for key '%s'\n", key); return -1; } @@ -1352,6 +1460,7 @@ int nats_json_index_add(const char *key, int key_len, free(rev_blob); idx_fv_free(&list); + fts_json_free(doc); LM_DBG("indexed key '%s' (%d fields)\n", key, rc); /* the other fields stay indexed (best effort); the caller learns @@ -1373,7 +1482,7 @@ static int index_add_into(nats_search_idx *target, const char *key, ctx.doc_key = key; ctx.doc_key_len = key_len; ctx.target = target; - rc = parse_json_fields(json_str, json_len, index_field_cb, &ctx); + rc = parse_json_fields(json_str, json_len, index_field_cb, &ctx, NULL); if (rc >= 0) atomic_fetch_add_explicit(&target->num_documents, 1, memory_order_relaxed); @@ -1487,7 +1596,7 @@ int nats_json_index_remove_fields(const char *key, int key_len, ctx.doc_key_len = key_len; ctx.removed_any = 0; rc = parse_json_fields(json_str, json_len, index_remove_field_cb, - &ctx); + &ctx, NULL); if (rc < 0) return -1; diff --git a/modules-contrib/cachedb_nats_fts/fts_index.h b/modules-contrib/cachedb_nats_fts/fts_index.h index 32e1459963d..69f148cff4f 100644 --- a/modules-contrib/cachedb_nats_fts/fts_index.h +++ b/modules-contrib/cachedb_nats_fts/fts_index.h @@ -37,6 +37,7 @@ typedef struct __kvStore kvStore; #include #include "../../cachedb/cachedb.h" +#include "../../sr_module.h" /* modparam_t */ #include /* @@ -169,6 +170,39 @@ typedef struct _nats_search_idx { */ int nats_json_index_init(void); +/* + * Limits on a document before cJSON parses it (modparams json_max_depth + * and json_max_bytes): a document nested deeper, or larger, is refused + * and not indexed. cJSON recurses once per nesting level, hence the + * depth ceiling. + */ +#define FTS_JSON_DEFAULT_MAX_DEPTH 64 +#define FTS_JSON_DEFAULT_MAX_BYTES (1 * 1024 * 1024) +#define FTS_JSON_DEPTH_CEILING 1024 +extern int fts_json_max_depth; +extern int fts_json_max_bytes; + +/* + * Check json_max_depth (1..FTS_JSON_DEPTH_CEILING) and json_max_bytes + * (at least 2, the size of "{}"). + * + * @return 0 when both are valid; -1, with an error logged, otherwise. + * + * Thread safety: reads the modparams only. Called from mod_init. + */ +int fts_json_check_limits(void); + +/* + * The json_max_depth / json_max_bytes modparam setters (INT_PARAM): check + * the value as the config is read, so that "opensips -C" reports a bad + * one, and store it. + * + * @return 0 when stored; -1, with an error logged and the value + * unchanged, when out of range. + */ +int fts_json_set_max_depth(modparam_t type, void *val); +int fts_json_set_max_bytes(modparam_t type, void *val); + /* * Build the search index from existing KV data. * diff --git a/modules-contrib/cachedb_nats_fts/test/fts_ut.h b/modules-contrib/cachedb_nats_fts/test/fts_ut.h index a67329b04f1..813a58a1867 100644 --- a/modules-contrib/cachedb_nats_fts/test/fts_ut.h +++ b/modules-contrib/cachedb_nats_fts/test/fts_ut.h @@ -36,6 +36,7 @@ void fts_ut_query(void); void fts_ut_revmap(void); void fts_ut_entry_oom(void); void fts_ut_index_partial_snapshot(void); +void fts_ut_json_parse(void); /* puts `t` in place of this process's intern table, returns the old one */ void *fts_ut_intern_swap(void *t); diff --git a/modules-contrib/cachedb_nats_fts/test/test.c b/modules-contrib/cachedb_nats_fts/test/test.c index 7052668467c..03c3eb48adc 100644 --- a/modules-contrib/cachedb_nats_fts/test/test.c +++ b/modules-contrib/cachedb_nats_fts/test/test.c @@ -38,4 +38,5 @@ void mod_tests(void) fts_ut_revmap(); fts_ut_entry_oom(); fts_ut_index_partial_snapshot(); + fts_ut_json_parse(); } diff --git a/modules-contrib/cachedb_nats_fts/test/test_index_partial_snapshot.c b/modules-contrib/cachedb_nats_fts/test/test_index_partial_snapshot.c index 71b302b8675..3de7a4c81fe 100644 --- a/modules-contrib/cachedb_nats_fts/test/test_index_partial_snapshot.c +++ b/modules-contrib/cachedb_nats_fts/test/test_index_partial_snapshot.c @@ -162,9 +162,9 @@ void fts_ut_index_partial_snapshot(void) ASSERT(nats_json_index_init() == 0, "index init"); /* seed the LIVE index with two complete documents */ - ASSERT(nats_json_index_add("doc.a1", 6, "{\"aor\":\"alice\"}", 16) == 0, + ASSERT(nats_json_index_add("doc.a1", 6, "{\"aor\":\"alice\"}", 15) == 0, "seed doc a1"); - ASSERT(nats_json_index_add("doc.a2", 6, "{\"aor\":\"anna\"}", 15) == 0, + ASSERT(nats_json_index_add("doc.a2", 6, "{\"aor\":\"anna\"}", 14) == 0, "seed doc a2"); ASSERT(nats_json_index_count() == 2, "live index holds 2 documents"); diff --git a/modules-contrib/cachedb_nats_fts/test/test_json_parse.c b/modules-contrib/cachedb_nats_fts/test/test_json_parse.c new file mode 100644 index 00000000000..dcb66b3a4d0 --- /dev/null +++ b/modules-contrib/cachedb_nats_fts/test/test_json_parse.c @@ -0,0 +1,506 @@ +/* + * Copyright (C) 2026 OpenSIPS Solutions + * + * This file is part of opensips, a free SIP server. + * + * opensips is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * opensips is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + * Documents are parsed with the core's cJSON (lib/cJSON.h), so this + * module needs nothing of cachedb_nats's JSON code (GitHub #4501: + * cachedb_nats was opened RTLD_GLOBAL only to share it, and that put its + * "exports" in place of rtpengine's). Through nats_json_index_add() and + * the query, on a private index: every top-level string field is indexed + * with its value decoded; any other value is skipped; a document that is + * malformed, too deep, too large or carries a NUL is refused whole and + * leaves the index as it was. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "../../../sr_module.h" +#include "../../../cachedb/cachedb_types.h" +#include "../fts_index.h" +#include "../fts_intern.h" + +#include "fts_ut.h" + +#define CHECK(cond, ...) ok((cond), "json_parse: " __VA_ARGS__) + +/* number of documents the query field=value matches; -1 on error */ +static int matches(const char *field, int flen, const char *value, int vlen) +{ + cdb_filter_t f; + char **out = NULL; + int n = -1; + + memset(&f, 0, sizeof f); + f.key.name.s = (char *)field; + f.key.name.len = flen; + f.op = CDB_OP_EQ; + f.val.is_str = 1; + f.val.s.s = (char *)value; + f.val.s.len = vlen; + if (fts_query_match_keys(&f, &out, &n) < 0) + return -1; + fts_release_keyset(out, n); + return n; +} + +#define M(field, value) matches(field, (int)strlen(field), \ + value, (int)strlen(value)) + +static int add(const char *key, const char *doc, int len) +{ + return nats_json_index_add(key, (int)strlen(key), doc, len); +} + +#define ADD(key, doc) add(key, doc, (int)sizeof(doc) - 1) + +static void indexed(void) +{ + /* the buffer is not NUL-terminated past json_len: "zz" follows */ + static const char unterminated[] = "{\"t\":\"u\"}zz"; + + CHECK(ADD("p.plain", " \n{ \"f\" : \"x\", \"n\": 12, \"b\": true, " + "\"z\": null, \"a\": [\"x\"], \"o\": {\"inner\": \"y\"} }\t") == 0, + "a plain document is indexed"); + CHECK(M("f", "x") == 1, "its top-level string field is found"); + CHECK(M("n", "12") == 0 && M("b", "true") == 0 && M("z", "null") == 0, + "number, bool and null values are not indexed"); + CHECK(M("a", "x") == 0, "an array value is not indexed"); + CHECK(M("o", "{\"inner\": \"y\"}") == 0 && M("inner", "y") == 0, + "a nested object is not indexed, nor its own fields"); + + CHECK(ADD("p.esc", "{\"q\":\"a\\\"b\",\"bs\":\"c:\\\\dir\"," + "\"nl\":\"l1\\nl2\",\"sl\":\"a\\/b\"}") == 0, + "a document with escaped values is indexed"); + CHECK(M("q", "a\"b") == 1, "an escaped quote is decoded"); + CHECK(M("q", "a\\\"b") == 0, "... and the raw escape is not indexed"); + CHECK(M("bs", "c:\\dir") == 1, "an escaped backslash is decoded"); + CHECK(M("nl", "l1\nl2") == 1, "an escaped newline is decoded"); + CHECK(M("sl", "a/b") == 1, "an escaped slash is decoded"); + + CHECK(ADD("p.uni", "{\"u\":\"caf\\u00e9\",\"k\\\"ey\":\"v\"}") == 0, + "a document with a \\u escape and an escaped field name is indexed"); + CHECK(M("u", "caf\xc3\xa9") == 1, "a \\u escape is decoded to UTF-8"); + CHECK(M("k\"ey", "v") == 1, "an escaped field name is decoded"); + + CHECK(ADD("p.special", "{\"uri\":\"sip:alice@example.com;tag=a:b=c\"," + "\"e\":\"\",\"sp\":\" two words \"}") == 0, + "a document with ':', '=', ';', empty and spaced values is indexed"); + CHECK(M("uri", "sip:alice@example.com;tag=a:b=c") == 1, + "a value with ':' '=' ';' '@' is found whole"); + CHECK(M("sp", " two words ") == 1, "inner and edge spaces are kept"); + + CHECK(add("p.unterm", unterminated, (int)sizeof unterminated - 3) == 0, + "a document is parsed up to json_len, not up to a NUL"); + CHECK(M("t", "u") == 1, "... and indexed"); + + CHECK(ADD("p.empty", "{}") == 0, "an empty object is a valid document"); +} + +/* nats_json_index_add() refuses @doc[0..len) and the index is unchanged */ +static void refused(const char *what, const char *doc, int len) +{ + int before; + + /* independent cases: drop what an earlier case may have let in */ + nats_json_index_remove("r.doc", 5); + before = nats_json_index_count(); + CHECK(add("r.doc", doc, len) == -1, "refused: %s", what); + CHECK(nats_json_index_count() == before && M("r", "x") == 0, + "... and nothing of it is indexed"); +} + +#define REFUSED(what, doc) refused(what, doc, (int)sizeof(doc) - 1) + +static void rejected(void) +{ + static const char raw_nul[] = "{\"r\":\"x\",\"n\":\"a\0b\"}"; + char deep[300], *p; + char *big; + int i; + + REFUSED("a \\u0000 escape (would truncate the value)", + "{\"r\":\"x\",\"n\":\"a\\u0000b\"}"); + refused("a raw NUL byte", raw_nul, (int)sizeof raw_nul - 1); + REFUSED("a missing value", "{\"r\":\"x\",\"a\":"); + REFUSED("a missing colon", "{\"r\":\"x\",\"a\" \"b\"}"); + REFUSED("an unterminated string", "{\"r\":\"x\",\"a\":\"b}"); + REFUSED("an unterminated object", "{\"r\":\"x\""); + REFUSED("a bad escape", "{\"r\":\"x\",\"a\":\"\\q\"}"); + REFUSED("text after the object", "{\"r\":\"x\"} trailing"); + REFUSED("a second object", "{\"r\":\"x\"}{\"r\":\"x\"}"); + REFUSED("a top-level array", "[{\"r\":\"x\"}]"); + REFUSED("a top-level string", "\"r\""); + REFUSED("only whitespace", " \t\n"); + refused("an empty buffer", "", 0); + CHECK(nats_json_index_add("r.doc", 5, NULL, 4) == -1, + "refused: a NULL buffer"); + + /* nesting: 64 levels pass, 65 are refused before cJSON recurses */ + p = deep; + p += sprintf(p, "{\"r\":\"y\",\"d\":"); + for (i = 0; i < 63; i++) + *p++ = '['; + for (i = 0; i < 63; i++) + *p++ = ']'; + *p++ = '}'; + CHECK(add("r.deep64", deep, (int)(p - deep)) == 0 && M("r", "y") == 1, + "64 levels of nesting are indexed"); + + p = deep; + p += sprintf(p, "{\"r\":\"x\",\"d\":"); + for (i = 0; i < 64; i++) + *p++ = '['; + for (i = 0; i < 64; i++) + *p++ = ']'; + *p++ = '}'; + refused("65 levels of nesting", deep, (int)(p - deep)); + + /* brackets inside strings do not count as nesting */ + p = deep; + p += sprintf(p, "{\"r\":\"z\",\"s\":\""); + for (i = 0; i < 100; i++) + *p++ = '['; + p += sprintf(p, "\"}"); + CHECK(add("r.strbr", deep, (int)(p - deep)) == 0 && M("r", "z") == 1, + "brackets inside a string are not nesting"); + + /* larger than NATS's default max_payload (1 MiB) */ + big = malloc((1 << 20) + 32); + if (big) { + p = big; + p += sprintf(p, "{\"r\":\"x\",\"v\":\""); + memset(p, 'a', (1 << 20)); + p += (1 << 20); + p += sprintf(p, "\"}"); + refused("a document over 1 MiB", big, (int)(p - big)); + free(big); + } +} + +static struct { const char *doc; int len; } ceil_ctx; + +static void *ceil_thread(void *arg) +{ + *(int *)arg = add("l.ceil", ceil_ctx.doc, ceil_ctx.len); + return NULL; +} + +/* json_max_depth / json_max_bytes: the guard's limits are the modparams */ +static void limits(void) +{ + int depth = fts_json_max_depth, bytes = fts_json_max_bytes; + /* 3 levels: {"r":"l","d":[[]]} ; 4 levels: {"r":"l","d":[[[]]]} */ + static const char d3[] = "{\"r\":\"l\",\"d\":[[]]}"; + static const char d4[] = "{\"r\":\"l\",\"d\":[[[]]]}"; + /* exactly 20 bytes, then 21 */ + static const char b20[] = "{\"r\":\"m\",\"x\":\"1234\"}"; + static const char b21[] = "{\"r\":\"m\",\"x\":\"12345\"}"; + + CHECK(depth == 64 && bytes == 1024 * 1024, + "default limits: depth 64, 1 MiB (%d, %d)", depth, bytes); + CHECK(fts_json_check_limits() == 0, "the default limits are valid"); + + fts_json_max_depth = 3; + CHECK(ADD("l.d3", d3) == 0 && M("r", "l") == 1, + "json_max_depth 3: 3 levels are indexed"); + nats_json_index_remove("l.d3", 4); + CHECK(ADD("l.d4", d4) == -1 && M("r", "l") == 0, + "json_max_depth 3: 4 levels are refused"); + fts_json_max_depth = depth; + CHECK(ADD("l.d4", d4) == 0, "back at the default, 4 levels pass"); + nats_json_index_remove("l.d4", 4); + + CHECK(sizeof b20 - 1 == 20 && sizeof b21 - 1 == 21, "probe sizes"); + fts_json_max_bytes = 20; + CHECK(ADD("l.b20", b20) == 0 && M("r", "m") == 1, + "json_max_bytes 20: a 20-byte document is indexed"); + nats_json_index_remove("l.b20", 5); + CHECK(ADD("l.b21", b21) == -1 && M("r", "m") == 0, + "json_max_bytes 20: a 21-byte document is refused"); + fts_json_max_bytes = bytes; + CHECK(ADD("l.b21", b21) == 0, "back at the default, 21 bytes pass"); + nats_json_index_remove("l.b21", 5); + + /* the ceiling is safe: a document exactly 1024 deep parses, on this + * process's stack and on a thread's */ + { + static char ceil_doc[16 + 2 * FTS_JSON_DEPTH_CEILING]; + pthread_t th; + int i, n = 0, rc = -1; + + n += sprintf(ceil_doc, "{\"r\":\"c\",\"d\":"); + for (i = 1; i < FTS_JSON_DEPTH_CEILING; i++) + ceil_doc[n++] = '['; + for (i = 1; i < FTS_JSON_DEPTH_CEILING; i++) + ceil_doc[n++] = ']'; + ceil_doc[n++] = '}'; + ceil_ctx.doc = ceil_doc; + ceil_ctx.len = n; + + fts_json_max_depth = FTS_JSON_DEPTH_CEILING; + CHECK(add("l.ceil", ceil_doc, n) == 0 && M("r", "c") == 1, + "json_max_depth %d: a document that deep is indexed", + FTS_JSON_DEPTH_CEILING); + nats_json_index_remove("l.ceil", 6); + if (pthread_create(&th, NULL, ceil_thread, &rc) == 0) + pthread_join(th, NULL); + CHECK(rc == 0 && M("r", "c") == 1, + "... and from a thread"); + nats_json_index_remove("l.ceil", 6); + fts_json_max_depth = depth; + } + + /* mod_init refuses what cannot work: a depth below the top-level + * object, a size below "{}", a depth deep enough to exhaust the + * stack in cJSON's recursion */ + { + static const struct { int depth, bytes, valid; const char *what; } + cases[] = { + { 0, 1024, 0, "json_max_depth 0" }, + { -1, 1024, 0, "a negative json_max_depth" }, + { 1, 1024, 1, "json_max_depth 1 (the top-level object)" }, + { 1024, 1024, 1, "json_max_depth 1024 (the ceiling)" }, + { 1025, 1024, 0, "json_max_depth 1025 (over the ceiling)" }, + { 64, 0, 0, "json_max_bytes 0" }, + { 64, -5, 0, "a negative json_max_bytes" }, + { 64, 1, 0, "json_max_bytes 1 (smaller than \"{}\")" }, + { 64, 2, 1, "json_max_bytes 2" }, + { 64, INT_MAX, 1, "json_max_bytes INT_MAX" }, + }; + unsigned i; + + for (i = 0; i < sizeof cases / sizeof cases[0]; i++) { + fts_json_max_depth = cases[i].depth; + fts_json_max_bytes = cases[i].bytes; + CHECK((fts_json_check_limits() == 0) == cases[i].valid, + "%s is %s", cases[i].what, + cases[i].valid ? "accepted" : "refused at startup"); + } + fts_json_max_depth = depth; + fts_json_max_bytes = bytes; + } + + /* the modparam setters refuse a bad value as the config is read + * (so "opensips -C" reports it), keeping the previous value */ + { + static const struct { int depth; int ok; } dc[] = { + { 0, 0 }, { -3, 0 }, { 1025, 0 }, { INT_MIN, 0 }, + { 1, 1 }, { 16, 1 }, { 1024, 1 }, + }; + static const struct { int bytes; int ok; } bc[] = { + { 0, 0 }, { 1, 0 }, { -1, 0 }, { INT_MIN, 0 }, + { 2, 1 }, { 4096, 1 }, { INT_MAX, 1 }, + }; + unsigned i; + int prev, rc; + + for (i = 0; i < sizeof dc / sizeof dc[0]; i++) { + prev = fts_json_max_depth; + rc = fts_json_set_max_depth(INT_PARAM, (void *)(long)dc[i].depth); + CHECK(dc[i].ok ? (rc == 0 && fts_json_max_depth == dc[i].depth) + : (rc < 0 && fts_json_max_depth == prev), + "modparam json_max_depth %d is %s", dc[i].depth, + dc[i].ok ? "set" : "refused, the value kept"); + } + for (i = 0; i < sizeof bc / sizeof bc[0]; i++) { + prev = fts_json_max_bytes; + rc = fts_json_set_max_bytes(INT_PARAM, (void *)(long)bc[i].bytes); + CHECK(bc[i].ok ? (rc == 0 && fts_json_max_bytes == bc[i].bytes) + : (rc < 0 && fts_json_max_bytes == prev), + "modparam json_max_bytes %d is %s", bc[i].bytes, + bc[i].ok ? "set" : "refused, the value kept"); + } + fts_json_max_depth = depth; + fts_json_max_bytes = bytes; + } +} + +/* The index is used from threads (its lists use malloc, its locks are + * shards): parsing must not touch the process's pkg memory. Each thread + * adds and removes its own documents, over 1 KiB (the heap copy) and + * with escapes (the decoding), while the others do the same. */ +#define THREADS 4 +#define PER_THREAD 100 + +static int thread_failures; + +static void *churn(void *arg) +{ + long t = (long)arg; + char key[32], doc[2048], *p; + int i, bad = 0; + + for (i = 0; i < PER_THREAD; i++) { + snprintf(key, sizeof key, "th.%ld.%d", t, i); + p = doc; + p += sprintf(p, "{\"th\":\"t%ld \\\"q\\\"\",\"pad\":\"", t); + memset(p, 'p', 1500); + p += 1500; + p += sprintf(p, "\"}"); + if (add(key, doc, (int)(p - doc)) != 0) + bad++; + if (nats_json_index_remove_by_revmap(key, (int)strlen(key)) != 0) + bad++; + } + __atomic_add_fetch(&thread_failures, bad, __ATOMIC_RELAXED); + return NULL; +} + +static void threads(void) +{ + pthread_t th[THREADS]; + int i, n = 0, before = nats_json_index_count(); + char doc[2048], *p; + + for (i = 0; i < THREADS; i++) + if (pthread_create(&th[i], NULL, churn, (void *)(long)i) == 0) + n++; + for (i = 0; i < n; i++) + pthread_join(th[i], NULL); + CHECK(n == THREADS && thread_failures == 0, + "%d threads index and remove documents over 1 KiB (%d failures)", + THREADS, thread_failures); + CHECK(nats_json_index_count() == before && M("th", "t0 \"q\"") == 0, + "... and leave the index as it was"); + + /* the same document from this thread: decoded and found */ + p = doc; + p += sprintf(p, "{\"th\":\"t9 \\\"q\\\"\",\"pad\":\""); + memset(p, 'p', 1500); + p += 1500; + p += sprintf(p, "\"}"); + CHECK(add("th.main", doc, (int)(p - doc)) == 0 + && M("th", "t9 \"q\"") == 1, + "a document over 1 KiB is indexed with its value decoded"); +} + +static const struct sr_module *module(const char *name) +{ + const struct sr_module *m; + + for (m = modules; m; m = m->next) + if (m->exports && m->exports->name + && !strcmp(m->exports->name, name)) + return m; + return NULL; +} + +/* this module takes nothing from cachedb_nats's JSON code, and nothing of + * cachedb_nats resolves in the global scope */ +static void scope(void) +{ + const struct sr_module *cdb = module("cachedb_nats"); + const struct sr_module *fts = module("cachedb_nats_fts"); + /* the main program's handle searches the global scope only */ + void *main_h = dlopen(NULL, RTLD_NOW); + + CHECK(find_export("cdbn_json_bind", 0) == NULL, + "no cdbn_json_bind command: the walkers are not shared"); + CHECK(cdb && fts && main_h, "cachedb_nats and cachedb_nats_fts loaded"); + if (!cdb || !fts || !main_h) + return; + CHECK(dlsym(main_h, "exports") != (void *)cdb->exports, + "the global-scope exports is not cachedb_nats's"); + CHECK(dlsym(main_h, "cdbn_skip_ws") == NULL, + "cdbn_skip_ws does not resolve in the global scope"); + /* the module's own scope: itself and its dependencies (the handle + * form is POSIX; RTLD_DEFAULT is a GNU extension) */ + CHECK(dlsym(fts->handle, "cdbn_skip_ws") == NULL, + "nor in cachedb_nats_fts.so and its dependencies"); + dlclose(main_h); +} + +/* The README documents every exported parameter with its real default: + * a "#### (integer)" section whose "*Default value is "N"" line + * holds the value the module starts with (the test config sets none). */ +static void readme_params(void) +{ + const struct sr_module *fts = module("cachedb_nats_fts"); + const param_export_t *pe; + FILE *f; + static char doc[64 * 1024]; + size_t n; + + f = fopen("modules-contrib/cachedb_nats_fts/README.md", "r"); + CHECK(f != NULL, "README.md readable from the source tree"); + if (!f || !fts) + return; + n = fread(doc, 1, sizeof doc - 1, f); + fclose(f); + doc[n] = '\0'; + CHECK(n > 0 && n < sizeof doc - 1, "README.md read whole (%zu bytes)", n); + + for (pe = fts->exports->params; pe && pe->name; pe++) { + char head[128], want[64]; + const char *h, *d, *next; + const int *var = pe->param_pointer; + + /* a setter-backed parameter: its variable */ + if (pe->type & USE_FUNC_PARAM) + var = !strcmp(pe->name, "json_max_depth") ? &fts_json_max_depth + : !strcmp(pe->name, "json_max_bytes") ? &fts_json_max_bytes + : NULL; + CHECK(var != NULL, "%s: its value can be read", pe->name); + if (!var) + continue; + + snprintf(head, sizeof head, "\n#### %s (integer)\n", pe->name); + h = strstr(doc, head); + CHECK(h != NULL, "README documents %s", pe->name); + if (!h) + continue; + /* the default must be stated inside this section */ + next = strstr(h + strlen(head), "\n#### "); + snprintf(want, sizeof want, "*Default value is \"%d\"", *var); + d = strstr(h, want); + CHECK(d != NULL && (!next || d < next), + "README gives %s's default as %d", pe->name, *var); + } +} + +void fts_ut_json_parse(void) +{ + nats_search_idx *live_idx = NULL; + void *live_rev = NULL; + void *live_intern; + int okay; + + fts_ut_index_swap(&live_idx, &live_rev); + live_intern = fts_ut_intern_swap(NULL); + okay = nats_intern_init(64) == 0 && nats_json_index_init() == 0; + CHECK(okay, "a private index"); + if (okay) { + indexed(); + rejected(); + limits(); + threads(); + } + nats_json_index_destroy(); + nats_intern_destroy(); + fts_ut_index_swap(&live_idx, &live_rev); + fts_ut_intern_swap(live_intern); + + scope(); + readme_params(); +} diff --git a/modules-contrib/nats/README.md b/modules-contrib/nats/README.md index 8d23a28cc66..93de25f6cd0 100644 --- a/modules-contrib/nats/README.md +++ b/modules-contrib/nats/README.md @@ -29,8 +29,7 @@ own. The three modules that talk to NATS (*event_nats*, *cachedb_nats*, Load `nats.so` and the modules you need. *event_nats*, *cachedb_nats* and *nats_consumer* each run on their own, and any combination shares the same connection; *cachedb_nats_fts* needs *cachedb_nats*. Load -order does not matter, except that *cachedb_nats_fts* must be loaded -after *cachedb_nats*: each NATS module declares a dependency on *nats*, +order does not matter: each NATS module declares a dependency on *nats*, so OpenSIPS initializes *nats* first, and a configuration that loads a NATS module without `nats.so` does not start: