From 09928047d0227ad9035f5878c595b60f66341b41 Mon Sep 17 00:00:00 2001
From: BinaryAlley <147156862+BinaryAlley@users.noreply.github.com>
Date: Wed, 6 Nov 2024 19:11:03 +0200
Subject: [PATCH] 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
---
.../Infrastructure/ICryptographyService.cs | 27 +++++
.../InfrastructureLayerServices.cs | 3 +-
.../SharedConfiguration.cs | 11 +-
.../Common/Errors/Errors.Configuration.cs | 7 ++
.../Configuration/EncryptionSettingsModel.cs | 19 ++++
.../Models/Configuration/JwtSettingsModel.cs | 34 ++++++
.../EncryptionSettingsModelValidator.cs | 24 ++++
.../Validators/JwtSettingsModelValidator.cs | 36 ++++++
.../Validators/MediaSettingsModelValidator.cs | 1 -
.../Core/Security/CryptographyService.cs | 103 ++++++++++++++++++
src/Lumina.Presentation.Api/appsettings.json | 9 ++
.../Common/Setup/LuminaApiFactory.cs | 14 ++-
12 files changed, 280 insertions(+), 8 deletions(-)
create mode 100644 src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs
create mode 100644 src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs
create mode 100644 src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs
create mode 100644 src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs
create mode 100644 src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs
create mode 100644 src/Lumina.Infrastructure/Core/Security/CryptographyService.cs
diff --git a/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs b/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs
new file mode 100644
index 00000000..197ee8c9
--- /dev/null
+++ b/src/Lumina.Application/Common/Infrastructure/ICryptographyService.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Application.Common.Infrastructure;
+
+///
+/// Interface for the service for cryptographic concerns.
+///
+public interface ICryptographyService
+{
+ ///
+ /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
+ ///
+ /// The plaintext string to encrypt.
+ /// A Base64-encoded string of the combined IV and encrypted ciphertext.
+ /// Thrown when is or empty.
+ string Encrypt(string plaintext);
+
+ ///
+ /// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
+ ///
+ /// The Base64-encoded string containing both IV and ciphertext.
+ /// The decrypted plaintext string.
+ /// Thrown when is , empty, or invalid.
+ string Decrypt(string ciphertext);
+}
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
index 3b94555a..c08c6e2e 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs
@@ -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();
+ services.AddSingleton();
+ services.AddSingleton();
return services;
}
}
diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
index bdd205dd..877c375b 100644
--- a/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
+++ b/src/Lumina.Infrastructure/Common/DependencyInjection/SharedConfiguration.cs
@@ -43,12 +43,21 @@ public static class SharedConfiguration
.ValidateFluently()
.ValidateOnStart();
-
services.AddOptions()
.Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME))
.ValidateFluently()
.ValidateOnStart();
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME))
+ .ValidateFluently()
+ .ValidateOnStart();
+
+ services.AddOptions()
+ .Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
+ .ValidateFluently()
+ .ValidateOnStart();
+
return services;
}
}
diff --git a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
index e37f6112..94fb3220 100644
--- a/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
+++ b/src/Lumina.Infrastructure/Common/Errors/Errors.Configuration.cs
@@ -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));
}
}
diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs
new file mode 100644
index 00000000..5a672e71
--- /dev/null
+++ b/src/Lumina.Infrastructure/Common/Models/Configuration/EncryptionSettingsModel.cs
@@ -0,0 +1,19 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Infrastructure.Common.Models.Configuration;
+
+///
+/// Model for deserializing media settings.
+///
+[DebuggerDisplay("{SECTION_NAME}")]
+public class EncryptionSettingsModel
+{
+ public const string SECTION_NAME = "EncryptionSettings";
+
+ ///
+ /// Gets or sets the root directory where media files are stored.
+ ///
+ public required string SecretKey { get; init; }
+}
diff --git a/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs b/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs
new file mode 100644
index 00000000..0ac5f6ff
--- /dev/null
+++ b/src/Lumina.Infrastructure/Common/Models/Configuration/JwtSettingsModel.cs
@@ -0,0 +1,34 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Infrastructure.Common.Models.Configuration;
+
+///
+/// Model for deserializing media settings.
+///
+[DebuggerDisplay("{SECTION_NAME}")]
+public class JwtSettingsModel
+{
+ public const string SECTION_NAME = "JwtSettings";
+
+ ///
+ /// The secret key used to sign the JWT. This should be a strong, securely stored key.
+ ///
+ public required string SecretKey { get; init; }
+
+ ///
+ /// The duration (in minutes) for which the JWT is valid.
+ ///
+ public required int ExpiryMinutes { get; init; }
+
+ ///
+ /// The issuer of the JWT, typically the application or service generating the token.
+ ///
+ public required string Issuer { get; init; }
+
+ ///
+ /// The intended audience for the JWT, usually representing the clients that can consume the token.
+ ///
+ public required string Audience { get; init; }
+}
diff --git a/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs
new file mode 100644
index 00000000..b95344fe
--- /dev/null
+++ b/src/Lumina.Infrastructure/Common/Validators/EncryptionSettingsModelValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
+///
+public class EncryptionSettingsModelValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ 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);
+ }
+}
diff --git a/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs
new file mode 100644
index 00000000..47201c97
--- /dev/null
+++ b/src/Lumina.Infrastructure/Common/Validators/JwtSettingsModelValidator.cs
@@ -0,0 +1,36 @@
+#region ========================================================================= USING =====================================================================================
+using FluentValidation;
+using Lumina.Infrastructure.Common.Models.Configuration;
+#endregion
+
+namespace Lumina.Infrastructure.Common.Validators;
+
+///
+/// Validates the needed validation rules for the JwtSettings application configuration settings section.
+///
+public class JwtSettingsModelValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ 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);
+ }
+}
diff --git a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs
index f42a018f..caf6d52e 100644
--- a/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs
+++ b/src/Lumina.Infrastructure/Common/Validators/MediaSettingsModelValidator.cs
@@ -1,7 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Infrastructure.Common.Models.Configuration;
-
#endregion
namespace Lumina.Infrastructure.Common.Validators;
diff --git a/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs
new file mode 100644
index 00000000..f222f63c
--- /dev/null
+++ b/src/Lumina.Infrastructure/Core/Security/CryptographyService.cs
@@ -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;
+
+///
+/// Service for cryptographic concerns.
+///
+public sealed class CryptographyService : ICryptographyService, IDisposable
+{
+ private readonly byte[] _key;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for retrieving .
+ public CryptographyService(IOptions encryptionSettingsModelOptions)
+ {
+ _key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey);
+ }
+
+ ///
+ /// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
+ ///
+ /// The plaintext string to encrypt.
+ /// A Base64-encoded string of the combined IV and encrypted ciphertext.
+ /// Thrown when is or empty.
+ 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);
+ }
+
+ ///
+ /// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
+ ///
+ /// The Base64-encoded string containing both IV and ciphertext.
+ /// The decrypted plaintext string.
+ /// Thrown when is , empty, or invalid.
+ 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);
+ }
+
+ ///
+ /// Clears sensitive key data when the service is disposed.
+ ///
+ public void Dispose()
+ {
+ Array.Clear(_key, 0, _key.Length);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/appsettings.json b/src/Lumina.Presentation.Api/appsettings.json
index f5281223..2db1c53f 100644
--- a/src/Lumina.Presentation.Api/appsettings.json
+++ b/src/Lumina.Presentation.Api/appsettings.json
@@ -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": {
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs
index b71a7373..434c29c2 100644
--- a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Common/Setup/LuminaApiFactory.cs
@@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
+using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
@@ -41,13 +42,16 @@ public class LuminaApiFactory : WebApplicationFactory, IDisposable
// clear all existing configuration sources
config.Sources.Clear();
- // add environment variables coming from CI secrets
- config.AddEnvironmentVariables();
-
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
- config.AddJsonFile($"appsettings.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+ config.AddJsonFile($"appsettings.test.json", optional: true, reloadOnChange: true);
config.AddJsonFile("appsettings.shared.json", optional: true, reloadOnChange: true);
- config.AddJsonFile($"appsettings.shared.{context.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
+ config.AddJsonFile($"appsettings.shared.test.json", optional: true, reloadOnChange: true);
+ // First add the test values directly
+ config.AddInMemoryCollection(initialData: new Dictionary
+ {
+ ["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
+ ["EncryptionSettings:SecretKey"] = "dGVzdC1rZXktdGhhdHMtYXQtbGVhc3QtMzItY2hhcnMtbG9uZy1mb3ItZW5jcnlwdGlvbg==" // base64 encoded test key
+ });
});
builder.ConfigureServices(services =>
{