1919import com .fasterxml .jackson .databind .JsonNode ;
2020import com .fasterxml .jackson .databind .ObjectMapper ;
2121
22+ import java .nio .charset .StandardCharsets ;
23+ import java .util .ArrayDeque ;
24+ import java .util .Deque ;
2225import java .util .Iterator ;
2326import java .util .Optional ;
2427
3033 * Deliberately a small, closed-rule validator rather than a full JSON Schema engine:
3134 * JSON parse, {@code required}, {@code type}, {@code enum}, numeric
3235 * {@code minimum}/{@code maximum} range, {@code additionalProperties: false} and
33- * {@code null} type handling. It never loads external resources: {@code $ref} nodes are
34- * skipped (bounded local expansion is future work), so remote references cannot be
35- * fetched and recursion is bounded by the finite schema document.
36+ * {@code null} type handling, plus resource limits on argument size, nesting depth and
37+ * collection cardinality. Remote references are never fetched: {@code $ref} values are
38+ * resolved locally within the schema document when they are {@code #/...} pointers, and
39+ * rejected explicitly otherwise. Recursion is bounded by the depth limit and a cycle
40+ * guard, so neither hostile arguments nor hostile schemas can recurse unboundedly.
3641 * </p>
3742 *
3843 * <p>
4247 */
4348public final class ToolArgumentValidator {
4449
50+ /** Maximum accepted size of the raw arguments payload, in UTF-8 bytes. */
51+ static final int MAX_ARGUMENTS_BYTES = 64 * 1024 ;
52+
53+ /** Maximum nesting depth traversed across arguments and schema. */
54+ static final int MAX_DEPTH = 64 ;
55+
56+ /** Maximum number of entries in a validated object or array. */
57+ static final int MAX_COLLECTION_SIZE = 1_000 ;
58+
4559 private static final ObjectMapper MAPPER = new ObjectMapper ();
4660
4761 private ToolArgumentValidator () {
@@ -65,6 +79,11 @@ public record ToolArgumentValidationFailure(String errorCode, String fieldPath,
6579 * @return the first validation failure, or empty when the arguments are acceptable
6680 */
6781 public static Optional <ToolArgumentValidationFailure > validate (String inputSchema , String arguments ) {
82+ if (arguments != null && arguments .getBytes (StandardCharsets .UTF_8 ).length > MAX_ARGUMENTS_BYTES ) {
83+ return Optional .of (new ToolArgumentValidationFailure ("ARGUMENTS_TOO_LARGE" , "$" ,
84+ "tool arguments exceed the maximum accepted size" ));
85+ }
86+
6887 JsonNode schema = null ;
6988 if (inputSchema != null && !inputSchema .isBlank ()) {
7089 try {
@@ -103,56 +122,36 @@ public static Optional<ToolArgumentValidationFailure> validate(String inputSchem
103122 if (schema == null ) {
104123 return Optional .empty ();
105124 }
106- return validateObject (args , schema , "$" );
125+ return validateValue (args , schema , "$" , 1 , schema , new ArrayDeque <>() );
107126 }
108127
109- private static Optional <ToolArgumentValidationFailure > validateObject (JsonNode value , JsonNode schema , String path ) {
110- if (schema .has ("$ref" )) {
111- // $ref resolution is intentionally out of scope for the initial gate
112- return Optional .empty ();
128+ private static Optional <ToolArgumentValidationFailure > validateValue (JsonNode value , JsonNode schema , String path ,
129+ int depth , JsonNode schemaRoot , Deque <String > activeRefs ) {
130+ if (depth > MAX_DEPTH ) {
131+ return Optional .of (new ToolArgumentValidationFailure ("DEPTH_EXCEEDED" , path ,
132+ "nesting depth exceeds the configured limit" ));
113133 }
114134
115- JsonNode required = schema .path ("required" );
116- if (required .isArray ()) {
117- for (JsonNode requirement : required ) {
118- String key = requirement .asText ();
119- if (!value .has (key )) {
120- return Optional .of (new ToolArgumentValidationFailure ("REQUIRED_MISSING" , childPath (path , key ),
121- "required property is missing" ));
122- }
135+ JsonNode refNode = schema .path ("$ref" );
136+ if (refNode .isTextual ()) {
137+ String ref = refNode .asText ();
138+ if (!ref .startsWith ("#" )) {
139+ return Optional .of (new ToolArgumentValidationFailure ("REF_NOT_LOCAL" , path ,
140+ "only local $ref pointers are supported; remote references are never fetched" ));
123141 }
124- }
125-
126- JsonNode properties = schema .path ("properties" );
127- if (properties .isObject ()) {
128- Iterator <String > names = value .fieldNames ();
129- while (names .hasNext ()) {
130- String key = names .next ();
131- JsonNode propertySchema = properties .get (key );
132- String childPath = childPath (path , key );
133- if (propertySchema == null || !propertySchema .isObject ()) {
134- if (isProhibited (schema .path ("additionalProperties" ))) {
135- return Optional .of (new ToolArgumentValidationFailure ("ADDITIONAL_PROPERTY" , childPath ,
136- "property is not declared in the schema" ));
137- }
138- continue ;
139- }
140- Optional <ToolArgumentValidationFailure > failure = validateValue (value .get (key ), propertySchema , childPath );
141- if (failure .isPresent ()) {
142- return failure ;
143- }
142+ if (activeRefs .contains (ref )) {
143+ return Optional .of (new ToolArgumentValidationFailure ("REF_CYCLE" , path , "cyclic $ref detected" ));
144144 }
145- }
146- else if (isProhibited (schema .path ("additionalProperties" )) && value .size () > 0 ) {
147- return Optional .of (new ToolArgumentValidationFailure ("ADDITIONAL_PROPERTY" , childPath (path , nextKey (value )),
148- "property is not declared in the schema" ));
149- }
150- return Optional .empty ();
151- }
152-
153- private static Optional <ToolArgumentValidationFailure > validateValue (JsonNode value , JsonNode schema , String path ) {
154- if (schema .has ("$ref" )) {
155- return Optional .empty ();
145+ JsonNode target = resolvePointer (schemaRoot , ref );
146+ if (target == null || !target .isObject ()) {
147+ return Optional .of (new ToolArgumentValidationFailure ("REF_UNRESOLVED" , path ,
148+ "$ref does not resolve to a schema object within the document" ));
149+ }
150+ activeRefs .push (ref );
151+ Optional <ToolArgumentValidationFailure > failure = validateValue (value , target , path , depth + 1 , schemaRoot ,
152+ activeRefs );
153+ activeRefs .pop ();
154+ return failure ;
156155 }
157156
158157 JsonNode typeNode = schema .path ("type" );
@@ -189,14 +188,18 @@ private static Optional<ToolArgumentValidationFailure> validateValue(JsonNode va
189188 }
190189 }
191190
192- if (value .isObject () && ( schema . path ( "properties" ). isObject () || isProhibited ( schema . path ( "additionalProperties" ))) ) {
193- return validateObject (value , schema , path );
191+ if (value .isObject ()) {
192+ return validateObjectFields (value , schema , path , depth , schemaRoot , activeRefs );
194193 }
195194
196195 if (value .isArray () && schema .path ("items" ).isObject ()) {
196+ if (value .size () > MAX_COLLECTION_SIZE ) {
197+ return Optional .of (new ToolArgumentValidationFailure ("COLLECTION_TOO_LARGE" , path ,
198+ "array exceeds the maximum number of items" ));
199+ }
197200 for (int i = 0 ; i < value .size (); i ++) {
198201 Optional <ToolArgumentValidationFailure > failure = validateValue (value .get (i ), schema .path ("items" ),
199- path + "[" + i + "]" );
202+ path + "[" + i + "]" , depth + 1 , schemaRoot , activeRefs );
200203 if (failure .isPresent ()) {
201204 return failure ;
202205 }
@@ -205,6 +208,76 @@ private static Optional<ToolArgumentValidationFailure> validateValue(JsonNode va
205208 return Optional .empty ();
206209 }
207210
211+ private static Optional <ToolArgumentValidationFailure > validateObjectFields (JsonNode value , JsonNode schema ,
212+ String path , int depth , JsonNode schemaRoot , Deque <String > activeRefs ) {
213+ if (value .size () > MAX_COLLECTION_SIZE ) {
214+ return Optional .of (new ToolArgumentValidationFailure ("COLLECTION_TOO_LARGE" , path ,
215+ "object exceeds the maximum number of properties" ));
216+ }
217+
218+ JsonNode required = schema .path ("required" );
219+ if (required .isArray ()) {
220+ for (JsonNode requirement : required ) {
221+ String key = requirement .asText ();
222+ if (!value .has (key )) {
223+ return Optional .of (new ToolArgumentValidationFailure ("REQUIRED_MISSING" , childPath (path , key ),
224+ "required property is missing" ));
225+ }
226+ }
227+ }
228+
229+ JsonNode properties = schema .path ("properties" );
230+ Iterator <String > names = value .fieldNames ();
231+ while (names .hasNext ()) {
232+ String key = names .next ();
233+ JsonNode propertySchema = properties .isObject () ? properties .get (key ) : null ;
234+ String childPath = childPath (path , key );
235+ if (propertySchema == null || !propertySchema .isObject ()) {
236+ if (isProhibited (schema .path ("additionalProperties" ))) {
237+ return Optional .of (new ToolArgumentValidationFailure ("ADDITIONAL_PROPERTY" , childPath ,
238+ "property is not declared in the schema" ));
239+ }
240+ continue ;
241+ }
242+ Optional <ToolArgumentValidationFailure > failure = validateValue (value .get (key ), propertySchema , childPath ,
243+ depth + 1 , schemaRoot , activeRefs );
244+ if (failure .isPresent ()) {
245+ return failure ;
246+ }
247+ }
248+ return Optional .empty ();
249+ }
250+
251+ private static JsonNode resolvePointer (JsonNode schemaRoot , String ref ) {
252+ if ("#" .equals (ref )) {
253+ return schemaRoot ;
254+ }
255+ if (!ref .startsWith ("#/" )) {
256+ return null ;
257+ }
258+ JsonNode current = schemaRoot ;
259+ for (String rawToken : ref .substring (2 ).split ("/" )) {
260+ String token = rawToken .replace ("~1" , "/" ).replace ("~0" , "~" );
261+ if (current .isArray ()) {
262+ int index ;
263+ try {
264+ index = Integer .parseInt (token );
265+ }
266+ catch (NumberFormatException e ) {
267+ return null ;
268+ }
269+ current = index >= 0 && index < current .size () ? current .get (index ) : null ;
270+ }
271+ else {
272+ current = current .path (token );
273+ }
274+ if (current == null || current .isMissingNode ()) {
275+ return null ;
276+ }
277+ }
278+ return current ;
279+ }
280+
208281 private static boolean matchesType (JsonNode value , JsonNode typeNode ) {
209282 if (typeNode .isArray ()) {
210283 for (JsonNode candidate : typeNode ) {
@@ -238,9 +311,4 @@ private static String childPath(String path, String key) {
238311 return path + "." + key ;
239312 }
240313
241- private static String nextKey (JsonNode object ) {
242- Iterator <String > names = object .fieldNames ();
243- return names .hasNext () ? names .next () : "" ;
244- }
245-
246314}
0 commit comments