Skip to content

Commit e10f9ab

Browse files
authored
feat(agent): add resource limits and local $ref expansion to tool argument validation (T31) (#151)
1 parent 7a0bf41 commit e10f9ab

3 files changed

Lines changed: 333 additions & 58 deletions

File tree

‎argi-agent-framework/src/main/java/io/github/agentic/ai/graph/agent/validation/ToolArgumentValidator.java‎

Lines changed: 123 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
import com.fasterxml.jackson.databind.JsonNode;
2020
import com.fasterxml.jackson.databind.ObjectMapper;
2121

22+
import java.nio.charset.StandardCharsets;
23+
import java.util.ArrayDeque;
24+
import java.util.Deque;
2225
import java.util.Iterator;
2326
import java.util.Optional;
2427

@@ -30,9 +33,11 @@
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>
@@ -42,6 +47,15 @@
4247
*/
4348
public 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
}

‎argi-agent-framework/src/test/java/io/github/agentic/ai/graph/agent/node/ToolArgumentValidationGateTest.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,4 +259,45 @@ public ToolCallResponse interceptToolCall(ToolCallRequest request, ToolCallHandl
259259
};
260260
}
261261

262+
@Test
263+
@DisplayName("oversized arguments are rejected before the callback runs")
264+
void oversizedArgumentsAreRejected() throws Exception {
265+
AtomicInteger calls = new AtomicInteger();
266+
AgentToolNode node = baseBuilder()
267+
.validateToolArguments(true)
268+
.toolCallbacks(List.of(countedTool("gated", "{}", calls)))
269+
.build();
270+
271+
// 70_000 bytes, well above the validator's 64 KiB byte limit
272+
String response = run(node, "gated", "{\"name\": \"" + "a".repeat(70_000) + "\"}");
273+
274+
assertEquals(0, calls.get(), "byte-limit rejection must happen before dispatch");
275+
assertTrue(response.contains("ARGUMENTS_TOO_LARGE"), response);
276+
}
277+
278+
@Test
279+
@DisplayName("local $ref rules in a tool schema are enforced by the gate")
280+
void localRefSchemaIsEnforced() throws Exception {
281+
AtomicInteger calls = new AtomicInteger();
282+
String refSchema = """
283+
{
284+
"type": "object",
285+
"properties": {
286+
"name": { "$ref": "#/definitions/str" }
287+
},
288+
"definitions": { "str": { "type": "string" } }
289+
}""";
290+
AgentToolNode node = baseBuilder()
291+
.validateToolArguments(true)
292+
.toolCallbacks(List.of(countedTool("gated", refSchema, calls)))
293+
.build();
294+
295+
assertTrue(run(node, "gated", "{\"name\": \"ok\"}").contains("executed:"));
296+
assertEquals(1, calls.get());
297+
298+
String rejected = run(node, "gated", "{\"name\": 1}");
299+
assertEquals(1, calls.get(), "second call must be rejected before the callback");
300+
assertTrue(rejected.contains("INVALID_TYPE"), rejected);
301+
}
302+
262303
}

0 commit comments

Comments
 (0)