json-c: accept a bare number or boolean, refuse a bare null

The five header setters (jwt_signature_add_protected_json,
jwt_signature_add_header_json, jwe_builder_add_protected_json,
jwe_builder_add_unprotected_json, jwe_recipient_add_header_json) parse the
value with jwt_json_parse(..., JWT_JSON_DECODE_ANY, ...). With json-c a
bare number or literal has no closing delimiter, so json-c cannot tell it
has ended and reports json_tokener_continue, which the wrapper took for a
parse error: 1, -1, 1.5, true and false were refused, though Jansson (and
the documented contract of these setters) accepts them.

Give json-c the end of the input it needs: jwt_json_parse() parses a C
string with slen + 1 so the terminating NUL is included, and
jwt_json_parse_buf(), whose buffer is not NUL-terminated, ends its input
with a second json_tokener_parse_ex() call on a lone NUL when the first
returns json_tokener_continue. That second call restarts json-c's
parse-end counter, so validate_parsed() now takes the parse end from the
first call rather than reading it from the tokener.

A bare JSON null is refused by both backends: json-c has no object to
store one (it represents a null as a C NULL, which every caller reads as
absent), so the Jansson parser is made to refuse a top-level null too,
rather than silently accept one the json-c backend cannot. Only a
DECODE_ANY caller can reach that path; the default mode already rejects a
top-level non-array/object. The documented accepted-types list for
jwe_builder_add_protected_json() notes that null is refused.

Tested under both JSON backends for all five setters: numbers and
booleans are accepted and emitted as JSON scalars, a bare null and
trailing data (1 2, {} x) are refused.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Signed-off-by: Ben Collins <bcollins@libjwt.io>
diff --git a/include/jwt.h b/include/jwt.h
index 3a5d07c..2ea6137 100644
--- a/include/jwt.h
+++ b/include/jwt.h
@@ -2642,9 +2642,10 @@
  *
  * @p value_json is parsed as JSON, so a string value must include its quotes
  * (the four-byte fragment quote-p-r-o-d-quote for the string @c prod); objects,
- * arrays, numbers and booleans are accepted as written. The same parameter name
- * must not also appear in the shared unprotected or any per-recipient header
- * (@rfc{7516,7.2.1}).
+ * arrays, numbers and booleans are accepted as written. A bare ``null`` is
+ * refused (the json-c backend cannot store one, so both backends refuse it
+ * alike). The same parameter name must not also appear in the shared
+ * unprotected or any per-recipient header (@rfc{7516,7.2.1}).
  *
  * @param builder Pointer to a JWE builder object
  * @param key The header parameter name
diff --git a/libjwt/jansson/jwt-jansson.c b/libjwt/jansson/jwt-jansson.c
index 8fdec26..536d3c3 100644
--- a/libjwt/jansson/jwt-jansson.c
+++ b/libjwt/jansson/jwt-jansson.c
@@ -333,6 +333,18 @@
 	if (!obj && error)
 		map_error(error, &jerr);
 
+	/* json-c has no object for a bare JSON null (it represents one as a C
+	 * NULL, which every jwt_json_* caller reads as absent/failure), so the
+	 * JSON header setters refuse one with json-c. Refuse it here too, so the
+	 * two backends agree. Only a DECODE_ANY caller reaches this: the default
+	 * mode already rejects a top-level value that is not an array or object,
+	 * and the setters pass a NULL error, so no message is set (the setter
+	 * reports its own). */
+	if (obj && json_is_null(obj)) {
+		json_decref(obj);
+		return NULL;
+	}
+
 	return from_json(obj);
 }
 
diff --git a/libjwt/json-c/jwt-json-c.c b/libjwt/json-c/jwt-json-c.c
index aa6402c..e8be442 100644
--- a/libjwt/json-c/jwt-json-c.c
+++ b/libjwt/json-c/jwt-json-c.c
@@ -684,24 +684,25 @@
 /**
  * Common post-parse validation for all parse functions.
  * Checks trailing garbage and enforces DECODE_ANY semantics.
+ *
+ * @parse_end is the offset one past the last byte json-c consumed. The caller
+ * passes it in rather than reading it from the tokener, because the buffer
+ * parser may call json_tokener_parse_ex() a second time (to end a bare scalar)
+ * and that resets json-c's parse-end counter.
  */
-static jwt_json_t *validate_parsed(struct json_tokener *tok,
-				   struct json_object *obj,
-				   size_t input_len, size_t flags,
-				   const char *source,
+static jwt_json_t *validate_parsed(struct json_object *obj,
+				   size_t parse_end, size_t input_len,
+				   size_t flags, const char *source,
 				   jwt_json_error_t *error)
 {
 	/* Reject trailing garbage */
-	if (json_tokener_get_parse_end(tok) < input_len) {
+	if (parse_end < input_len) {
 		set_error(error, source, "Trailing data after JSON value");
-		json_tokener_free(tok);
 		if (obj)
 			json_object_put(obj);
 		return NULL;
 	}
 
-	json_tokener_free(tok);
-
 	/* Without DECODE_ANY, only accept objects and arrays
 	 * (matches jansson default behavior) */
 	if (!(flags & JWT_JSON_DECODE_ANY)) {
@@ -732,6 +733,7 @@
 	struct json_object *obj;
 	enum json_tokener_error jerr;
 	const char *scan_err;
+	size_t parse_end;
 
 	if (!input) {
 		set_error(error, "<string>", "NULL input");
@@ -739,7 +741,7 @@
 	}
 
 	size_t slen = strlen(input);
-	if (slen > INT_MAX) {
+	if (slen >= INT_MAX) {
 		set_error(error, "<string>", "Input too large");
 		return NULL;
 	}
@@ -756,19 +758,22 @@
 		return NULL;
 	}
 
-	obj = json_tokener_parse_ex(tok, input, (int)slen);
+	/* Pass slen + 1 so json-c sees the terminating NUL and can end a bare
+	 * scalar (a number or a literal) that has no closing delimiter. */
+	obj = json_tokener_parse_ex(tok, input, (int)(slen + 1));
 	jerr = json_tokener_get_error(tok);
+	parse_end = json_tokener_get_parse_end(tok);
+	json_tokener_free(tok);
 
 	if (jerr != json_tokener_success) {
 		set_error(error, "<string>",
 			  json_tokener_error_desc(jerr));
-		json_tokener_free(tok);
 		if (obj)
 			json_object_put(obj);
 		return NULL;
 	}
 
-	return validate_parsed(tok, obj, slen, flags, "<string>", error);
+	return validate_parsed(obj, parse_end, slen, flags, "<string>", error);
 }
 
 jwt_json_t *jwt_json_parse_buf(const char *buffer, size_t buflen,
@@ -778,6 +783,7 @@
 	struct json_object *obj;
 	enum json_tokener_error jerr;
 	const char *scan_err;
+	size_t parse_end;
 
 	if (!buffer) {
 		set_error(error, "<buffer>", "NULL buffer");
@@ -803,17 +809,30 @@
 
 	obj = json_tokener_parse_ex(tok, buffer, (int)buflen);
 	jerr = json_tokener_get_error(tok);
+	parse_end = json_tokener_get_parse_end(tok);
+
+	/* A bare scalar at the exact end of the buffer has no delimiter, so
+	 * json-c cannot tell it has ended and asks for more input. The buffer
+	 * is not NUL-terminated, so signal the end with a lone NUL, as a C
+	 * string's terminator would. The second call restarts json-c's
+	 * parse-end counter, so the trailing-data check uses the end saved
+	 * from the first call. */
+	if (jerr == json_tokener_continue) {
+		obj = json_tokener_parse_ex(tok, "", 1);
+		jerr = json_tokener_get_error(tok);
+	}
+	json_tokener_free(tok);
 
 	if (jerr != json_tokener_success) {
 		set_error(error, "<buffer>",
 			  json_tokener_error_desc(jerr));
-		json_tokener_free(tok);
 		if (obj)
 			json_object_put(obj);
 		return NULL;
 	}
 
-	return validate_parsed(tok, obj, buflen, flags, "<buffer>", error);
+	return validate_parsed(obj, parse_end, buflen, flags, "<buffer>",
+			       error);
 }
 
 jwt_json_t *jwt_json_parse_file(const char *path, size_t flags,
diff --git a/tests/jwe_json.c b/tests/jwe_json.c
index ad14723..30dbc68 100644
--- a/tests/jwe_json.c
+++ b/tests/jwe_json.c
@@ -236,6 +236,67 @@
 }
 END_TEST
 
+/* #358: a bare number or boolean value is accepted (and emitted as a JSON
+ * scalar), a bare null and trailing data are refused - alike on both JSON
+ * backends. json-c used to refuse numbers/booleans (its tokener needs the
+ * terminating NUL to end a value with no delimiter), and Jansson used to
+ * accept a null json-c cannot store. */
+START_TEST(json_scalar_header_values)
+{
+	static const char * const ok[] = { "1", "-1", "1.5", "true", "false" };
+	static const char * const bad[] = { "null", "1 2", "{} x" };
+	size_t i;
+
+	SET_OPS();
+	read_json("oct_key_256_enc.json");
+
+	for (i = 0; i < ARRAY_SIZE(ok); i++) {
+		jwe_builder_auto_t *b = jwe_builder_new();
+
+		ck_assert_int_eq(jwe_builder_setkey(b, JWE_ALG_A256KW,
+						    JWE_ENC_A256GCM, g_item), 0);
+		ck_assert_int_eq(jwe_builder_add_protected_json(b, "p", ok[i]),
+				 0);
+		ck_assert_int_eq(jwe_builder_add_unprotected_json(b, "u",
+								  ok[i]), 0);
+	}
+
+	for (i = 0; i < ARRAY_SIZE(bad); i++) {
+		jwe_builder_auto_t *b = jwe_builder_new();
+
+		ck_assert_int_eq(jwe_builder_setkey(b, JWE_ALG_A256KW,
+						    JWE_ENC_A256GCM, g_item), 0);
+		ck_assert_int_ne(jwe_builder_add_protected_json(b, "p", bad[i]),
+				 0);
+		jwe_builder_error_clear(b);
+		ck_assert_int_ne(jwe_builder_add_unprotected_json(b, "u",
+								  bad[i]), 0);
+	}
+
+	/* A number and a boolean are emitted as JSON scalars, not strings. */
+	{
+		jwe_builder_auto_t *b = jwe_builder_new();
+		char_auto *tok = NULL;
+
+		ck_assert_int_eq(jwe_builder_setkey(b, JWE_ALG_A256KW,
+						    JWE_ENC_A256GCM, g_item), 0);
+		ck_assert_int_eq(jwe_builder_set_format(b,
+							JWE_FORMAT_JSON_FLAT), 0);
+		ck_assert_int_eq(jwe_builder_add_unprotected_json(b, "n", "1"),
+				 0);
+		ck_assert_int_eq(jwe_builder_add_unprotected_json(b, "y",
+								  "true"), 0);
+		tok = jwe_builder_generate(b, (const unsigned char *)PT,
+					   strlen(PT));
+		ck_assert_ptr_nonnull(tok);
+		ck_assert_ptr_nonnull(strstr(tok, "\"n\":1"));
+		ck_assert_ptr_nonnull(strstr(tok, "\"y\":true"));
+	}
+
+	free_key();
+}
+END_TEST
+
 /* The Compact Serialization cannot carry a shared unprotected header or aad. */
 START_TEST(compact_rejects_json_only)
 {
@@ -503,6 +564,7 @@
 	tcase_add_loop_test(tc_core, alg_in_recipient_header, 0, i);
 	tcase_add_loop_test(tc_core, app_headers, 0, i);
 	tcase_add_loop_test(tc_core, reserved_header_rejected, 0, i);
+	tcase_add_loop_test(tc_core, json_scalar_header_values, 0, i);
 	tcase_add_loop_test(tc_core, compact_rejects_json_only, 0, i);
 	tcase_add_loop_test(tc_core, bad_format_rejected, 0, i);
 	tcase_add_loop_test(tc_core, json_structural_negatives, 0, i);
diff --git a/tests/jwe_multi.c b/tests/jwe_multi.c
index df1685b..fe68aa0 100644
--- a/tests/jwe_multi.c
+++ b/tests/jwe_multi.c
@@ -214,6 +214,17 @@
 	ck_assert_int_ne(jwe_recipient_add_header_json(r, "x", NULL), 0);
 	ck_assert_int_ne(jwe_recipient_add_header_json(r, "x", "{bad json"), 0);
 
+	/* #358: a bare number or boolean is accepted, a bare null and trailing
+	 * data are refused - alike on both JSON backends. */
+	ck_assert_int_eq(jwe_recipient_add_header_json(r, "n1", "1"), 0);
+	ck_assert_int_eq(jwe_recipient_add_header_json(r, "n2", "-1"), 0);
+	ck_assert_int_eq(jwe_recipient_add_header_json(r, "n3", "1.5"), 0);
+	ck_assert_int_eq(jwe_recipient_add_header_json(r, "b1", "true"), 0);
+	ck_assert_int_eq(jwe_recipient_add_header_json(r, "b2", "false"), 0);
+	ck_assert_int_ne(jwe_recipient_add_header_json(r, "z1", "null"), 0);
+	ck_assert_int_ne(jwe_recipient_add_header_json(r, "z2", "1 2"), 0);
+	ck_assert_int_ne(jwe_recipient_add_header_json(r, "z3", "{} x"), 0);
+
 	free_key();
 }
 END_TEST
diff --git a/tests/jws_json.c b/tests/jws_json.c
index 4ce15ff..5061e07 100644
--- a/tests/jws_json.c
+++ b/tests/jws_json.c
@@ -429,6 +429,75 @@
 }
 END_TEST
 
+/* #358: a per-signature header value that is a bare number or boolean is
+ * accepted (and emitted as a JSON scalar), a bare null and trailing data are
+ * refused - alike on both JSON backends. */
+START_TEST(test_sig_scalar_header)
+{
+	jwk_set_t *eks;
+	const jwk_item_t *ec;
+	static const char * const ok[] = { "1", "-1", "1.5", "true", "false" };
+	static const char * const bad[] = { "null", "1 2", "{} x" };
+	size_t i;
+
+	SET_OPS();
+
+	eks = load_one("ec_key_prime256v1.json");
+	ec = jwks_item_get(eks, 0);
+
+	for (i = 0; i < ARRAY_SIZE(ok); i++) {
+		jwt_builder_auto_t *b = jwt_builder_new();
+		jwt_signature_t *sig = jwt_builder_add_signature(b,
+						JWT_ALG_ES256, ec);
+
+		ck_assert_ptr_nonnull(sig);
+		ck_assert_int_eq(jwt_signature_add_protected_json(sig, "p",
+								  ok[i]), 0);
+		ck_assert_int_eq(jwt_signature_add_header_json(sig, "h",
+							       ok[i]), 0);
+	}
+
+	for (i = 0; i < ARRAY_SIZE(bad); i++) {
+		jwt_builder_auto_t *b = jwt_builder_new();
+		jwt_signature_t *sig = jwt_builder_add_signature(b,
+						JWT_ALG_ES256, ec);
+
+		ck_assert_ptr_nonnull(sig);
+		ck_assert_int_ne(jwt_signature_add_protected_json(sig, "p",
+								  bad[i]), 0);
+		ck_assert_int_ne(jwt_signature_add_header_json(sig, "h",
+							       bad[i]), 0);
+	}
+
+	/* A number and a boolean round-trip in the unprotected per-signature
+	 * header as JSON scalars, and the token still verifies. */
+	{
+		jwt_builder_auto_t *b = jwt_builder_new();
+		jwt_checker_auto_t *c = jwt_checker_new();
+		jwt_signature_t *sig = jwt_builder_add_signature(b,
+						JWT_ALG_ES256, ec);
+		char_auto *tok = NULL;
+
+		ck_assert_ptr_nonnull(sig);
+		ck_assert_int_eq(jwt_signature_add_header_json(sig, "n", "1"),
+				 0);
+		ck_assert_int_eq(jwt_signature_add_header_json(sig, "y",
+							       "true"), 0);
+		ck_assert_int_eq(jwt_builder_set_format(b,
+							JWT_FORMAT_JSON_FLAT), 0);
+		tok = jwt_builder_generate(b);
+		ck_assert_ptr_nonnull(tok);
+		ck_assert_ptr_nonnull(strstr(tok, "\"n\":1"));
+		ck_assert_ptr_nonnull(strstr(tok, "\"y\":true"));
+
+		ck_assert_int_eq(jwt_checker_setkey(c, JWT_ALG_ES256, ec), 0);
+		ck_assert_int_eq(jwt_checker_verify(c, tok), 0);
+	}
+
+	jwks_free(eks);
+}
+END_TEST
+
 /* ====================================================================
  * GHSA-mhc9-xvg5-qg29: a keyring checker verifies a Compact token as the
  * equivalent one-signature JWS -- the same kid binding and kid-less scan,
@@ -1797,6 +1866,7 @@
 	tcase_add_loop_test(tc_core, test_malformed, 0, i);
 	tcase_add_loop_test(tc_core, test_none_rejected_builder, 0, i);
 	tcase_add_loop_test(tc_core, test_edges, 0, i);
+	tcase_add_loop_test(tc_core, test_sig_scalar_header, 0, i);
 	tcase_add_loop_test(tc_core, test_compact_keyring, 0, i);
 	tcase_add_loop_test(tc_core, test_compact_keyring_none, 0, i);
 	tcase_add_loop_test(tc_core, test_compact_keyring_confusion, 0, i);