@@ -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,74 @@
|
||||
using System.Threading.RateLimiting;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace StartupHelpers;
|
||||
|
||||
public static class RateLimitingExtensions
|
||||
{
|
||||
public static void AddPublicApiRateLimiting(this IServiceCollection services)
|
||||
{
|
||||
services.AddRateLimiter(options =>
|
||||
{
|
||||
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(
|
||||
partitionKey: ip,
|
||||
factory: _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 120,
|
||||
Window = TimeSpan.FromMinutes(1),
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
});
|
||||
});
|
||||
|
||||
options.AddPolicy("contact", httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(
|
||||
partitionKey: ip,
|
||||
factory: _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 5,
|
||||
Window = TimeSpan.FromMinutes(1),
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
});
|
||||
});
|
||||
|
||||
options.AddPolicy("cv-matcher", httpContext =>
|
||||
{
|
||||
var ip = httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
|
||||
return RateLimitPartition.GetFixedWindowLimiter(
|
||||
partitionKey: ip,
|
||||
factory: _ => new FixedWindowRateLimiterOptions
|
||||
{
|
||||
PermitLimit = 10,
|
||||
Window = TimeSpan.FromMinutes(10),
|
||||
QueueLimit = 0,
|
||||
AutoReplenishment = true
|
||||
});
|
||||
});
|
||||
|
||||
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,229 @@
|
||||
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";
|
||||
});
|
||||
}
|
||||
|
||||
public static void MapHealthEndpoint(this WebApplication app, string serviceName, string appVersion)
|
||||
{
|
||||
app.MapGet("/health", () => Results.Ok(new
|
||||
{
|
||||
status = "ok",
|
||||
service = serviceName,
|
||||
version = appVersion,
|
||||
timeUtc = DateTimeOffset.UtcNow
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RootNamespace>startup_helpers</RootNamespace>
|
||||
<RootNamespace>StartupHelpers</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.5.1" />
|
||||
<PackageReference Include="Azure.Identity" Version="1.21.0" />
|
||||
<PackageReference Include="DotNetEnv" Version="3.2.0" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Enrichers.Environment" Version="3.0.1" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.1.7" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="10.1.7" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user