Skip to content

Commit

Permalink
Ensure string values in headers are not quoted. (#329)
Browse files Browse the repository at this point in the history
* Ensure string values in headers are not quoted.

* Fix range issue

* Updated to use HeaderUtilities.RemoveQuotes.

* Switch to using JToken.Parse to process the value to ensure we deal with other escaped values in the string.
  • Loading branch information
jongeorge1 authored Mar 6, 2023
1 parent 8c52ce1 commit de9085b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ namespace Menes.Internal
using System.IO;
using System.Linq;
using System.Threading.Tasks;

using Corvus.Extensions.Json;
using Menes.Converters;
using Menes.Exceptions;

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;

/// <summary>
/// Wraps an <see cref="OpenApiResult"/> instance with the ability to apply the result to an
Expand Down Expand Up @@ -315,7 +317,18 @@ private void BuildHeaders(HttpResponse httpResponse, OpenApiResponse response)
convertedValue = this.ConvertValue(header.Value.Schema, value);
}

httpResponse.Headers.Add(header.Key, new Microsoft.Extensions.Primitives.StringValues(convertedValue));
// If the input value was a string, it will have been returned as if it were a serialized JSON element.
// This means it will be quoted, which we don't want for values going in the headers, so we'll get rid
// of the quotes if they are present. In order to ensure any other escaped characters introduced during
// serialization are written correctly, we need to do this by deserializing the data and extracting the
// string value from the resulting JToken.
if (convertedValue.Length > 0 && convertedValue[0] == '"')
{
var tokenValue = JToken.Parse(convertedValue);
convertedValue = tokenValue.ToObject<string>();
}

httpResponse.Headers.Add(header.Key, new StringValues(convertedValue));

if (this.logger.IsEnabled(LogLevel.Debug))
{
Expand Down
6 changes: 6 additions & 0 deletions Solutions/Menes.PetStore.Specs/Steps/Steps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ public void ThenTheResponseShouldContainTheHeader(string headerName)

Assert.IsTrue(response.Headers.TryGetValues(headerName, out IEnumerable<string>? values));
Assert.IsNotEmpty(values!);

// Ensure the supplied value is a valid URI
string rawLocation = values!.First();
string decodedLocation = Uri.UnescapeDataString(rawLocation);

Assert.IsTrue(Uri.IsWellFormedUriString(decodedLocation, UriKind.RelativeOrAbsolute));
}

[Then("the response should not contain the '(.*)' header")]
Expand Down

0 comments on commit de9085b

Please sign in to comment.