Skip to content

Commit

Permalink
Merge pull request #2131 from microsoft/fix/validate-empty-memory-stream
Browse files Browse the repository at this point in the history
fix: add meaningful exception message during validation
  • Loading branch information
baywet authored Feb 6, 2025
2 parents 9856058 + f0146c3 commit 4a6547d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/Microsoft.OpenApi.Readers/OpenApiYamlReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using SharpYaml.Serialization;
using Microsoft.OpenApi.Models;
using System;
using System.Linq;
using System.Text;

namespace Microsoft.OpenApi.Readers
Expand Down Expand Up @@ -123,8 +124,12 @@ static JsonNode LoadJsonNodesFromYamlDocument(TextReader input)
{
var yamlStream = new YamlStream();
yamlStream.Load(input);
var yamlDocument = yamlStream.Documents[0];
return yamlDocument.ToJsonNode();
if (yamlStream.Documents.Any())
{
return yamlStream.Documents[0].ToJsonNode();
}

throw new InvalidOperationException("No documents found in the YAML stream.");
}
}
}
5 changes: 4 additions & 1 deletion src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,10 +278,13 @@ private static ReadResult InternalLoad(MemoryStream input, string format, OpenAp
{
throw new InvalidOperationException("Loading external references are not supported when using synchronous methods.");
}
if (input.Length == 0 || input.Position == input.Length)
{
throw new ArgumentException($"Cannot parse the stream: {nameof(input)} is empty or contains no elements.");
}

var reader = OpenApiReaderRegistry.GetReader(format);
var readResult = reader.Read(input, settings);

return readResult;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
using Microsoft.OpenApi.Writers;
using Xunit;
using VerifyXunit;
using VerifyTests;
using Microsoft.OpenApi.Models.Interfaces;
using System;

namespace Microsoft.OpenApi.Readers.Tests.V31Tests
{
Expand Down Expand Up @@ -539,5 +539,11 @@ public async Task ParseDocumentWith31PropertiesWorks()
// Assert
await Verifier.Verify(actual);
}

[Fact]
public void ParseEmptyMemoryStreamThrowsAnArgumentException()
{
Assert.Throws<ArgumentException>(() => OpenApiDocument.Load(new MemoryStream()));
}
}
}

0 comments on commit 4a6547d

Please sign in to comment.