Changes
Build and Push Docker Images / build (push) Successful in 4m35s

This commit is contained in:
2026-05-14 14:12:29 +03:00
parent 92278ae375
commit 75bc9509c5
137 changed files with 0 additions and 371 deletions
+14
View File
@@ -0,0 +1,14 @@
using System.Security.Cryptography;
using System.Text;
namespace CommonHelpers
{
public static class HashHelper
{
public static string Compute(string value)
{
using var sha = SHA256.Create();
return Convert.ToHexString(sha.ComputeHash(Encoding.UTF8.GetBytes(value ?? string.Empty)));
}
}
}
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<RootNamespace>CommonHelpers</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -0,0 +1,23 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shared.Models.Settings;
namespace StartupHelpers;
public static class DatabaseExtensions
{
public static string GetConfiguredDbConnectionString(this IServiceCollection services, IConfiguration configuration)
{
var dbOptions = configuration
.GetSection("Database")
.Get<DatabaseSettings>()
?? throw new InvalidOperationException("Database config missing");
return
$"Server={dbOptions.Host},{dbOptions.Port};" +
$"Database={dbOptions.Name};" +
$"User Id={dbOptions.User};" +
$"Password={dbOptions.Password};" +
$"TrustServerCertificate={dbOptions.TrustServerCertificate};";
}
}
@@ -0,0 +1,92 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace StartupHelpers;
public static class EnvironmentDiagnostics
{
public static void LogEnvironmentSettings(ILogger logger, IConfiguration configuration, IWebHostEnvironment environment)
{
logger.LogInformation("==================== ENVIRONMENT SETTINGS ====================");
logger.LogInformation("Application Name: {ApplicationName}", environment.ApplicationName);
logger.LogInformation("Environment Name: {EnvironmentName}", environment.EnvironmentName);
logger.LogInformation("Content Root Path: {ContentRootPath}", environment.ContentRootPath);
logger.LogInformation("Web Root Path: {WebRootPath}", environment.WebRootPath);
logger.LogInformation("-------------- Environment Variables --------------");
var envVars = Environment.GetEnvironmentVariables();
var sortedEnvVars = new SortedDictionary<string, string?>();
foreach (System.Collections.DictionaryEntry entry in envVars)
{
var key = entry.Key?.ToString() ?? string.Empty;
var value = entry.Value?.ToString() ?? string.Empty;
if (IsSensitiveKey(key))
{
value = MaskValueWithLastChars(value);
}
sortedEnvVars[key] = value;
}
foreach (var kvp in sortedEnvVars)
{
logger.LogInformation(" {Key} = {Value}", kvp.Key, kvp.Value);
}
logger.LogInformation("-------------- Configuration Settings --------------");
LogConfigurationRecursive(logger, configuration.GetChildren(), string.Empty);
logger.LogInformation("===========================================================");
}
private static void LogConfigurationRecursive(ILogger logger, IEnumerable<IConfigurationSection> sections, string prefix)
{
foreach (var section in sections)
{
var key = string.IsNullOrEmpty(prefix) ? section.Key : $"{prefix}:{section.Key}";
if (section.Value != null)
{
var value = section.Value;
if (IsSensitiveKey(key))
{
value = MaskValueWithLastChars(value);
}
logger.LogInformation(" {Key} = {Value}", key, value);
}
if (section.GetChildren().Any())
{
LogConfigurationRecursive(logger, section.GetChildren(), key);
}
}
}
private static bool IsSensitiveKey(string key)
{
return key.Contains("Password", StringComparison.OrdinalIgnoreCase)
|| key.Contains("Secret", StringComparison.OrdinalIgnoreCase)
|| key.Contains("Token", StringComparison.OrdinalIgnoreCase)
|| key.Contains("Key", StringComparison.OrdinalIgnoreCase)
|| key.Contains("ConnectionString", StringComparison.OrdinalIgnoreCase);
}
private static string MaskValueWithLastChars(string value)
{
if (string.IsNullOrEmpty(value))
{
return "***NOT SET***";
}
if (value.Length <= 4)
{
return "***MASKED***";
}
var lastChars = value[^4..];
return $"***MASKED***...{lastChars}";
}
}
@@ -0,0 +1,75 @@
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Shared.Models.Settings;
namespace StartupHelpers;
public static class RateLimitingExtensions
{
public static void AddPublicApiRateLimiting(
this IServiceCollection services,
IConfiguration configuration,
string sectionName = "RateLimiting")
{
var settings = configuration.GetSection(sectionName).Get<RateLimitingSettings>()
?? new RateLimitingSettings();
services.AddRateLimiter(options =>
{
var global = settings.Global ?? new RateLimitPolicySettings();
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: ip,
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = global.PermitLimit,
Window = global.Window,
QueueLimit = global.QueueLimit,
AutoReplenishment = global.AutoReplenishment
});
});
foreach (var entry in settings.Policies)
{
var policyName = entry.Key;
var policy = entry.Value ?? new RateLimitPolicySettings();
options.AddPolicy(policyName, httpContext =>
{
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(
partitionKey: ip,
factory: _ => new FixedWindowRateLimiterOptions
{
PermitLimit = policy.PermitLimit,
Window = policy.Window,
QueueLimit = policy.QueueLimit,
AutoReplenishment = policy.AutoReplenishment
});
});
}
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.OnRejected = async (context, ct) =>
{
var logger = context.HttpContext.RequestServices
.GetRequiredService<ILoggerFactory>()
.CreateLogger("RateLimiting");
var ip = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
var endpoint = context.HttpContext.Request.Path;
logger.LogWarning("Rate limit exceeded for {Endpoint} from IP {IP}", endpoint, ip);
context.HttpContext.Response.ContentType = "application/json";
await context.HttpContext.Response.WriteAsync("""{"error":"Too many requests. Try again later."}""", ct);
};
});
}
}
@@ -0,0 +1,218 @@
using System.Reflection;
using Azure.Identity;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.Annotations;
namespace StartupHelpers;
public static class StartupExtensions
{
public static void LoadDotEnvFile()
{
DotNetEnv.Env.Load();
}
public static string GetApplicationVersion(Assembly assembly)
{
return assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
?? assembly.GetName().Version?.ToString()
?? "unknown";
}
public static void ConfigureJsonSerilog(this WebApplicationBuilder builder, string serviceName, string appVersion)
{
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.Enrich.WithMachineName()
.Enrich.WithEnvironmentName()
.Enrich.WithProperty("Service", serviceName)
.Enrich.WithProperty("AppVersion", appVersion)
.WriteTo.Console(new Serilog.Formatting.Json.JsonFormatter());
});
}
public static void AddAzureKeyVaultIfConfigured(this WebApplicationBuilder builder)
{
var keyVaultUri = builder.Configuration["KeyVault:VaultUri"];
var keyVaultEnabled = builder.Configuration.GetValue<bool>("KeyVault:Enabled");
if (!keyVaultEnabled || string.IsNullOrWhiteSpace(keyVaultUri))
{
Log.Information("Azure Key Vault is disabled or not configured");
return;
}
Log.Information("Loading configuration from Azure Key Vault: {VaultUri}", keyVaultUri);
try
{
builder.Configuration.AddAzureKeyVault(new Uri(keyVaultUri), new DefaultAzureCredential());
Log.Information("Azure Key Vault configuration loaded successfully");
}
catch (Exception ex)
{
Log.Warning(ex, "Failed to load Azure Key Vault configuration. Continuing with other configuration sources.");
}
}
public static void AddSwaggerWithXmlComments(this IServiceCollection services, Assembly assembly, string fallbackName, bool enableAnnotations = true)
{
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(options =>
{
var xmlFile = (assembly.GetName().Name ?? fallbackName) + ".xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
options.IncludeXmlComments(xmlPath);
}
if (enableAnnotations)
{
options.EnableAnnotations();
}
});
}
public static void ConfigureCaddyForwardedHeaders(this IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
options.ForwardedForHeaderName = "X-Real-IP";
options.KnownIPNetworks.Clear();
options.KnownProxies.Clear();
options.ForwardLimit = 1;
});
}
public static void AddFrontendCorsFromConfiguration(this IServiceCollection services, IConfiguration configuration, string policyName = "FrontendOnly")
{
var allowedOrigins = configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
services.AddCors(options =>
{
options.AddPolicy(policyName, policy =>
{
if (allowedOrigins.Length > 0)
{
policy.WithOrigins(allowedOrigins)
.WithMethods("POST", "OPTIONS")
.WithHeaders("Content-Type")
.SetPreflightMaxAge(TimeSpan.FromHours(1));
}
});
});
}
public static void LogStartupDiagnostics(this WebApplication app, string serviceName)
{
var logger = app.Services.GetRequiredService<ILoggerFactory>().CreateLogger(serviceName);
logger.LogInformation("{Service} starting up...", serviceName);
logger.LogInformation("Environment: {Environment}", app.Environment.EnvironmentName);
var logEnvironmentOnStartup = app.Configuration.GetValue("LogEnvironmentOnStartup", defaultValue: true);
if (logEnvironmentOnStartup)
{
EnvironmentDiagnostics.LogEnvironmentSettings(logger, app.Configuration, app.Environment);
}
}
public static void UseDefaultSerilogRequestLogging(this WebApplication app, bool includeProxyHeaders = false)
{
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms";
options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
{
diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
diagnosticContext.Set("RemoteIP", httpContext.Connection.RemoteIpAddress?.ToString());
diagnosticContext.Set("UserAgent", httpContext.Request.Headers.UserAgent.ToString());
if (includeProxyHeaders)
{
diagnosticContext.Set("XRealIP", httpContext.Request.Headers["X-Real-IP"].ToString());
diagnosticContext.Set("XForwardedFor", httpContext.Request.Headers["X-Forwarded-For"].ToString());
}
};
});
}
public static void UseJsonExceptionHandler(this WebApplication app, string serviceName)
{
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var feature = context.Features.Get<IExceptionHandlerFeature>();
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger(serviceName);
if (feature?.Error is not null)
{
logger.LogError(feature.Error, "Unhandled exception in {Service}", serviceName);
}
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
context.Response.ContentType = "application/json";
await context.Response.WriteAsJsonAsync(new { error = "Unexpected server error." });
});
});
}
public static void UseInternalApiKeyProtection(this WebApplication app, string sectionName = "InternalApi")
{
app.Use(async (context, next) =>
{
var requireApiKey = context.RequestServices.GetRequiredService<IConfiguration>().GetValue<bool>($"{sectionName}:RequireApiKey");
if (requireApiKey)
{
var configuredApiKey = context.RequestServices.GetRequiredService<IConfiguration>()[$"{sectionName}:ApiKey"];
var headerApiKey = context.Request.Headers["X-Internal-Api-Key"].ToString();
if (string.IsNullOrWhiteSpace(configuredApiKey) || headerApiKey != configuredApiKey)
{
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("InternalApiKey");
logger.LogWarning(
"Rejected unauthorized internal API call. Path={Path}, RemoteIP={RemoteIP}",
context.Request.Path,
context.Connection.RemoteIpAddress?.ToString());
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
await context.Response.WriteAsJsonAsync(new { error = "Unauthorized internal API call." });
return;
}
}
await next();
});
}
public static void UseSwaggerInDevelopment(this WebApplication app, string documentTitle, string endpointName)
{
if (!app.Environment.IsDevelopment())
{
return;
}
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.DocumentTitle = documentTitle;
options.SwaggerEndpoint("/swagger/v1/swagger.json", $"{endpointName} v1");
options.RoutePrefix = "swagger";
});
}
}