Spaces:
Running
Running
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 files82 unmodified lines8384858687888990919277 unmodified lines170171172173174175176177178179146 unmodified lines32632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043182 unmodified lines return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." }); }
var validationError = ValidateQuestSchema(schema); if (validationError != null) return BadRequest(new { message = validationError });
try { // Retrieve the system agent user dynamically by email to prevent Guid mismatches (e.g. SQLite seeded DB vs Prod DB)77 unmodified lines return BadRequest(new { message = "QuestboardAI plan must contain at least one task node." }); }
var validationError = ValidateQuestSchema(schema); if (validationError != null) return BadRequest(new { message = validationError });
try { var dbGraph = await _graphRepo.GetByIdAsync(id);146 unmodified lines } }
private string? ValidateQuestSchema(QuestSchemaDto schema) { const int MaxNodes = 200; const int MaxLabelLength = 120; // JSON-fragment detection: labels that look like raw JSON code fragments // e.g. "\"status\": \"Todo\"," or "{" or "}," var jsonFragmentPatterns = new[] { // Starts with a JSON punctuation character "{", "[", "},", "],", "},", "]}", };
if (schema.Nodes.Count > MaxNodes) return $"Payload rejected: too many nodes ({schema.Nodes.Count}). Maximum allowed is {MaxNodes}. " + "Please break your plan into smaller chunks or reduce the level of detail.";
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var allIds = schema.Nodes .Where(n => !string.IsNullOrWhiteSpace(n.Id)) .Select(n => n.Id) .ToHashSet(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < schema.Nodes.Count; i++) { var node = schema.Nodes[i]; string nodeRef = $"Node[{i}]" + (string.IsNullOrWhiteSpace(node.Id) ? "" : $" (id='{node.Id}')");
// 1. Empty Id if (string.IsNullOrWhiteSpace(node.Id)) return $"{nodeRef}: 'id' field is missing or empty. " + "Each node must have a unique alphanumeric string id (e.g. \"start\", \"phase1\").";
// 2. Duplicate Id if (!seenIds.Add(node.Id)) return $"{nodeRef}: duplicate id '{node.Id}'. " + "Every node must have a unique 'id'. " + "This error usually means the AI generated the same id multiple times — please ensure all ids are distinct.";
// 3. Empty Label if (string.IsNullOrWhiteSpace(node.Label)) return $"{nodeRef}: 'label' field is missing or empty. " + "Each node must have a short descriptive label (1–4 words).";
// 4. Label length guard if (node.Label.Length > MaxLabelLength) return $"{nodeRef}: label is too long ({node.Label.Length} chars). " + $"Maximum label length is {MaxLabelLength} characters. " + "This usually means the AI placed a full description into 'label' instead of 'description'. " + "Please shorten the label to 1–4 words.";
// 5. JSON-fragment detection in label — the #1 symptom of the fallback bug var trimmedLabel = node.Label.Trim(); bool looksLikeJsonFragment = jsonFragmentPatterns.Any(p => trimmedLabel.StartsWith(p)) || (trimmedLabel.Contains("\": \"") && trimmedLabel.EndsWith(",")) || (trimmedLabel.Contains("\": ") && trimmedLabel.EndsWith(",")) || (trimmedLabel.StartsWith("\"") && trimmedLabel.EndsWith("\","));
if (looksLikeJsonFragment) return $"{nodeRef}: label '{node.Label.Substring(0, Math.Min(60, node.Label.Length))}' " + "looks like a raw JSON code fragment, not a human-readable task name. " + "This means the AI sent a raw JSON string as the prompt file instead of a properly " + "structured QuestSchema payload. " + "Please ensure the prompt file contains a valid JSON object with a 'nodes' array " + "where each node has meaningful 'id', 'label', and 'description' fields.";
// 6. Dangling dependsOn reference if (!string.IsNullOrWhiteSpace(node.DependsOn) && !allIds.Contains(node.DependsOn)) return $"{nodeRef}: 'dependsOn' references unknown id '{node.DependsOn}'. " + "Make sure the parent node id exists in the 'nodes' array. " + "Check for typos or missing nodes in your plan.";
// 7. Self-referencing node (circular dependency of depth 1) if (!string.IsNullOrWhiteSpace(node.DependsOn) && string.Equals(node.DependsOn, node.Id, StringComparison.OrdinalIgnoreCase)) return $"{nodeRef}: a node cannot depend on itself (dependsOn='{node.DependsOn}'). " + "Please fix the dependency chain.";
// 8. Invalid status value var validStatuses = new[] { "Todo", "In Progress", "Progress", "Review", "Done" }; if (!string.IsNullOrWhiteSpace(node.Status) && !validStatuses.Any(s => s.Equals(node.Status, StringComparison.OrdinalIgnoreCase))) return $"{nodeRef}: invalid status '{node.Status}'. " + $"Allowed values are: {string.Join(", ", validStatuses)}.";
// 9. Invalid color value var validColors = new[] { "default", "yellow", "blue", "green", "pink", "purple", "orange", "white" }; if (!string.IsNullOrWhiteSpace(node.Color) && !validColors.Any(c => c.Equals(node.Color, StringComparison.OrdinalIgnoreCase))) return $"{nodeRef}: invalid color '{node.Color}'. " + $"Allowed values are: {string.Join(", ", validColors)}.";
// 10. Progress range if (node.Progress.HasValue && (node.Progress.Value < 0 || node.Progress.Value > 100)) return $"{nodeRef}: 'progress' must be between 0 and 100 (got {node.Progress.Value})."; }
return null; // All validations passed }
private string GenerateClaimToken(Guid graphId, DateTime expiry) { var key = _config["Jwt:Key"] ?? "TaskFlow_Secret_Key_For_JWT_Authentication_2026_!@#";FlowAPI/Controllers/AgentCanvasController.cs+108