Skip to content

Commit d1bab84

Browse files
authored
fix: prevent infinite loops in collection deserialization by skipping unexpected tokens (#5)
1 parent d42e439 commit d1bab84

3 files changed

Lines changed: 506 additions & 0 deletions

File tree

src/Yamlify.SourceGenerator/YamlSourceGenerator.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,8 @@ private static void GenerateReadMethod(StringBuilder sb, TypeToGenerate type, IR
566566

567567
sb.AppendLine(" if (reader.TokenType != YamlTokenType.MappingStart)");
568568
sb.AppendLine(" {");
569+
sb.AppendLine(" // Skip unexpected token to prevent infinite loops when reading collections");
570+
sb.AppendLine(" reader.Skip();");
569571
sb.AppendLine(" return default;");
570572
sb.AppendLine(" }");
571573
sb.AppendLine();
@@ -2819,6 +2821,8 @@ private static void GenerateRootCollectionRead(StringBuilder sb, ITypeSymbol col
28192821

28202822
sb.AppendLine(" if (reader.TokenType != YamlTokenType.SequenceStart)");
28212823
sb.AppendLine(" {");
2824+
sb.AppendLine(" // Skip unexpected token to prevent infinite loops when reading collections");
2825+
sb.AppendLine(" reader.Skip();");
28222826
sb.AppendLine(" return default;");
28232827
sb.AppendLine(" }");
28242828
sb.AppendLine();
@@ -2860,6 +2864,8 @@ private static void GenerateRootDictionaryRead(StringBuilder sb, ITypeSymbol dic
28602864

28612865
sb.AppendLine(" if (reader.TokenType != YamlTokenType.MappingStart)");
28622866
sb.AppendLine(" {");
2867+
sb.AppendLine(" // Skip unexpected token to prevent infinite loops when reading collections");
2868+
sb.AppendLine(" reader.Skip();");
28632869
sb.AppendLine(" return default;");
28642870
sb.AppendLine(" }");
28652871
sb.AppendLine();

src/Yamlify/Reader/Utf8YamlReader.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -587,6 +587,13 @@ public void Skip()
587587
// Keep reading until we exit the current depth
588588
}
589589
}
590+
else if (_tokenType is YamlTokenType.Scalar)
591+
{
592+
// For scalar values (including nulls like ~, null, Null, NULL), just advance to the next token
593+
Read();
594+
}
595+
// For other tokens (end markers, etc.), do nothing - they're structural tokens
596+
// that don't need to be skipped
590597
}
591598
}
592599

0 commit comments

Comments
 (0)