Skip to content

Commit

Permalink
Target .NET6 instead of .NET Standard 2.0 and .NET Core 3.1 (#280)
Browse files Browse the repository at this point in the history
* Set Target Framework to net6.0, remove conditional compilations and fix variety of arising nullability errors

* Fix typos

* Use static where possible for private methods

* Fix typo in internal class name

* Improve style consistency in xml doc comments

* Simplify control flow

* Use Contains over IndexOf >= 0

* Modernize code style and adjust indentation for consistency

* Use discard over __

* Remove redundant annotations
  • Loading branch information
Mafii authored Jan 16, 2023
1 parent f31dbfa commit 2ca07d2
Show file tree
Hide file tree
Showing 34 changed files with 59 additions and 169 deletions.
4 changes: 2 additions & 2 deletions src/Kestrel.Certificates/KestrelHttpsOptionsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace Microsoft.AspNetCore.Hosting;

/// <summary>
/// API for configuring Kestrel certificiate options
/// API for configuring Kestrel certificate options
/// </summary>
public static class KestrelHttpsOptionsExtensions
{
Expand All @@ -22,7 +22,7 @@ public static HttpsConnectionAdapterOptions UseServerCertificateSelector(
this HttpsConnectionAdapterOptions httpsOptions,
IServerCertificateSelector certificateSelector)
{
httpsOptions.ServerCertificateSelector = certificateSelector.Select;
httpsOptions.ServerCertificateSelector = certificateSelector.Select!;
return httpsOptions;
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<TargetFramework>net6.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Nullable>enable</Nullable>
<IsPackable>true</IsPackable>
Expand All @@ -13,12 +13,9 @@ This library includes API for dynamically selecting which HTTPS certificate to u
<PackageVersion Condition="'$(IncludePreReleaseLabelInPackageVersion)' == 'true'">$(PackageVersion)-$(VersionSuffix)</PackageVersion>
</PropertyGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.1'">
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Core" Version="2.1.25" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

#if FEATURE_VALIDATE_DATA_ANNOTATIONS
using System.ComponentModel.DataAnnotations;
#endif
using Azure.Core;
using Azure.Identity;
using LettuceEncrypt.Accounts;
Expand All @@ -18,10 +16,8 @@ public class AzureKeyVaultLettuceEncryptOptions
/// <summary>
/// Gets or sets the Url for the KeyVault instance.
/// </summary>
#if FEATURE_VALIDATE_DATA_ANNOTATIONS
[Url]
[Required]
#endif
public string AzureKeyVaultEndpoint { get; set; } = null!;

/// <summary>
Expand All @@ -34,8 +30,6 @@ public class AzureKeyVaultLettuceEncryptOptions
/// This is a JSON string which encodes the information in <see cref="AccountModel"/>.
/// If not set, the name defaults to the name of the "le-account-${ACME server hostname}".
/// </summary>
#if FEATURE_VALIDATE_DATA_ANNOTATIONS
[MaxLength(127)]
#endif
public string? AccountKeySecretName { get; set; }
}
9 changes: 3 additions & 6 deletions src/LettuceEncrypt.Azure/AzureLettuceEncryptExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,10 @@ public static ILettuceEncryptServiceBuilder PersistCertificatesToAzureKeyVault(
config?.Bind("LettuceEncrypt:AzureKeyVault", o));
});

var options = services
services
.AddOptions<AzureKeyVaultLettuceEncryptOptions>()
.Configure(configure);

#if FEATURE_VALIDATE_DATA_ANNOTATIONS
options.ValidateDataAnnotations();
#endif
.Configure(configure)
.ValidateDataAnnotations();

return builder;
}
Expand Down
6 changes: 1 addition & 5 deletions src/LettuceEncrypt.Azure/LettuceEncrypt.Azure.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;netstandard2.0</TargetFrameworks>
<TargetFramework>net6.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<Nullable>enable</Nullable>
<IsPackable>true</IsPackable>
Expand All @@ -12,10 +12,6 @@ See https://nuget.org/packages/LettuceEncrypt for more details.
</PackageDescription>
</PropertyGroup>

<PropertyGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<DefineConstants>$(DefineConstants);FEATURE_VALIDATE_DATA_ANNOTATIONS</DefineConstants>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.6.0" />
<PackageReference Include="Azure.Security.KeyVault.Certificates" Version="4.3.0" />
Expand Down
4 changes: 2 additions & 2 deletions src/LettuceEncrypt/FileSystemPersistenceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static class FileSystemStorageExtensions
/// </summary>
/// <param name="builder"></param>
/// <param name="directory">The root directory for storing information. Information may be stored in subdirectories.</param>
/// <param name="pfxPassword">Set to null or empty for passwordless .pfx files.</param>
/// <param name="pfxPassword">Set to null or empty for password-less .pfx files.</param>
/// <returns></returns>
public static ILettuceEncryptServiceBuilder PersistDataToDirectory(
this ILettuceEncryptServiceBuilder builder,
Expand All @@ -47,7 +47,7 @@ public static ILettuceEncryptServiceBuilder PersistDataToDirectory(

foreach (var serviceDescriptor in otherFileSystemRepoServices)
{
var otherRepo = (FileSystemCertificateRepository)serviceDescriptor.ImplementationInstance;
var otherRepo = (FileSystemCertificateRepository)serviceDescriptor.ImplementationInstance!;
if (otherRepo.RootDir.Equals(directory))
{
if (otherRepo.PfxPassword != pfxPassword)
Expand Down
2 changes: 1 addition & 1 deletion src/LettuceEncrypt/ICertificateRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public interface ICertificateRepository
/// <summary>
/// Save the certificate.
/// </summary>
/// <param name="certificate">The certificate, including its private keys</param>
/// <param name="certificate">The certificate, including its private keys.</param>
/// <param name="cancellationToken">A token which, when canceled, should stop any async operations.</param>
/// <returns>A task which completes once the certificate is done saving.</returns>
Task SaveAsync(X509Certificate2 certificate, CancellationToken cancellationToken);
Expand Down
2 changes: 1 addition & 1 deletion src/LettuceEncrypt/ICertificateSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ public interface ICertificateSource
/// Gets available certificates from the source.
/// </summary>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>A collection of certificates</returns>
/// <returns>A collection of certificates.</returns>
Task<IEnumerable<X509Certificate2>> GetCertificatesAsync(CancellationToken cancellationToken);
}
4 changes: 0 additions & 4 deletions src/LettuceEncrypt/Internal/AcmeCertificateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

#if NETSTANDARD2_0
using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;
#endif

namespace LettuceEncrypt.Internal;

internal class AcmeCertificateFactory
Expand Down
4 changes: 1 addition & 3 deletions src/LettuceEncrypt/Internal/AcmeCertificateLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,6 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
}

private bool LettuceEncryptDomainNamesWereConfigured()
{
return _options.Value.DomainNames
=> _options.Value.DomainNames
.Any(w => !string.Equals("localhost", w, StringComparison.OrdinalIgnoreCase));
}
}
11 changes: 4 additions & 7 deletions src/LettuceEncrypt/Internal/AcmeClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,9 @@ public async Task<int> CreateAccountAsync(string emailAddress)
var eabCredentials = _options.Value.EabCredentials;
_accountContext = await _context.NewAccount(emailAddress, termsOfServiceAgreed: true, eabKeyId: eabCredentials.EabKeyId, eabKey: eabCredentials.EabKey, eabKeyAlg: eabCredentials.EabKeyAlg);

if (!int.TryParse(_accountContext.Location.Segments.Last(), out var accountId))
{
accountId = 0;
}

return accountId;
return int.TryParse(_accountContext.Location.Segments.Last(), out var accountId)
? accountId
: 0;
}

public async Task<Uri> GetTermsOfServiceAsync()
Expand Down Expand Up @@ -122,5 +119,5 @@ public async Task<CertificateChain> GetCertificateAsync(CsrInfo csrInfo, IKey pr
return await order.Generate(csrInfo, privateKey);
}

private Exception MissingAccountContext() => new InvalidOperationException("Account wasn't initialized yet");
private static Exception MissingAccountContext() => new InvalidOperationException("Account wasn't initialized yet");
}
2 changes: 1 addition & 1 deletion src/LettuceEncrypt/Internal/AcmeStates/AcmeState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ internal interface IAcmeState

internal class TerminalState : IAcmeState
{
public static TerminalState Singleton { get; } = new TerminalState();
public static TerminalState Singleton { get; } = new();

private TerminalState() { }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ internal class BeginCertificateCreationState : AcmeState
private readonly CertificateSelector _selector;
private readonly IEnumerable<ICertificateRepository> _certificateRepositories;

public BeginCertificateCreationState(AcmeStateMachineContext context, ILogger<ServerStartupState> logger,
public BeginCertificateCreationState(
AcmeStateMachineContext context, ILogger<ServerStartupState> logger,
IOptions<LettuceEncryptOptions> options, AcmeCertificateFactory acmeCertificateFactory,
CertificateSelector selector, IEnumerable<ICertificateRepository> certificateRepositories) : base(context)
CertificateSelector selector, IEnumerable<ICertificateRepository> certificateRepositories)
: base(context)
{
_logger = logger;
_options = options;
Expand Down Expand Up @@ -60,9 +62,9 @@ private async Task SaveCertificateAsync(X509Certificate2 cert, CancellationToken
_selector.Add(cert);

var saveTasks = new List<Task>
{
Task.Delay(TimeSpan.FromMinutes(5), cancellationToken)
};
{
Task.Delay(TimeSpan.FromMinutes(5), cancellationToken)
};

var errors = new List<Exception>();
foreach (var repo in _certificateRepositories)
Expand Down
15 changes: 5 additions & 10 deletions src/LettuceEncrypt/Internal/CertificateSelector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public virtual void Add(X509Certificate2 certificate)
{
var selectedCert = AddWithDomainName(_certs, dnsName, certificate);

// Call preload once per certificate, but only if the cetificate is actually selected to be used
// Call preload once per certificate, but only if the certificate is actually selected to be used
// for this domain. This is a small optimization which avoids preloading on a cert that may not be used.
if (!preloaded && selectedCert == certificate)
{
Expand Down Expand Up @@ -88,7 +88,6 @@ private X509Certificate2 AddWithDomainName(ConcurrentDictionary<string, X509Cert

public X509Certificate2? Select(ConnectionContext context, string? domainName)
{
#if NETCOREAPP3_1_OR_GREATER
if (_challengeCerts.Count > 0)
{
// var sslStream = context.Features.Get<SslStream>();
Expand All @@ -102,10 +101,6 @@ private X509Certificate2 AddWithDomainName(ConcurrentDictionary<string, X509Cert
return challengeCert;
}
}
#elif NETSTANDARD2_0
#else
#error Update TFMs
#endif

if (domainName == null || !_certs.TryGetValue(domainName, out var retVal))
{
Expand All @@ -117,7 +112,7 @@ private X509Certificate2 AddWithDomainName(ConcurrentDictionary<string, X509Cert

public void Reset(string domainName)
{
_certs.TryRemove(domainName, out var _);
_certs.TryRemove(domainName, out _);
}

public bool TryGet(string domainName, out X509Certificate2? certificate)
Expand All @@ -136,9 +131,9 @@ private void PreloadIntermediateCertificates(X509Certificate2 certificate)
using var chain = new X509Chain
{
ChainPolicy =
{
RevocationMode = X509RevocationMode.NoCheck
}
{
RevocationMode = X509RevocationMode.NoCheck
}
};

var commonName = X509CertificateHelpers.GetCommonName(certificate);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

#if NETSTANDARD2_0
using IHostEnvironment = Microsoft.Extensions.Hosting.IHostingEnvironment;
#endif

namespace LettuceEncrypt.Internal;

internal class DefaultCertificateAuthorityConfiguration : ICertificateAuthorityConfiguration
Expand Down
4 changes: 0 additions & 4 deletions src/LettuceEncrypt/Internal/DeveloperCertLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

#if NETSTANDARD2_0
using IHostEnvironment = Microsoft.Extensions.Hosting.IHostingEnvironment;
#endif

namespace LettuceEncrypt.Internal;

/// <summary>
Expand Down
4 changes: 0 additions & 4 deletions src/LettuceEncrypt/Internal/DomainOwnershipValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

#if NETSTANDARD2_0
using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;
#endif

namespace LettuceEncrypt.Internal;

internal abstract class DomainOwnershipValidator
Expand Down
2 changes: 1 addition & 1 deletion src/LettuceEncrypt/Internal/FileSystemAccountStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public FileSystemAccountStore(
return default;
}

private async Task<AccountModel?> Deserialize(FileInfo jsonFile, CancellationToken cancellationToken)
private static async Task<AccountModel?> Deserialize(FileInfo jsonFile, CancellationToken cancellationToken)
{
using var fileStream = jsonFile.OpenRead();
var deserializeOptions = new JsonSerializerOptions
Expand Down
10 changes: 4 additions & 6 deletions src/LettuceEncrypt/Internal/Http01DomainValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,17 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

#if NETSTANDARD2_0
using IHostApplicationLifetime = Microsoft.Extensions.Hosting.IApplicationLifetime;
#endif

namespace LettuceEncrypt.Internal;

internal class Http01DomainValidator : DomainOwnershipValidator
{
private readonly IHttpChallengeResponseStore _challengeStore;

public Http01DomainValidator(IHttpChallengeResponseStore challengeStore,
public Http01DomainValidator(
IHttpChallengeResponseStore challengeStore,
IHostApplicationLifetime appLifetime,
AcmeClient client, ILogger logger, string domainName) : base(appLifetime, client, logger, domainName)
AcmeClient client, ILogger logger, string domainName)
: base(appLifetime, client, logger, domainName)
{
_challengeStore = challengeStore;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)

context.Response.ContentLength = value?.Length ?? 0;
context.Response.ContentType = "application/octet-stream";
await context.Response.WriteAsync(value, context.RequestAborted);
await context.Response.WriteAsync(value!, context.RequestAborted);
}
}
4 changes: 1 addition & 3 deletions src/LettuceEncrypt/Internal/IHttpChallengeResponseStore.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;

namespace LettuceEncrypt.Internal;

internal interface IHttpChallengeResponseStore
{
void AddChallengeResponse(string token, string response);

bool TryGetResponse(string token, [MaybeNullWhen(false)] out string? value);
bool TryGetResponse(string token, out string? value);
}
8 changes: 6 additions & 2 deletions src/LettuceEncrypt/Internal/IO/PhysicalConsole.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Copyright (c) Nate McMaster.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;

namespace LettuceEncrypt.Internal.IO;

internal class PhysicalConsole : IConsole
{
public static PhysicalConsole Singleton { get; } = new PhysicalConsole();
public static PhysicalConsole Singleton { get; } = new();

private PhysicalConsole()
{
Expand All @@ -25,6 +27,8 @@ public ConsoleColor ForegroundColor
set => Console.ForegroundColor = value;
}

[SuppressMessage("Interoperability", "CA1416:Validate platform compatibility",
Justification = "Annotation introduced after .NET Core 3.1. Behavior is no different in .NET 6.")]
public bool CursorVisible
{
get => Console.CursorVisible;
Expand All @@ -34,5 +38,5 @@ public bool CursorVisible
public void WriteLine(string line) => Console.WriteLine(line);
public void Write(string line) => Console.Write(line);
public void ResetColor() => Console.ResetColor();
public string ReadLine() => Console.ReadLine();
public string ReadLine() => Console.ReadLine()!;
}
Loading

0 comments on commit 2ca07d2

Please sign in to comment.