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 7 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.

10 changes: 8 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,12 @@ async function initializeConnection(options: CircuitStartOptions, logger: Logger
await connection.start();
} catch (ex) {
unhandledError(connection, ex, logger);

if (ex.message.includes('UnsupportedTransportWebSocketsError')) {
showErrorNotification('Unable to connect, please ensure you are using an updated browser that supports WebSockets.');
} else if (ex.message.includes('FailedToStartTransportWebSocketsError')) {
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.

}
}

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,125 @@
// 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<ServerStartup>>
{
public ServerTransportsTest(
BrowserFixture browserFixture,
BasicTestAppServerSiteFixture<ServerStartup> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}

[Fact]
public void DefaultTransportsWorksWithWebSockets()
{
Navigate("/subdir/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 ErrorIfBrowserDoesNotSupportWebSockets()
{
Navigate("subdir/Transports");

Browser.Exists(By.Id("startWithWebSocketsDisabledInBrowserBtn")).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. WebSockets failed: UnsupportedTransportWebSocketsError: 'WebSockets' is not supported in your environment.",
"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 you are using an updated browser that supports WebSockets.", errorUiElem.GetAttribute("innerHTML"));
Browser.Equal("block", () => errorUiElem.GetCssValue("display"));
}

[Fact]
public void ErrorIfClientAttemptsLongPollingWithServerOnWebSockets()
{
Navigate("subdir/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("subdir/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. FailedToStartTransportWebSocketsError: 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"));
}

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,66 @@
@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="startWithWebSocketsDisabledInBrowserBtn" onclick="startWithWebSocketsDisabledInBrowser()">Start with WebSockets Disabled in Browser</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 startWithWebSocketsDisabledInBrowser() {
WebSocket = null; // emulates browsers which don't support WebSockets
startBlazorServer();
}

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,
Copy link
Contributor

Choose a reason for hiding this comment

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

Same for this one. A much more useful test is to have the server disable websockets which would simulates a misconfigured server.

Copy link
Contributor Author

@TanayParikh TanayParikh Jul 26, 2021

Choose a reason for hiding this comment

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

I'm inclined to keep this test as:

WebSocketNotAllowed approach should effectively be the same as the server rejecting a websocket request

I'd discussed testing VPN/proxy issues blocking WebSockets with Brennan, and this was the testing approach suggested. It's part of SignalR's testing mechanism that we're leveraging.

transport: 1, // WebSockets (1)
})
}
}).then(function () {
window['__aspnetcore__testing__blazor__start__script__executed__'] = true;
});
}
</script>
18 changes: 16 additions & 2 deletions src/SignalR/clients/ts/signalr/src/HttpConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ export class HttpConnection implements IConnection {
} catch (ex) {
this._logger.log(LogLevel.Error, `Failed to start the transport '${endpoint.transport}': ${ex}`);
negotiate = undefined;
transportExceptions.push(`${endpoint.transport} failed: ${ex}`);
transportExceptions.push(new FailedToStartTransportError(`${endpoint.transport} failed: ${ex}`, endpoint.transport));

if (this._connectionState !== ConnectionState.Connecting) {
const message = "Failed to select transport before stop() was called.";
Expand Down Expand Up @@ -447,7 +447,7 @@ export class HttpConnection implements IConnection {
if ((transport === HttpTransportType.WebSockets && !this._options.WebSocket) ||
(transport === HttpTransportType.ServerSentEvents && !this._options.EventSource)) {
this._logger.log(LogLevel.Debug, `Skipping transport '${HttpTransportType[transport]}' because it is not supported in your environment.'`);
return new Error(`'${HttpTransportType[transport]}' is not supported in your environment.`);
return new UnsupportedTransportError(`'${HttpTransportType[transport]}' is not supported in your environment.`, HttpTransportType[transport]);
} else {
this._logger.log(LogLevel.Debug, `Selecting transport '${HttpTransportType[transport]}'.`);
try {
Expand Down Expand Up @@ -650,6 +650,20 @@ export class TransportSendQueue {
}
}

class UnsupportedTransportError extends Error {
Copy link
Member

Choose a reason for hiding this comment

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

constructor(public message: string, transport: string) {
super(message);
this.name = `UnsupportedTransport${transport}Error`;
}
}

class FailedToStartTransportError extends Error {
constructor(public message: string, transport: string) {
super(message);
this.name = `FailedToStartTransport${transport}Error`;
}
}

class PromiseSource {
private _resolver?: () => void;
private _rejecter!: (reason?: any) => void;
Expand Down