Turn on scope validation for service provider

Fixes https://github.com/dotnet/aspnetcore/issues/9365
This commit is contained in:
Pranav K 2020-03-16 16:01:09 -07:00
parent e2b574c325
commit c37f3fefce
No known key found for this signature in database
GPG Key ID: F748807460A27E91
7 changed files with 114 additions and 34 deletions

View File

@ -89,7 +89,7 @@ namespace Microsoft.JSInterop.WebAssembly
/// <param name="arg1">The second argument.</param>
/// <param name="arg2">The third argument.</param>
/// <returns>The result of the function invocation.</returns>
public TResult InvokeUnmarshalled<T0, T1, T2, TResult>(string identifier, T0 arg0, T1 arg1, T2 arg2)
public virtual TResult InvokeUnmarshalled<T0, T1, T2, TResult>(string identifier, T0 arg0, T1 arg1, T2 arg2)
{
var result = InternalCalls.InvokeJSUnmarshalled<T0, T1, T2, TResult>(out var exception, identifier, arg0, arg1, arg2);
return exception != null

View File

@ -6,6 +6,8 @@ using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.JSInterop.WebAssembly;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
@ -15,7 +17,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void CanResolve_AccessTokenProvider()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.AddApiAuthorization();
var host = builder.Build();
@ -25,7 +27,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void CanResolve_IRemoteAuthenticationService()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.AddApiAuthorization();
var host = builder.Build();
@ -35,7 +37,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void ApiAuthorizationOptions_ConfigurationDefaultsGetApplied()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.AddApiAuthorization();
var host = builder.Build();
@ -69,7 +71,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void ApiAuthorizationOptions_DefaultsCanBeOverriden()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.AddApiAuthorization(options =>
{
options.AuthenticationPaths = new RemoteAuthenticationApplicationPathsOptions
@ -129,7 +131,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void OidcOptions_ConfigurationDefaultsGetApplied()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.Replace(ServiceDescriptor.Singleton<NavigationManager, TestNavigationManager>());
builder.Services.AddOidcAuthentication(options => { });
var host = builder.Build();
@ -167,7 +169,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
[Fact]
public void OidcOptions_DefaultsCanBeOverriden()
{
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(GetJSRuntime());
builder.Services.AddOidcAuthentication(options =>
{
options.AuthenticationPaths = new RemoteAuthenticationApplicationPathsOptions
@ -242,5 +244,19 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Authentication
protected override void NavigateToCore(string uri, bool forceLoad) => throw new System.NotImplementedException();
}
private WebAssemblyJSRuntime GetJSRuntime(string environment = "Production")
{
var jsRuntime = new Mock<WebAssemblyJSRuntime>();
jsRuntime.Setup(j => j.InvokeUnmarshalled<object, object, object, string>("Blazor._internal.getApplicationEnvironment", null, null, null))
.Returns(environment)
.Verifiable();
jsRuntime.Setup(j => j.InvokeUnmarshalled<string, object, object, byte[]>("Blazor._internal.getConfig", It.IsAny<string>(), null, null))
.Returns((byte[])null)
.Verifiable();
return jsRuntime.Object;
}
}
}

View File

@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.Extensions.Configuration;
@ -14,6 +13,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Microsoft.JSInterop.WebAssembly;
namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
{
@ -35,7 +35,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
// We don't use the args for anything right now, but we want to accept them
// here so that it shows up this way in the project templates.
args ??= Array.Empty<string>();
var builder = new WebAssemblyHostBuilder();
var builder = new WebAssemblyHostBuilder(DefaultWebAssemblyJSRuntime.Instance);
// Right now we don't have conventions or behaviors that are specific to this method
// however, making this the default for the template allows us to add things like that
@ -47,7 +47,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
/// <summary>
/// Creates an instance of <see cref="WebAssemblyHostBuilder"/> with the minimal configuration.
/// </summary>
private WebAssemblyHostBuilder()
internal WebAssemblyHostBuilder(WebAssemblyJSRuntime jsRuntime)
{
// Private right now because we don't have much reason to expose it. This can be exposed
// in the future if we want to give people a choice between CreateDefault and something
@ -58,25 +58,20 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
InitializeDefaultServices();
var hostEnvironment = InitializeEnvironment(jsRuntime);
_createServiceProvider = () =>
{
return Services.BuildServiceProvider();
return Services.BuildServiceProvider(validateScopes: hostEnvironment.Environment == "Development");
};
InitializeEnvironment();
}
private void InitializeEnvironment()
private WebAssemblyHostEnvironment InitializeEnvironment(WebAssemblyJSRuntime jsRuntime)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
{
// The remainder of this method relies on the ability to make .NET WebAssembly-specific JSInterop calls.
// Note that this short-circuit exists as a way for unit tests running in .NET Core without JSInterop to run.
return;
}
var applicationEnvironment = jsRuntime.InvokeUnmarshalled<string>("Blazor._internal.getApplicationEnvironment");
var hostEnvironment = new WebAssemblyHostEnvironment(applicationEnvironment);
var applicationEnvironment = DefaultWebAssemblyJSRuntime.Instance.InvokeUnmarshalled<string>("Blazor._internal.getApplicationEnvironment");
Services.AddSingleton<IWebAssemblyHostEnvironment>(new WebAssemblyHostEnvironment(applicationEnvironment));
Services.AddSingleton<IWebAssemblyHostEnvironment>(hostEnvironment);
var configFiles = new[]
{
@ -86,7 +81,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
foreach (var configFile in configFiles)
{
var appSettingsJson = DefaultWebAssemblyJSRuntime.Instance.InvokeUnmarshalled<string, byte[]>(
var appSettingsJson = jsRuntime.InvokeUnmarshalled<string, byte[]>(
"Blazor._internal.getConfig",
configFile);
@ -97,6 +92,8 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
Configuration.Add<JsonStreamConfigurationSource>(s => s.Stream = new MemoryStream(appSettingsJson));
}
}
return hostEnvironment;
}
/// <summary>

View File

@ -23,6 +23,7 @@
<ItemGroup>
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.WebAssembly.Tests" />
<InternalsVisibleTo Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication.Tests" />
<InternalsVisibleTo Include="BasicTestApp" />
</ItemGroup>

View File

@ -0,0 +1,25 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.JSInterop.WebAssembly;
using Moq;
namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
{
public class TestWebAssemblyJSRuntime
{
public static WebAssemblyJSRuntime Create(string environment = "Production")
{
var jsRuntime = new Mock<WebAssemblyJSRuntime>();
jsRuntime.Setup(j => j.InvokeUnmarshalled<object, object, object, string>("Blazor._internal.getApplicationEnvironment", null, null, null))
.Returns(environment)
.Verifiable();
jsRuntime.Setup(j => j.InvokeUnmarshalled<string, object, object, byte[]>("Blazor._internal.getConfig", It.IsAny<string>(), null, null))
.Returns((byte[])null)
.Verifiable();
return jsRuntime.Object;
}
}
}

View File

@ -3,14 +3,14 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Microsoft.JSInterop.WebAssembly;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
@ -21,7 +21,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Build_AllowsConfiguringConfiguration()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Configuration.AddInMemoryCollection(new[]
{
@ -39,7 +39,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Build_AllowsConfiguringServices()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
// This test also verifies that we create a scope.
builder.Services.AddScoped<StringBuilder>();
@ -55,7 +55,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Build_AllowsConfiguringContainer()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Services.AddScoped<StringBuilder>();
var factory = new MyFakeServiceProviderFactory();
@ -73,7 +73,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Build_AllowsConfiguringContainer_WithDelegate()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Services.AddScoped<StringBuilder>();
@ -92,6 +92,46 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
Assert.NotNull(host.Services.GetRequiredService<List<string>>());
}
[Fact]
public void Build_InDevelopment_ConfiguresWithServiceProviderWithScopeValidation()
{
// Arrange
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create(environment: "Development"));
builder.Services.AddScoped<StringBuilder>();
builder.Services.AddSingleton<TestServiceThatTakesStringBuilder>();
// Act
var host = builder.Build();
// Assert
Assert.NotNull(host.Services.GetRequiredService<StringBuilder>());
Assert.Throws<InvalidOperationException>(() => host.Services.GetRequiredService<TestServiceThatTakesStringBuilder>());
}
[Fact]
public void Build_InProduction_ConfiguresWithServiceProviderWithScopeValidation()
{
// Arrange
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Services.AddScoped<StringBuilder>();
builder.Services.AddSingleton<TestServiceThatTakesStringBuilder>();
// Act
var host = builder.Build();
// Assert
Assert.NotNull(host.Services.GetRequiredService<StringBuilder>());
Assert.NotNull(host.Services.GetRequiredService<TestServiceThatTakesStringBuilder>());
}
private class TestServiceThatTakesStringBuilder
{
public TestServiceThatTakesStringBuilder(StringBuilder builder) { }
}
private class MyFakeDIBuilderThing
{
public MyFakeDIBuilderThing(IServiceCollection serviceCollection)
@ -125,7 +165,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Build_AddsConfigurationToServices()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Configuration.AddInMemoryCollection(new[]
{
@ -151,6 +191,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
typeof(INavigationInterception),
typeof(ILoggerFactory),
typeof(ILogger<>),
typeof(IWebAssemblyHostEnvironment),
};
}
}
@ -159,7 +200,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public void Constructor_AddsDefaultServices()
{
// Arrange & Act
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
// Assert
Assert.Equal(DefaultServiceTypes.Count, builder.Services.Count);

View File

@ -18,7 +18,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public async Task RunAsync_CanExitBasedOnCancellationToken()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
var host = builder.Build();
var cts = new CancellationTokenSource();
@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public async Task RunAsync_CallingTwiceCausesException()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
var host = builder.Build();
var cts = new CancellationTokenSource();
@ -56,7 +56,7 @@ namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting
public async Task DisposeAsync_CanDisposeAfterCallingRunAsync()
{
// Arrange
var builder = WebAssemblyHostBuilder.CreateDefault();
var builder = new WebAssemblyHostBuilder(TestWebAssemblyJSRuntime.Create());
builder.Services.AddSingleton<DisposableService>();
var host = builder.Build();