< Summary

Information
Class: ProjectTemplate.Web.Extensions.DataProtectionServiceExtensions
Assembly: ProjectTemplate.Web
File(s): /home/runner/work/NetCoreApplicationTemplate/NetCoreApplicationTemplate/src/ProjectTemplate.Web/Extensions/DataProtectionServiceExtensions.cs
Line coverage
95%
Covered lines: 67
Uncovered lines: 3
Coverable lines: 70
Total lines: 137
Line coverage: 95.7%
Branch coverage
81%
Covered branches: 13
Total branches: 16
Branch coverage: 81.2%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
AddApplicationDataProtection(...)75%44100%
ResolveRequiredSetting(...)100%44100%
LoadKeyEncryptionCertificate(...)75%8883.33%

File(s)

/home/runner/work/NetCoreApplicationTemplate/NetCoreApplicationTemplate/src/ProjectTemplate.Web/Extensions/DataProtectionServiceExtensions.cs

#LineLine coverage
 1using System.Security.Cryptography.X509Certificates;
 2using Microsoft.AspNetCore.DataProtection;
 3using ProjectTemplate.Web.Options;
 4
 5namespace ProjectTemplate.Web.Extensions;
 6
 7/// <summary>
 8/// Provides extension methods for configuring the persistent ASP.NET Core Data Protection key ring.
 9/// </summary>
 10public static class DataProtectionServiceExtensions
 11{
 12    private const string _keyEncryptionPasswordWithoutPathMessage =
 13        "ProjectTemplate:DataProtection:KeyEncryptionCertificatePassword requires KeyEncryptionCertificatePath.";
 14
 15    /// <summary>
 16    /// Registers Data Protection with a stable application discriminator and persistent filesystem key ring.
 17    /// </summary>
 18    /// <param name="services">The service collection to configure.</param>
 19    /// <param name="configuration">The application configuration source.</param>
 20    /// <param name="environment">The current hosting environment.</param>
 21    /// <returns>The same service collection instance for chaining.</returns>
 22    public static IServiceCollection AddApplicationDataProtection(
 23        this IServiceCollection services,
 24        IConfiguration configuration,
 25        IHostEnvironment environment)
 26    {
 12627        ArgumentNullException.ThrowIfNull(services);
 12628        ArgumentNullException.ThrowIfNull(configuration);
 12629        ArgumentNullException.ThrowIfNull(environment);
 30
 12631        IConfigurationSection section = configuration.GetSection(ApplicationDataProtectionOptions.SectionName);
 32
 12633        services
 12634            .AddOptions<ApplicationDataProtectionOptions>()
 12635            .Bind(section)
 12636            .Validate(
 12637                options => !string.IsNullOrWhiteSpace(options.ApplicationName),
 12638                "ProjectTemplate:DataProtection:ApplicationName is required.")
 12639            .Validate(
 12640                options => !string.IsNullOrWhiteSpace(options.KeyRingPath),
 12641                "ProjectTemplate:DataProtection:KeyRingPath is required.")
 12642            .Validate(
 12643                options => string.IsNullOrEmpty(options.KeyEncryptionCertificatePassword) ||
 12644                    !string.IsNullOrWhiteSpace(options.KeyEncryptionCertificatePath),
 12645                _keyEncryptionPasswordWithoutPathMessage)
 12646            .ValidateOnStart();
 47
 12648        ApplicationDataProtectionOptions defaults = new();
 49
 12650        string applicationName = ResolveRequiredSetting(
 12651            section[nameof(ApplicationDataProtectionOptions.ApplicationName)],
 12652            defaults.ApplicationName,
 12653            $"{ApplicationDataProtectionOptions.SectionName}:ApplicationName");
 12554        string configuredKeyRingPath = ResolveRequiredSetting(
 12555            section[nameof(ApplicationDataProtectionOptions.KeyRingPath)],
 12556            defaults.KeyRingPath,
 12557            $"{ApplicationDataProtectionOptions.SectionName}:KeyRingPath");
 12458        string keyRingPath = Path.IsPathFullyQualified(configuredKeyRingPath)
 12459            ? configuredKeyRingPath
 12460            : Path.GetFullPath(configuredKeyRingPath, environment.ContentRootPath);
 61
 12462        IDataProtectionBuilder dataProtectionBuilder = services
 12463            .AddDataProtection()
 12464            .SetApplicationName(applicationName)
 12465            .PersistKeysToFileSystem(new DirectoryInfo(keyRingPath));
 66
 12467        string? configuredCertificatePath = section[nameof(ApplicationDataProtectionOptions.KeyEncryptionCertificatePath
 12468        string? configuredCertificatePassword = section[nameof(ApplicationDataProtectionOptions.KeyEncryptionCertificate
 69
 12470        if (!string.IsNullOrWhiteSpace(configuredCertificatePath))
 71        {
 372            X509Certificate2 keyEncryptionCertificate = LoadKeyEncryptionCertificate(
 373                configuredCertificatePath.Trim(),
 374                configuredCertificatePassword,
 375                environment.ContentRootPath);
 76
 77            // ProtectKeysWithCertificate encrypts new keys. UnprotectKeysWithAnyCertificate supplies the same
 78            // certificate for decryption, which is required on Linux and macOS where the framework cannot resolve it
 79            // from a certificate store by thumbprint.
 280            _ = dataProtectionBuilder
 281                .ProtectKeysWithCertificate(keyEncryptionCertificate)
 282                .UnprotectKeysWithAnyCertificate(keyEncryptionCertificate);
 83        }
 84
 12385        return services;
 86    }
 87
 88    private static string ResolveRequiredSetting(
 89        string? configuredValue,
 90        string defaultValue,
 91        string settingName)
 92    {
 25193        return configuredValue switch
 25194        {
 195            null => defaultValue,
 25096            var value when string.IsNullOrWhiteSpace(value) =>
 297                throw new InvalidOperationException($"{settingName} is required."),
 24898            var value => value.Trim()
 25199        };
 100    }
 101
 102    private static X509Certificate2 LoadKeyEncryptionCertificate(
 103        string configuredCertificatePath,
 104        string? password,
 105        string contentRootPath)
 106    {
 3107        string certificatePath = Path.IsPathFullyQualified(configuredCertificatePath)
 3108            ? configuredCertificatePath
 3109            : Path.GetFullPath(configuredCertificatePath, contentRootPath);
 110
 3111        if (!File.Exists(certificatePath))
 112        {
 1113            throw new InvalidOperationException(
 1114                $"ProjectTemplate:DataProtection:KeyEncryptionCertificatePath '{certificatePath}' was not found.");
 115        }
 116
 117        // EphemeralKeySet avoids writing the private key to the user profile or machine key store. macOS does not
 118        // support ephemeral key sets, so the default storage is used there.
 2119        X509KeyStorageFlags keyStorageFlags = OperatingSystem.IsMacOS()
 2120            ? X509KeyStorageFlags.DefaultKeySet
 2121            : X509KeyStorageFlags.EphemeralKeySet;
 122
 2123        X509Certificate2 certificate = X509CertificateLoader.LoadPkcs12FromFile(
 2124            certificatePath,
 2125            password,
 2126            keyStorageFlags);
 127
 2128        if (!certificate.HasPrivateKey)
 129        {
 0130            certificate.Dispose();
 0131            throw new InvalidOperationException(
 0132                "ProjectTemplate:DataProtection:KeyEncryptionCertificatePath must reference a certificate that includes 
 133        }
 134
 2135        return certificate;
 136    }
 137}