-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Blazor Disable Non-WebSockets Transports by Default #34644
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
Changes from 7 commits
c4b3a17
fab2c82
e03d084
f1dbafc
895afb2
ce0ba7d
b2dc979
dfd0128
3bb93eb
1c3e8f6
221503a
b55777f
61a27b7
6b6c71e
5f8b828
0668383
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Large diffs are not rendered by default.
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'; | ||
|
@@ -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); | ||
|
@@ -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.'); | ||
TanayParikh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} else if (ex.message.includes('FailedToStartTransportWebSocketsError')) { | ||
showErrorNotification('Unable to connect, please ensure WebSockets are available. A VPN or proxy may be blocking the connection.'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Unable to connect, please ensure WebSockets are available on the server. There was a problem hiding this comment. Choose a reason for hiding this commentThe 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({ | ||
|
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(); | ||
} | ||
TanayParikh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
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', | ||
{ | ||
TanayParikh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
WebSocket: WebSocketNotAllowed, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm inclined to keep this test as:
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> |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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."; | ||
|
@@ -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 { | ||
|
@@ -650,6 +650,20 @@ export class TransportSendQueue { | |
} | ||
} | ||
|
||
class UnsupportedTransportError extends Error { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
|
Uh oh!
There was an error while loading. Please reload this page.