danylokhodus commited on
Commit
3159e54
·
1 Parent(s): 83f2320

feat(api): add server-side QuestSchema payload validation - block JSON-fragment labels, duplicate IDs, dangling dependsOn, self-refs, invalid status/color, node/label limits

Browse files
FlowAPI/Controllers/AgentCanvasController.cs CHANGED
@@ -83,6 +83,10 @@ namespace FlowAPI.Controllers
83
  return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." });
84
  }
85
 
 
 
 
 
86
  try
87
  {
88
  // Retrieve the system agent user dynamically by email to prevent Guid mismatches (e.g. SQLite seeded DB vs Prod DB)
@@ -166,6 +170,10 @@ namespace FlowAPI.Controllers
166
  return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." });
167
  }
168
 
 
 
 
 
169
  try
170
  {
171
  var dbGraph = await _graphRepo.GetByIdAsync(id);
@@ -318,6 +326,106 @@ namespace FlowAPI.Controllers
318
  }
319
  }
320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  private string GenerateClaimToken(Guid graphId, DateTime expiry)
322
  {
323
  var key = _config["Jwt:Key"] ?? "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#";
 
83
  return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." });
84
  }
85
 
86
+ var validationError = ValidateQuestSchema(schema);
87
+ if (validationError != null)
88
+ return BadRequest(new { message = validationError });
89
+
90
  try
91
  {
92
  // Retrieve the system agent user dynamically by email to prevent Guid mismatches (e.g. SQLite seeded DB vs Prod DB)
 
170
  return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." });
171
  }
172
 
173
+ var validationError = ValidateQuestSchema(schema);
174
+ if (validationError != null)
175
+ return BadRequest(new { message = validationError });
176
+
177
  try
178
  {
179
  var dbGraph = await _graphRepo.GetByIdAsync(id);
 
326
  }
327
  }
328
 
329
+ private string? ValidateQuestSchema(QuestSchemaDto schema)
330
+ {
331
+ const int MaxNodes = 200;
332
+ const int MaxLabelLength = 120;
333
+ // JSON-fragment detection: labels that look like raw JSON code fragments
334
+ // e.g. "\"status\": \"Todo\"," or "{" or "},"
335
+ var jsonFragmentPatterns = new[]
336
+ {
337
+ // Starts with a JSON punctuation character
338
+ "{", "[", "},", "],", "},", "]}",
339
+ };
340
+
341
+ if (schema.Nodes.Count > MaxNodes)
342
+ return $"Payload rejected: too many nodes ({schema.Nodes.Count}). Maximum allowed is {MaxNodes}. " +
343
+ "Please break your plan into smaller chunks or reduce the level of detail.";
344
+
345
+ var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
346
+ var allIds = schema.Nodes
347
+ .Where(n => !string.IsNullOrWhiteSpace(n.Id))
348
+ .Select(n => n.Id)
349
+ .ToHashSet(StringComparer.OrdinalIgnoreCase);
350
+
351
+ for (int i = 0; i < schema.Nodes.Count; i++)
352
+ {
353
+ var node = schema.Nodes[i];
354
+ string nodeRef = $"Node[{i}]" + (string.IsNullOrWhiteSpace(node.Id) ? "" : $" (id='{node.Id}')");
355
+
356
+ // 1. Empty Id
357
+ if (string.IsNullOrWhiteSpace(node.Id))
358
+ return $"{nodeRef}: 'id' field is missing or empty. " +
359
+ "Each node must have a unique alphanumeric string id (e.g. \"start\", \"phase1\").";
360
+
361
+ // 2. Duplicate Id
362
+ if (!seenIds.Add(node.Id))
363
+ return $"{nodeRef}: duplicate id '{node.Id}'. " +
364
+ "Every node must have a unique 'id'. " +
365
+ "This error usually means the AI generated the same id multiple times — please ensure all ids are distinct.";
366
+
367
+ // 3. Empty Label
368
+ if (string.IsNullOrWhiteSpace(node.Label))
369
+ return $"{nodeRef}: 'label' field is missing or empty. " +
370
+ "Each node must have a short descriptive label (1–4 words).";
371
+
372
+ // 4. Label length guard
373
+ if (node.Label.Length > MaxLabelLength)
374
+ return $"{nodeRef}: label is too long ({node.Label.Length} chars). " +
375
+ $"Maximum label length is {MaxLabelLength} characters. " +
376
+ "This usually means the AI placed a full description into 'label' instead of 'description'. " +
377
+ "Please shorten the label to 1–4 words.";
378
+
379
+ // 5. JSON-fragment detection in label — the #1 symptom of the fallback bug
380
+ var trimmedLabel = node.Label.Trim();
381
+ bool looksLikeJsonFragment =
382
+ jsonFragmentPatterns.Any(p => trimmedLabel.StartsWith(p)) ||
383
+ (trimmedLabel.Contains("\": \"") && trimmedLabel.EndsWith(",")) ||
384
+ (trimmedLabel.Contains("\": ") && trimmedLabel.EndsWith(",")) ||
385
+ (trimmedLabel.StartsWith("\"") && trimmedLabel.EndsWith("\","));
386
+
387
+ if (looksLikeJsonFragment)
388
+ return $"{nodeRef}: label '{node.Label.Substring(0, Math.Min(60, node.Label.Length))}' " +
389
+ "looks like a raw JSON code fragment, not a human-readable task name. " +
390
+ "This means the AI sent a raw JSON string as the prompt file instead of a properly " +
391
+ "structured QuestSchema payload. " +
392
+ "Please ensure the prompt file contains a valid JSON object with a 'nodes' array " +
393
+ "where each node has meaningful 'id', 'label', and 'description' fields.";
394
+
395
+ // 6. Dangling dependsOn reference
396
+ if (!string.IsNullOrWhiteSpace(node.DependsOn) && !allIds.Contains(node.DependsOn))
397
+ return $"{nodeRef}: 'dependsOn' references unknown id '{node.DependsOn}'. " +
398
+ "Make sure the parent node id exists in the 'nodes' array. " +
399
+ "Check for typos or missing nodes in your plan.";
400
+
401
+ // 7. Self-referencing node (circular dependency of depth 1)
402
+ if (!string.IsNullOrWhiteSpace(node.DependsOn) &&
403
+ string.Equals(node.DependsOn, node.Id, StringComparison.OrdinalIgnoreCase))
404
+ return $"{nodeRef}: a node cannot depend on itself (dependsOn='{node.DependsOn}'). " +
405
+ "Please fix the dependency chain.";
406
+
407
+ // 8. Invalid status value
408
+ var validStatuses = new[] { "Todo", "In Progress", "Progress", "Review", "Done" };
409
+ if (!string.IsNullOrWhiteSpace(node.Status) &&
410
+ !validStatuses.Any(s => s.Equals(node.Status, StringComparison.OrdinalIgnoreCase)))
411
+ return $"{nodeRef}: invalid status '{node.Status}'. " +
412
+ $"Allowed values are: {string.Join(", ", validStatuses)}.";
413
+
414
+ // 9. Invalid color value
415
+ var validColors = new[] { "default", "yellow", "blue", "green", "pink", "purple", "orange", "white" };
416
+ if (!string.IsNullOrWhiteSpace(node.Color) &&
417
+ !validColors.Any(c => c.Equals(node.Color, StringComparison.OrdinalIgnoreCase)))
418
+ return $"{nodeRef}: invalid color '{node.Color}'. " +
419
+ $"Allowed values are: {string.Join(", ", validColors)}.";
420
+
421
+ // 10. Progress range
422
+ if (node.Progress.HasValue && (node.Progress.Value < 0 || node.Progress.Value > 100))
423
+ return $"{nodeRef}: 'progress' must be between 0 and 100 (got {node.Progress.Value}).";
424
+ }
425
+
426
+ return null; // All validations passed
427
+ }
428
+
429
  private string GenerateClaimToken(Guid graphId, DateTime expiry)
430
  {
431
  var key = _config["Jwt:Key"] ?? "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#";