Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix setting user-agent in client when running in the browser #1165

Merged
merged 1 commit into from
Jan 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions src/Grpc.Net.Client.Web/GrpcWebHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Grpc.Net.Client.Web.Internal;
Expand All @@ -39,6 +40,9 @@ public sealed class GrpcWebHandler : DelegatingHandler
{
internal const string WebAssemblyEnableStreamingResponseKey = "WebAssemblyEnableStreamingResponse";

// Internal and mutable for unit testing.
internal IOperatingSystem OperatingSystem { get; set; } = Internal.OperatingSystem.Instance;

/// <summary>
/// Gets or sets the HTTP version to use when making gRPC-Web calls.
/// <para>
Expand Down Expand Up @@ -117,6 +121,11 @@ private async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request
{
request.Content = new GrpcWebRequestContent(request.Content!, GrpcWebMode);

if (OperatingSystem.IsBrowser)
{
FixBrowserUserAgent(request);
}

// Set WebAssemblyEnableStreamingResponse to true on gRPC-Web request.
// https://github.com/mono/mono/blob/a0d69a4e876834412ba676f544d447ec331e7c01/sdks/wasm/framework/src/System.Net.Http.WebAssemblyHttpHandler/WebAssemblyHttpHandler.cs#L149
//
Expand Down Expand Up @@ -163,14 +172,29 @@ private async Task<HttpResponseMessage> SendAsyncCore(HttpRequestMessage request
return response;
}

private void FixBrowserUserAgent(HttpRequestMessage request)
{
const string userAgentHeader = "User-Agent";

// Remove the user-agent header and re-add it as x-user-agent.
// We don't want to override the browser's user-agent value.
// Consistent with grpc-web JS client which sends its header in x-user-agent.
// https://github.com/grpc/grpc-web/blob/2e3e8d2c501c4ddce5406ac24a637003eabae4cf/javascript/net/grpc/web/grpcwebclientbase.js#L323
if (request.Headers.TryGetValues(userAgentHeader, out var values))
{
request.Headers.Remove(userAgentHeader);
request.Headers.TryAddWithoutValidation("X-User-Agent", values);
}
}

private static bool IsMatchingResponseContentType(GrpcWebMode mode, string? contentType)
{
if (mode == Web.GrpcWebMode.GrpcWeb)
if (mode == GrpcWebMode.GrpcWeb)
{
return CommonGrpcProtocolHelpers.IsContentType(GrpcWebProtocolConstants.GrpcWebContentType, contentType);
}

if (mode == Web.GrpcWebMode.GrpcWebText)
if (mode == GrpcWebMode.GrpcWebText)
{
return CommonGrpcProtocolHelpers.IsContentType(GrpcWebProtocolConstants.GrpcWebTextContentType, contentType);
}
Expand Down
39 changes: 39 additions & 0 deletions src/Grpc.Net.Client.Web/Internal/OperatingSystem.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
#region Copyright notice and license

// Copyright 2019 The gRPC Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System.Runtime.InteropServices;

namespace Grpc.Net.Client.Web.Internal
{
internal interface IOperatingSystem
{
bool IsBrowser { get; }
}

internal class OperatingSystem : IOperatingSystem
{
public static readonly OperatingSystem Instance = new OperatingSystem();

public bool IsBrowser { get; }

private OperatingSystem()
{
IsBrowser = RuntimeInformation.IsOSPlatform(OSPlatform.Create("browser"));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Huh, I didn't know it was possible to create a "browser" OS platform and it'll just work.

}
}
}
38 changes: 38 additions & 0 deletions test/Grpc.Net.Client.Tests/Web/GrpcWebHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
Expand Down Expand Up @@ -110,6 +111,36 @@ public async Task SendAsync_GrpcCall_ResponseStreamingPropertySet()
Assert.AreEqual(true, testHttpHandler.WebAssemblyEnableStreamingResponse);
}

[Test]
public async Task SendAsync_GrpcCallInBrowser_UserAgentFixed()
{
// Arrange
var request = new HttpRequestMessage
{
Version = HttpVersion.Version20,
Content = new ByteArrayContent(Array.Empty<byte>())
{
Headers = { ContentType = new MediaTypeHeaderValue("application/grpc") }
}
};
request.Headers.TryAddWithoutValidation("User-Agent", "TestUserAgent");
var testHttpHandler = new TestHttpHandler();
var grpcWebHandler = new GrpcWebHandler(GrpcWebMode.GrpcWeb, testHttpHandler);
grpcWebHandler.OperatingSystem = new TestOperatingSystem
{
IsBrowser = true
};
var messageInvoker = new HttpMessageInvoker(grpcWebHandler);

// Act
await messageInvoker.SendAsync(request, CancellationToken.None);

// Assert
Assert.AreEqual(false, testHttpHandler.RequestHeaders!.TryGetValues("user-agent", out _));
Assert.AreEqual(true, testHttpHandler.RequestHeaders!.TryGetValues("x-user-agent", out var values));
Assert.AreEqual("TestUserAgent", values!.Single());
}

[Test]
public async Task SendAsync_NonGrpcCall_ResponseStreamingPropertyNotSet()
{
Expand All @@ -133,14 +164,21 @@ public async Task SendAsync_NonGrpcCall_ResponseStreamingPropertyNotSet()
Assert.AreEqual(null, testHttpHandler.WebAssemblyEnableStreamingResponse);
}

private class TestOperatingSystem : IOperatingSystem
{
public bool IsBrowser { get; set; }
}

private class TestHttpHandler : HttpMessageHandler
{
public Version? RequestVersion { get; private set; }
public bool? WebAssemblyEnableStreamingResponse { get; private set; }
public HttpRequestHeaders? RequestHeaders { get; private set; }

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
RequestVersion = request.Version;
RequestHeaders = request.Headers;
#pragma warning disable CS0618 // Type or member is obsolete
if (request.Properties.TryGetValue(GrpcWebHandler.WebAssemblyEnableStreamingResponseKey, out var enableStreaming))
#pragma warning restore CS0618 // Type or member is obsolete
Expand Down