From d0cc04f95701e4c0decf19fc8c69a26c2df90fd3 Mon Sep 17 00:00:00 2001 From: Roman Marusyk Date: Thu, 26 Mar 2020 18:42:22 +0200 Subject: [PATCH] Convert InvalidOperationException to InvalidDataException for form reader (#20138) --- src/Http/WebUtilities/src/FormPipeReader.cs | 13 ++++++++++--- src/Http/WebUtilities/test/FormPipeReaderTests.cs | 12 ++++++++++++ src/Shared/UrlDecoder/UrlDecoder.cs | 2 +- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/Http/WebUtilities/src/FormPipeReader.cs b/src/Http/WebUtilities/src/FormPipeReader.cs index e5f158bc2d..6db8cfdceb 100644 --- a/src/Http/WebUtilities/src/FormPipeReader.cs +++ b/src/Http/WebUtilities/src/FormPipeReader.cs @@ -377,10 +377,17 @@ namespace Microsoft.AspNetCore.WebUtilities // We will also create a string from it by the end of the function. var span = MemoryMarshal.CreateSpan(ref Unsafe.AsRef(readOnlySpan[0]), readOnlySpan.Length); - var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true); - span = span.Slice(0, bytes); + try + { + var bytes = UrlDecoder.DecodeInPlace(span, isFormEncoding: true); + span = span.Slice(0, bytes); - return _encoding.GetString(span); + return _encoding.GetString(span); + } + catch (InvalidOperationException ex) + { + throw new InvalidDataException("The form value contains invalid characters.", ex); + } } else { diff --git a/src/Http/WebUtilities/test/FormPipeReaderTests.cs b/src/Http/WebUtilities/test/FormPipeReaderTests.cs index 9c973c680d..fac870f90f 100644 --- a/src/Http/WebUtilities/test/FormPipeReaderTests.cs +++ b/src/Http/WebUtilities/test/FormPipeReaderTests.cs @@ -78,6 +78,18 @@ namespace Microsoft.AspNetCore.WebUtilities Assert.Equal("2", formCollection["baz"].ToString()); } + [Fact] + public async Task ReadFormAsync_ValueContainsInvalidCharacters_Throw() + { + var bodyPipe = await MakePipeReader("%00"); + + var exception = await Assert.ThrowsAsync( + () => ReadFormAsync(new FormPipeReader(bodyPipe))); + + Assert.Equal("The form value contains invalid characters.", exception.Message); + Assert.IsType(exception.InnerException); + } + [Fact] public async Task ReadFormAsync_ValueCountLimitMet_Success() { diff --git a/src/Shared/UrlDecoder/UrlDecoder.cs b/src/Shared/UrlDecoder/UrlDecoder.cs index 9e01c15d5e..a5e4fbf045 100644 --- a/src/Shared/UrlDecoder/UrlDecoder.cs +++ b/src/Shared/UrlDecoder/UrlDecoder.cs @@ -294,7 +294,7 @@ namespace Microsoft.AspNetCore.Internal /// Read the next char and convert it into hexadecimal value. /// /// The index will be moved to the next - /// byte no matter no matter whether the operation successes. + /// byte no matter whether the operation successes. /// /// The index of the byte in the buffer to read /// The byte span from which the hex to be read