Skip to content

Commit

Permalink
Write grpc-web trailer names to response as lowercase (#1170)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK authored Jan 12, 2021
1 parent ab2efba commit 7d6683e
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 3 deletions.
9 changes: 7 additions & 2 deletions examples/Browser/Server/wwwroot/Scripts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,15 @@ streamInput.onclick = function () {
request.setName(nameInput.value);

streamingCall = client.sayHellos(request, {});
streamingCall.on('data', function (response) {
streamingCall.on('data', (response) => {
resultText.innerHTML += htmlEscape(response.getMessage()) + '<br />';
});
streamingCall.on('end', function () {
streamingCall.on('status', (status) => {
if (status.code == 0) {
resultText.innerHTML += 'Done';
} else {
resultText.innerHTML += 'Error: ' + htmlEscape(status.details);
}
});
} else {
streamingCall.cancel();
Expand Down
12 changes: 11 additions & 1 deletion src/Grpc.AspNetCore.Web/Internal/GrpcWebProtocolHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,17 @@ private static void WriteTrailersContent(Span<byte> buffer, IHeaderDictionary tr
{
if (value != null)
{
var position = Encoding.ASCII.GetBytes(kv.Key, currentBuffer);
// Get lower-case ASCII bytes for the key.
// gRPC-Web protocol says that names should be lower-case and grpc-web JS client
// will check for 'grpc-status' and 'grpc-message' in trailers with lower-case key.
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md#protocol-differences-vs-grpc-over-http2
for (int i = 0; i < kv.Key.Length; i++)
{
char c = kv.Key[i];
currentBuffer[i] = (byte)((uint)(c - 'A') <= ('Z' - 'A') ? c | 0x20 : c);
}

var position = kv.Key.Length;

currentBuffer[position++] = Colon;
currentBuffer[position++] = Space;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,31 @@ public void WriteTrailers_OneTrailer_WrittenToOutput()
Assert.AreEqual("one: two\r\n", text);
}

[Test]
public void WriteTrailers_OneTrailerMixedCase_WrittenToOutputLowerCase()
{
// Arrange
var trailers = new HeaderDictionary();
trailers.Add("One", "Two");
var output = new ArrayBufferWriter<byte>();

// Act
GrpcWebProtocolHelpers.WriteTrailers(trailers, output);

// Assert
Assert.AreEqual(15, output.WrittenSpan.Length);

Assert.AreEqual(128, output.WrittenSpan[0]);
Assert.AreEqual(0, output.WrittenSpan[1]);
Assert.AreEqual(0, output.WrittenSpan[2]);
Assert.AreEqual(0, output.WrittenSpan[3]);
Assert.AreEqual(10, output.WrittenSpan[4]);

var text = Encoding.ASCII.GetString(output.WrittenSpan.Slice(5));

Assert.AreEqual("one: Two\r\n", text);
}

[Test]
public void WriteTrailers_MultiValueTrailer_WrittenToOutput()
{
Expand Down

0 comments on commit 7d6683e

Please sign in to comment.