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

Blazor Disable Non-WebSockets Transports by Default #34644

Merged
merged 16 commits into from
Jul 27, 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
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public static ComponentEndpointConventionBuilder MapBlazorHub(
throw new ArgumentNullException(nameof(path));
}

return endpoints.MapBlazorHub(path, configureOptions: _ => { });
// Only support the WebSockets transport type by default
return endpoints.MapBlazorHub(path, configureOptions: options => { options.Transports = HttpTransportType.WebSockets; });
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.server.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/Components/Web.JS/dist/Release/blazor.webview.js

Large diffs are not rendered by default.

15 changes: 13 additions & 2 deletions src/Components/Web.JS/src/Boot.Server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DotNet } from '@microsoft/dotnet-js-interop';
import { Blazor } from './GlobalExports';
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr';
import { HubConnectionBuilder, HubConnection, HttpTransportType } from '@microsoft/signalr';
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack';
import { showErrorNotification } from './BootErrors';
import { shouldAutoStart } from './BootCommon';
Expand Down Expand Up @@ -85,7 +85,7 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger
(hubProtocol as unknown as { name: string }).name = 'blazorpack';

const connectionBuilder = new HubConnectionBuilder()
.withUrl('_blazor')
.withUrl('_blazor', HttpTransportType.WebSockets)
.withHubProtocol(hubProtocol);

options.configureSignalR(connectionBuilder);
Expand Down Expand Up @@ -130,6 +130,17 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger
await connection.start();
} catch (ex) {
unhandledError(connection, ex, logger);

if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'UnsupportedTransportError' && e.transport === 'WebSockets')) {
showErrorNotification('Unable to connect, please ensure you are using an updated browser that supports WebSockets.');
} else if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'FailedToStartTransportError' && e.transport === 'WebSockets')) {
showErrorNotification('Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.');
Copy link
Member

Choose a reason for hiding this comment

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

Unable to connect, please ensure WebSockets are available.

Unable to connect, please ensure WebSockets are available on the server.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I'm not so sure about this as this message is end-user facing and hence I would like to avoid "on the server" as it has no end user configurability. Additionally, it may not be a server issue if the local client VPN/proxy is blocking the connection.

} else if (ex.innerErrors && ex.innerErrors.some(e => e.errorType === 'DisabledTransportError' && e.transport === 'LongPolling')) {
logger.log(LogLevel.Error, 'Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. To troubleshoot this, visit https://aka.ms/blazor-server-websockets-error.');
showErrorNotification();
Copy link
Member

Choose a reason for hiding this comment

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

Why doesn't this one get a nice UI message?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This represents the case when the client is attempting WS and the server only supports long polling. There's no remedial action the end-user can take here so we just present the generic "Unhandled exception has occurred". Note the developer will be presented a message to check the console and they'll see this error message to resolve the issue.

} else {
showErrorNotification();
}
}

DotNet.attachDispatcher({
Expand Down
6 changes: 5 additions & 1 deletion src/Components/Web.JS/src/BootErrors.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
let hasFailed = false;

export async function showErrorNotification() {
export async function showErrorNotification(customErrorMessage: string = '') {
let errorUi = document.querySelector('#blazor-error-ui') as HTMLElement;
if (errorUi) {
errorUi.style.display = 'block';

if (customErrorMessage && errorUi.firstChild) {
errorUi.firstChild.textContent = `\n\t${customErrorMessage}\t\n`;
}
}

if (!hasFailed) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Linq;
using System.Threading;
using BasicTestApp;
using BasicTestApp.Reconnection;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using TestServer;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests
{
public class ServerTransportsTest : ServerTestBase<BasicTestAppServerSiteFixture<TransportsServerStartup>>
{
public ServerTransportsTest(
BrowserFixture browserFixture,
BasicTestAppServerSiteFixture<TransportsServerStartup> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}

[Fact]
public void DefaultTransportsWorksWithWebSockets()
{
Navigate("/defaultTransport/Transports");

Browser.Exists(By.Id("startBlazorServerBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Starting up Blazor server-side application.",
"WebSocket connected to ws://",
"Received render batch with",
"The HttpConnection connected successfully.",
"Blazor server-side application started.");
}

[Fact]
public void ErrorIfClientAttemptsLongPollingWithServerOnWebSockets()
{
Navigate("/defaultTransport/Transports");

Browser.Exists(By.Id("startWithLongPollingBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Information: Starting up Blazor server-side application.",
"Failed to start the connection: Error: Unable to connect to the server with any of the available transports.",
"Failed to start the circuit.");

var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10));
Assert.NotNull(errorUiElem);
Assert.Contains("An unhandled exception has occurred. See browser dev tools for details.", errorUiElem.GetAttribute("innerHTML"));
Browser.Equal("block", () => errorUiElem.GetCssValue("display"));
}

[Fact]
public void ErrorIfWebSocketsConnectionIsRejected()
{
Navigate("/defaultTransport/Transports");

Browser.Exists(By.Id("startAndRejectWebSocketConnectionBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Information: Starting up Blazor server-side application.",
"Selecting transport 'WebSockets'.",
"Error: Failed to start the transport 'WebSockets': Error: Don't allow Websockets.",
"Error: Failed to start the connection: Error: Unable to connect to the server with any of the available transports. Error: WebSockets failed: Error: Don't allow Websockets.",
"Failed to start the circuit.");

// Ensure error ui is visible
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10));
Assert.NotNull(errorUiElem);
Assert.Contains("Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.", errorUiElem.GetAttribute("innerHTML"));
Browser.Equal("block", () => errorUiElem.GetCssValue("display"));
}

[Fact]
public void ErrorIfClientAttemptsWebSocketsWithServerOnLongPolling()
{
Navigate("/longPolling/Transports");

Browser.Exists(By.Id("startBlazorServerBtn")).Click();

var javascript = (IJavaScriptExecutor)Browser;
Browser.True(() => (bool)javascript.ExecuteScript("return window['__aspnetcore__testing__blazor__start__script__executed__'] === true;"));

AssertLogContainsMessages(
"Starting up Blazor server-side application.",
"Unable to connect to the server with any of the available transports. LongPolling failed: Error: 'LongPolling' is disabled by the client.",
"Unable to initiate a SignalR connection to the server. This might be because the server is not configured to support WebSockets. To troubleshoot this, visit");

var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10));
Assert.NotNull(errorUiElem);
Assert.Contains("An unhandled exception has occurred. See browser dev tools for details.", errorUiElem.GetAttribute("innerHTML"));
Browser.Equal("block", () => errorUiElem.GetCssValue("display"));
}

void AssertLogContainsMessages(params string[] messages)
{
var log = Browser.Manage().Logs.GetLog(LogType.Browser);
foreach (var message in messages)
{
Assert.Contains(log, entry =>
{
return entry.Message.Contains(message, StringComparison.InvariantCulture);
});
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
@page
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"

<root><component type="typeof(BasicTestApp.Index)" render-mode="Server" /></root>

<div id="blazor-error-ui">
An unhandled exception has occurred. See browser dev tools for details.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>

<button id="startBlazorServerBtn" onclick="startBlazorServer()">Start Normally</button>
<button id="startWithLongPollingBtn" onclick="startWithLongPolling()">Start with Long Polling</button>
<button id="startAndRejectWebSocketConnectionBtn" onclick="startAndRejectWebSocketConnection()">Start with WebSockets and Reject Connection</button>

<script src="_framework/blazor.server.js" autostart="false"></script>
<script>
console.log('Blazor server-side');

function startBlazorServer() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}

function startWithLongPolling() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
.withUrl('_blazor', 4) // Long Polling (4)
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}

function WebSocketNotAllowed() { throw new Error("Don't allow Websockets."); }

function startAndRejectWebSocketConnection() {
Blazor.start({
logLevel: 1, // LogLevel.Debug
configureSignalR: builder => {
builder.configureLogging("debug") // LogLevel.Debug
.withUrl('_blazor', {
WebSocket: WebSocketNotAllowed,
transport: 1, // WebSockets (1)
})
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
</script>
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void ConfigureServices(IServiceCollection services)
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
{
var enUs = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = enUs;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Globalization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace TestServer
{
public class TransportsServerStartup : ServerStartup
{
public TransportsServerStartup(IConfiguration configuration)
: base (configuration)
{
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ResourceRequestLog resourceRequestLog)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Map("/defaultTransport", app =>
{
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_ServerHost");
});
});

app.Map("/longPolling", app =>
{
app.UseStaticFiles();

app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapBlazorHub(configureOptions: options =>
{
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.LongPolling;
Comment on lines +50 to +51
Copy link
Contributor

Choose a reason for hiding this comment

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

👍🏽

});
endpoints.MapFallbackToPage("/_ServerHost");
});
});
}
}
}
Loading