fix(template-folder): bound cycle-walk to defend against malformed graphs

This commit is contained in:
Joseph Doherty
2026-05-11 10:58:02 -04:00
parent 1269054651
commit e44bbc0caf
2 changed files with 24 additions and 1 deletions

View File

@@ -86,13 +86,17 @@ public class TemplateFolderService
return Result<TemplateFolder>.Failure($"Target folder with ID {newParentId.Value} not found.");
var all = await _repository.GetAllFoldersAsync(cancellationToken);
// Walk up from newParentId — if we encounter folderId, the move would create a cycle.
var byId = all.ToDictionary(f => f.Id);
var cursor = newParentId;
// Walk up from newParentId — if we encounter folderId, the move would create a cycle.
// Bound iterations by byId.Count to defensively terminate on a malformed graph.
var iterations = 0;
while (cursor.HasValue)
{
if (cursor.Value == folderId)
return Result<TemplateFolder>.Failure("Cannot move a folder under one of its descendants (cycle).");
if (++iterations > byId.Count)
return Result<TemplateFolder>.Failure("Folder hierarchy contains a cycle; cannot determine ancestry.");
cursor = byId.TryGetValue(cursor.Value, out var node) ? node.ParentFolderId : null;
}