Adds Infrastructure security cryptography service (#43)

* Adds Infrastructure security cryptography service

* Updates GitHub Action script to account for empty Environment values

* Updates section of GitHub Action script

* Fixes order of configuration settings import

* Hardcodes secrets used during integration tests
This commit is contained in:
BinaryAlley authored and GitHub committed 2024-11-06 19:11:03 +02:00
1 parent a71487eb05
commit 09928047d0
12 files changed
+280 -8

No files matched your search

@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Infrastructure;
/// <summary>
/// Interface for the service for cryptographic concerns.
/// </summary>
public interface ICryptographyService
{
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
string Encrypt(string plaintext);
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
string Decrypt(string ciphertext);
}
@@ -23,7 +23,8 @@ public static class InfrastructureLayerServices
// scan the current assembly for validators and add them to the DI container
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
services.AddTransient<IHashService, HashService>();
services.AddSingleton<IHashService, HashService>();
services.AddSingleton<ICryptographyService, CryptographyService>();
return services;
}
}
@@ -43,12 +43,21 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<MediaSettingsModel>()
.Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<JwtSettingsModel>()
.Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
services.AddOptions<EncryptionSettingsModel>()
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
return services;
}
}
@@ -14,5 +14,12 @@ public static partial class Errors
public static Error ApplicationThemeCannotBeEmpty => Error.Validation(description: nameof(ApplicationThemeCannotBeEmpty));
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty));
public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty));
public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty));
public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String));
public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty));
public static Error JwtSecretKeyTooShort => Error.Validation(description: nameof(JwtSecretKeyTooShort));
public static Error JwtExpiryMinutesMustBePositive => Error.Validation(description: nameof(JwtExpiryMinutesMustBePositive));
public static Error JwtIssuerCannotBeEmpty => Error.Validation(description: nameof(JwtIssuerCannotBeEmpty));
public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty));
}
}
@@ -0,0 +1,19 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class EncryptionSettingsModel
{
public const string SECTION_NAME = "EncryptionSettings";
/// <summary>
/// Gets or sets the root directory where media files are stored.
/// </summary>
public required string SecretKey { get; init; }
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Infrastructure.Common.Models.Configuration;
/// <summary>
/// Model for deserializing media settings.
/// </summary>
[DebuggerDisplay("{SECTION_NAME}")]
public class JwtSettingsModel
{
public const string SECTION_NAME = "JwtSettings";
/// <summary>
/// The secret key used to sign the JWT. This should be a strong, securely stored key.
/// </summary>
public required string SecretKey { get; init; }
/// <summary>
/// The duration (in minutes) for which the JWT is valid.
/// </summary>
public required int ExpiryMinutes { get; init; }
/// <summary>
/// The issuer of the JWT, typically the application or service generating the token.
/// </summary>
public required string Issuer { get; init; }
/// <summary>
/// The intended audience for the JWT, usually representing the clients that can consume the token.
/// </summary>
public required string Audience { get; init; }
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
using System;
using System.Buffers.Text;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
/// </summary>
public class EncryptionSettingsModelValidator : AbstractValidator<EncryptionSettingsModel>
{
/// <summary>
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidator"/> class.
/// </summary>
public EncryptionSettingsModelValidator()
{
RuleFor(x => x.SecretKey)
.NotEmpty().WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description)
.Must(value => Base64.IsValid(value.AsSpan())).WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description);
}
}
@@ -0,0 +1,36 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
/// <summary>
/// Validates the needed validation rules for the JwtSettings application configuration settings section.
/// </summary>
public class JwtSettingsModelValidator : AbstractValidator<JwtSettingsModel>
{
/// <summary>
/// Initializes a new instance of the <see cref="JwtSettingsModelValidator"/> class.
/// </summary>
public JwtSettingsModelValidator()
{
RuleFor(x => x.SecretKey)
.NotEmpty()
.WithMessage(Errors.Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description)
.MinimumLength(32)
.WithMessage(Errors.Errors.Configuration.JwtSecretKeyTooShort.Description);
RuleFor(x => x.ExpiryMinutes)
.GreaterThan(0)
.WithMessage(Errors.Errors.Configuration.JwtExpiryMinutesMustBePositive.Description);
RuleFor(x => x.Issuer)
.NotEmpty()
.WithMessage(Errors.Errors.Configuration.JwtIssuerCannotBeEmpty.Description);
RuleFor(x => x.Audience)
.NotEmpty()
.WithMessage(Errors.Errors.Configuration.JwtAudienceCannotBeEmpty.Description);
}
}
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
#endregion
namespace Lumina.Infrastructure.Common.Validators;
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure;
using Lumina.Infrastructure.Common.Models.Configuration;
using Microsoft.Extensions.Options;
using System;
using System.Security.Cryptography;
using System.Text;
#endregion
namespace Lumina.Infrastructure.Core.Security;
/// <summary>
/// Service for cryptographic concerns.
/// </summary>
public sealed class CryptographyService : ICryptographyService, IDisposable
{
private readonly byte[] _key;
/// <summary>
/// Initializes a new instance of the <see cref="CryptographyService"/> class.
/// </summary>
/// <param name="encryptionSettingsModelOptions">Injected service for retrieving <see cref="EncryptionSettingsModel"/>.</param>
public CryptographyService(IOptions<EncryptionSettingsModel> encryptionSettingsModelOptions)
{
_key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey);
}
/// <summary>
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
/// </summary>
/// <param name="plaintext">The plaintext string to encrypt.</param>
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
public string Encrypt(string plaintext)
{
if (string.IsNullOrEmpty(plaintext))
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
// generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
byte[] iv = new byte[16];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
rng.GetBytes(iv);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform encryptor = aes.CreateEncryptor();
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
// combine IV and ciphertext
byte[] combined = new byte[iv.Length + ciphertext.Length];
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
return Convert.ToBase64String(combined);
}
/// <summary>
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
/// </summary>
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
/// <returns>The decrypted plaintext string.</returns>
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
public string Decrypt(string ciphertext)
{
if (string.IsNullOrEmpty(ciphertext))
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
// decode the combined data (IV + ciphertext) from Base64
byte[] combined = Convert.FromBase64String(ciphertext);
if (combined.Length < 16)
throw new ArgumentException("Invalid ciphertext");
// extract IV and ciphertext
byte[] iv = new byte[16];
byte[] encryptedData = new byte[combined.Length - 16];
Buffer.BlockCopy(combined, 0, iv, 0, 16);
Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length);
using Aes aes = Aes.Create();
aes.Key = _key;
aes.IV = iv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
using ICryptoTransform decryptor = aes.CreateDecryptor();
byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.UTF8.GetString(decrypted);
}
/// <summary>
/// Clears sensitive key data when the service is disposed.
/// </summary>
public void Dispose()
{
Array.Clear(_key, 0, _key.Length);
}
}
@@ -1,4 +1,13 @@
{
"JwtSettings": {
"SecretKey": "",
"ExpiryMinutes": 60,
"Issuer": "Lumina",
"Audience": "Lumina"
},
"EncryptionSettings": {
"SecretKey": "" // base64 string
},
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {