Update to latest SDK (#25421)

* React to platform compatibility analyzer warnings
* React to new warnings
* Add platform compatibility attributes
This commit is contained in:
Pranav K 2020-09-10 15:12:17 -07:00 committed by GitHub
parent fa2a5076e4
commit 690c717314
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 169 additions and 15 deletions

View File

@ -13,6 +13,9 @@
<!-- Public members should not use oblivious types. Not done with all nullable annotations. -->
<NoWarn>$(NoWarn);RS0041</NoWarn>
<!-- Turn off platform compatiblity analyzer warnings in test, test assets, and samples -->
<NoWarn Condition="'$(IsTestProject)' == 'true' OR '$(IsTestAssetProject)' == 'true' OR '$(ISBenchmarkProject)' == 'true' OR '$(IsSampleProject)' == 'true'">$(NoWarn);CA1416</NoWarn>
</PropertyGroup>
<ItemGroup Condition=" Exists('$(MSBuildProjectDirectory)\PublicAPI.*.txt') AND

View File

@ -1,9 +1,9 @@
{
"sdk": {
"version": "5.0.100-rc.1.20379.10"
"version": "5.0.100-rc.1.20429.2"
},
"tools": {
"dotnet": "5.0.100-rc.1.20379.10",
"dotnet": "5.0.100-rc.1.20429.2",
"runtimes": {
"dotnet/x64": [
"2.1.18",

View File

@ -14,7 +14,7 @@ namespace Ignitor
{
Timeout = timeout;
Completion = new TaskCompletionSource<TResult>(TaskContinuationOptions.RunContinuationsAsynchronously);
Completion = new TaskCompletionSource<TResult>(TaskCreationOptions.RunContinuationsAsynchronously);
Completion.Task.ContinueWith(
(task, state) =>
{

View File

@ -47,7 +47,7 @@ namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests
Browser.MountTestComponent<CounterComponent>();
Browser.Equal("Current count: 0", () => Browser.FindElement(By.TagName("p")).Text);
GracefulDisconnectCompletionSource = new TaskCompletionSource<object>(TaskContinuationOptions.RunContinuationsAsynchronously);
GracefulDisconnectCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
Sink = _serverFixture.Host.Services.GetRequiredService<TestSink>();
Messages = new List<(Extensions.Logging.LogLevel level, string eventIdName)>();
Sink.MessageLogged += Log;

View File

@ -4,6 +4,7 @@
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.Versioning;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Cryptography;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
@ -223,6 +224,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// <param name="builder">The <see cref="IDataProtectionBuilder"/>.</param>
/// <param name="registryKey">The location in the registry where keys should be stored.</param>
/// <returns>A reference to the <see cref="IDataProtectionBuilder" /> after this operation has completed.</returns>
[SupportedOSPlatform("windows")]
public static IDataProtectionBuilder PersistKeysToRegistry(this IDataProtectionBuilder builder, RegistryKey registryKey)
{
if (builder == null)
@ -356,6 +358,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// <remarks>
/// This API is only supported on Windows platforms.
/// </remarks>
[SupportedOSPlatform("windows")]
public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder)
{
if (builder == null)
@ -378,6 +381,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// <remarks>
/// This API is only supported on Windows platforms.
/// </remarks>
[SupportedOSPlatform("windows")]
public static IDataProtectionBuilder ProtectKeysWithDpapi(this IDataProtectionBuilder builder, bool protectToLocalMachine)
{
if (builder == null)
@ -408,6 +412,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// See https://msdn.microsoft.com/en-us/library/windows/desktop/hh706794(v=vs.85).aspx
/// for more information on DPAPI-NG. This API is only supported on Windows 8 / Windows Server 2012 and higher.
/// </remarks>
[SupportedOSPlatform("windows")]
public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder)
{
if (builder == null)
@ -435,6 +440,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// and <paramref name="flags"/> arguments.
/// This API is only supported on Windows 8 / Windows Server 2012 and higher.
/// </remarks>
[SupportedOSPlatform("windows")]
public static IDataProtectionBuilder ProtectKeysWithDpapiNG(this IDataProtectionBuilder builder, string protectionDescriptorRule, DpapiNGProtectionDescriptorFlags flags)
{
if (builder == null)

View File

@ -7,6 +7,7 @@ using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
@ -500,6 +501,8 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
{
if (OSVersionUtil.IsWindows())
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); // Hint for the platform compatibility analyzer.
// If the user profile is available, we can protect using DPAPI.
// Probe to see if protecting to local user is available, and use it as the default if so.
encryptor = new DpapiXmlEncryptor(
@ -523,10 +526,14 @@ namespace Microsoft.AspNetCore.DataProtection.KeyManagement
RegistryKey regKeyStorageKey = null;
if (OSVersionUtil.IsWindows())
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); // Hint for the platform compatibility analyzer.
regKeyStorageKey = RegistryXmlRepository.DefaultRegistryKey;
}
if (regKeyStorageKey != null)
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)); // Hint for the platform compatibility analyzer.
regKeyStorageKey = RegistryXmlRepository.DefaultRegistryKey;
// If the user profile isn't available, we can protect using DPAPI (to machine).
encryptor = new DpapiXmlEncryptor(protectToLocalMachine: true, loggerFactory: _loggerFactory);
repository = new RegistryXmlRepository(regKeyStorageKey, _loggerFactory);

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>ASP.NET Core logic to protect and unprotect data, similar to DPAPI.</Description>
@ -14,6 +14,8 @@
<ItemGroup>
<Compile Include="..\..\shared\src\*.cs" />
<Compile Include="$(SharedSourceRoot)PlatformAttributes.cs"
Condition="'$(TargetFramework)' != '$(DefaultNetCoreTargetFramework)'" />
</ItemGroup>
<ItemGroup>

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
using Microsoft.AspNetCore.Cryptography;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.DataProtection.Internal;
@ -17,6 +18,7 @@ namespace Microsoft.AspNetCore.DataProtection
/// <summary>
/// A type which allows reading policy from the system registry.
/// </summary>
[SupportedOSPlatform("windows")]
internal sealed class RegistryPolicyResolver: IRegistryPolicyResolver
{
private readonly Func<RegistryKey> _getPolicyRegKey;

View File

@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Xml.Linq;
using Microsoft.Extensions.Logging;
@ -15,6 +16,7 @@ namespace Microsoft.AspNetCore.DataProtection.Repositories
/// <summary>
/// An XML repository backed by the Windows registry.
/// </summary>
[SupportedOSPlatform("windows")]
public class RegistryXmlRepository : IXmlRepository
{
private static readonly Lazy<RegistryKey> _defaultRegistryKeyLazy = new Lazy<RegistryKey>(GetDefaultHklmStorageKey);

View File

@ -3,6 +3,7 @@
using System;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Xml.Linq;
using Microsoft.AspNetCore.Cryptography;
@ -18,6 +19,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
/// <remarks>
/// This API is only supported on Windows 8 / Windows Server 2012 and higher.
/// </remarks>
[SupportedOSPlatform("windows")]
public sealed class DpapiNGXmlEncryptor : IXmlEncryptor
{
private readonly ILogger _logger;

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Xml.Linq;
using Microsoft.AspNetCore.Cryptography;
@ -16,6 +17,7 @@ namespace Microsoft.AspNetCore.DataProtection.XmlEncryption
/// <remarks>
/// This API is only supported on Windows platforms.
/// </remarks>
[SupportedOSPlatform("windows")]
public sealed class DpapiXmlEncryptor : IXmlEncryptor
{
private readonly ILogger _logger;

View File

@ -2,5 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
[assembly: InternalsVisibleTo("Microsoft.AspNetCore.Hosting.WindowsServices.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: SupportedOSPlatform("windows")]

View File

@ -162,7 +162,7 @@ namespace Microsoft.AspNetCore.Http.Headers
{
public static bool TryParse(string value, out TestHeaderValue result)
{
if (string.Equals("valid", value))
if (string.Equals("valid", value, StringComparison.Ordinal))
{
result = new TestHeaderValue();
return true;
@ -176,7 +176,7 @@ namespace Microsoft.AspNetCore.Http.Headers
var results = new List<TestHeaderValue>();
foreach (var value in values)
{
if (string.Equals("valid", value))
if (string.Equals("valid", value, StringComparison.Ordinal))
{
results.Add(new TestHeaderValue());
}

View File

@ -896,7 +896,7 @@ namespace Microsoft.AspNetCore.Routing.Template.Tests
foreach (var xconstraint in x.InlineConstraints)
{
if (!y.InlineConstraints.Any<InlineConstraint>(
c => string.Equals(c.Constraint, xconstraint.Constraint)))
c => string.Equals(c.Constraint, xconstraint.Constraint, StringComparison.Ordinal)))
{
return false;
}

View File

@ -257,7 +257,7 @@ namespace Microsoft.AspNetCore.Razor.Design.IntegrationTests
Assert.BuildOutputContainsLine(result, $"RazorTasksPath: {expected}");
}
[ConditionalFact]
[ConditionalFact(Skip = "https://github.com/dotnet/aspnetcore/issues/24427")]
[OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
[InitializeTestProject("SimpleMvc")]
public async Task IntrospectRazorTasksDllPath_DesktopMsBuild()

View File

@ -315,7 +315,7 @@ namespace Microsoft.AspNetCore.Authentication.Negotiate
// things like ClaimsTransformation run per request.
var identity = _negotiateState.GetIdentity();
ClaimsPrincipal user;
if (identity is WindowsIdentity winIdentity)
if (OperatingSystem.IsWindows() && identity is WindowsIdentity winIdentity)
{
user = new WindowsPrincipal(winIdentity);
Response.RegisterForDispose(winIdentity);

View File

@ -9,6 +9,9 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>aspnetcore;weblistener;httpsys</PackageTags>
<IsPackable>false</IsPackable>
<!-- Ignore platform compatibility warnings for this project. We know this only works on windows.-->
<NoWarn>$(NoWarn);CA1416</NoWarn>
</PropertyGroup>
<ItemGroup>

View File

@ -2,6 +2,7 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.Versioning;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.DependencyInjection;
@ -23,6 +24,7 @@ namespace Microsoft.AspNetCore.Hosting
/// <returns>
/// A reference to the <see cref="IWebHostBuilder" /> parameter object.
/// </returns>
[SupportedOSPlatform("windows")]
public static IWebHostBuilder UseHttpSys(this IWebHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices(services => {
@ -52,6 +54,7 @@ namespace Microsoft.AspNetCore.Hosting
/// <returns>
/// A reference to the <see cref="IWebHostBuilder" /> parameter object.
/// </returns>
[SupportedOSPlatform("windows")]
public static IWebHostBuilder UseHttpSys(this IWebHostBuilder hostBuilder, Action<HttpSysOptions> options)
{
return hostBuilder.UseHttpSys().ConfigureServices(services =>

View File

@ -11,12 +11,15 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<NativeAssetsTargetFramework>$(DefaultNetCoreTargetFramework)</NativeAssetsTargetFramework>
<IsPackable>false</IsPackable>
<!-- Ignore platform compatibility warnings for this project. We know this only works on windows.-->
<NoWarn>$(NoWarn);CA1416</NoWarn>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(SharedSourceRoot)TypeNameHelper\*.cs" />
<Compile Include="$(SharedSourceRoot)Buffers.MemoryPool\**\*.cs" LinkBase="Shared\" />
<Compile Include="$(SharedSourceRoot)HttpSys\**\*.cs" LinkBase="Shared\"/>
<Compile Include="$(SharedSourceRoot)HttpSys\**\*.cs" LinkBase="Shared\" />
<Compile Include="$(SharedSourceRoot)StackTrace\**\*.cs" LinkBase="Shared\" />
<Compile Include="$(SharedSourceRoot)RazorViews\*.cs" LinkBase="Shared\" />
<Compile Include="$(SharedSourceRoot)ErrorPage\*.cs" LinkBase="Shared\" />

View File

@ -9,6 +9,9 @@
<PackageTags>aspnetcore;iis</PackageTags>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<IsPackable>false</IsPackable>
<!-- Ignore platform compatibility warnings for this project. We know this only works on windows.-->
<NoWarn>$(NoWarn);CA1416</NoWarn>
</PropertyGroup>
<ItemGroup>

View File

@ -20,6 +20,8 @@
about this structure
-->
<NoWarn>$(NoWarn);NU5100</NoWarn>
<!-- Ignore platform compatibility analyzer warnings for test and test infrastructure -->
<NoWarn>$(NoWarn);CA1416</NoWarn>
</PropertyGroup>
<Import Project="..\..\build\assets.props" />

View File

@ -646,7 +646,7 @@ public class Program
{
await stream.WriteAsync(new byte[] { 1, 2, 3 });
var tcs = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
using (_cancellationToken.Register(() => tcs.SetResult(true)))
{
await tcs.Task.ConfigureAwait(false);

View File

@ -28,7 +28,9 @@ namespace Microsoft.AspNetCore.Certificates.Generation
public const int RSAMinimumKeySizeInBits = 2048;
public static CertificateManager Instance { get; } = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
#pragma warning disable CA1416 // Validate platform compatibility
new WindowsCertificateManager() :
#pragma warning restore CA1416 // Validate platform compatibility
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ?
new MacOSCertificateManager() as CertificateManager :
new UnixCertificateManager();

View File

@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.AspNetCore.Certificates.Generation
{
[SupportedOSPlatform("windows")]
internal class WindowsCertificateManager : CertificateManager
{
private const int UserCancelledErrorCode = 1223;

View File

@ -0,0 +1,107 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Copied from https://raw.githubusercontent.com/dotnet/runtime/b45ee9d37afec0c88141053e86ccf71c6f283000/src/libraries/System.Private.CoreLib/src/System/Runtime/Versioning/PlatformAttributes.cs
#nullable enable
namespace System.Runtime.Versioning
{
/// <summary>
/// Base type for all platform-specific API attributes.
/// </summary>
#pragma warning disable CS3015 // Type has no accessible constructors which use only CLS-compliant types
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
abstract class OSPlatformAttribute : Attribute
#pragma warning restore CS3015
{
private protected OSPlatformAttribute(string platformName)
{
PlatformName = platformName;
}
public string PlatformName { get; }
}
/// <summary>
/// Records the platform that the project targeted.
/// </summary>
[AttributeUsage(AttributeTargets.Assembly,
AllowMultiple = false, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class TargetPlatformAttribute : OSPlatformAttribute
{
public TargetPlatformAttribute(string platformName) : base(platformName)
{
}
}
/// <summary>
/// Records the operating system (and minimum version) that supports an API. Multiple attributes can be
/// applied to indicate support on multiple operating systems.
/// </summary>
/// <remarks>
/// Callers can apply a <see cref="System.Runtime.Versioning.SupportedOSPlatformAttribute " />
/// or use guards to prevent calls to APIs on unsupported operating systems.
///
/// A given platform should only be specified once.
/// </remarks>
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Enum |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Module |
AttributeTargets.Property |
AttributeTargets.Struct,
AllowMultiple = true, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
{
public SupportedOSPlatformAttribute (string platformName) : base(platformName)
{
}
}
/// <summary>
/// Marks APIs that were removed in a given operating system version.
/// </summary>
/// <remarks>
/// Primarily used by OS bindings to indicate APIs that are only available in
/// earlier versions.
/// </remarks>
[AttributeUsage(AttributeTargets.Assembly |
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Enum |
AttributeTargets.Event |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Module |
AttributeTargets.Property |
AttributeTargets.Struct,
AllowMultiple = true, Inherited = false)]
#if SYSTEM_PRIVATE_CORELIB
public
#else
internal
#endif
sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
{
public UnsupportedOSPlatformAttribute(string platformName) : base(platformName)
{
}
}
}

View File

@ -55,12 +55,13 @@ namespace System.Net.Http.Unit.Tests.HPack
public void IntegerEncoderDecoderRoundtrips()
{
IntegerDecoder decoder = new IntegerDecoder();
Span<byte> integerBytes = stackalloc byte[5];
for (int i = 0; i < 2048; ++i)
{
for (int prefixLength = 1; prefixLength <= 8; ++prefixLength)
{
Span<byte> integerBytes = stackalloc byte[5];
integerBytes.Clear();
Assert.True(IntegerEncoder.Encode(i, prefixLength, integerBytes, out int length));
bool decodeResult = decoder.BeginTryDecode(integerBytes[0], prefixLength, out int intResult);

View File

@ -580,7 +580,7 @@ namespace Microsoft.AspNetCore.Http.Connections.Internal
if (oldContext.User.Identity is WindowsIdentity windowsIdentity)
{
var skipFirstIdentity = false;
if (oldContext.User is WindowsPrincipal)
if (OperatingSystem.IsWindows() && oldContext.User is WindowsPrincipal)
{
// We want to explicitly create a WindowsPrincipal instead of a ClaimsPrincipal
// so methods that WindowsPrincipal overrides like 'IsInRole', work as expected.