+22
-11
@@ -1,15 +1,26 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
|
||||
COPY rag-api/rag-api.csproj rag-api/
|
||||
COPY rag-api-models/rag-api-models.csproj rag-api-models/
|
||||
COPY shared-models/shared-models.csproj shared-models/
|
||||
COPY startup-helpers/startup-helpers.csproj startup-helpers/startup-helpers/
|
||||
|
||||
RUN dotnet restore rag-api/api.csproj
|
||||
|
||||
COPY rag-api/ rag-api/
|
||||
COPY rag-api-models/ rag-api-models/
|
||||
COPY shared-models/ shared-models/
|
||||
COPY startup-helpers/ startup-helpers/
|
||||
|
||||
RUN dotnet publish rag-api/rag-api.csproj -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
|
||||
WORKDIR /app
|
||||
EXPOSE 8080
|
||||
ENV ASPNETCORE_URLS=http://0.0.0.0:8080
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
COPY ["rag-api.csproj", "./"]
|
||||
RUN dotnet restore "rag-api.csproj"
|
||||
COPY . .
|
||||
RUN dotnet publish "rag-api.csproj" -c Release -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
ENTRYPOINT ["dotnet", "rag-api.dll"]
|
||||
|
||||
ENTRYPOINT ["dotnet", "rag-api.dll"]
|
||||
+25
-233
@@ -1,71 +1,30 @@
|
||||
using Azure.Identity;
|
||||
using Microsoft.AspNetCore.Diagnostics;
|
||||
using System.Reflection;
|
||||
using Api.Clients.Ai;
|
||||
using Api.Clients.Ai.Contracts;
|
||||
using Api.Data;
|
||||
using Api.Data.Repositories;
|
||||
using Api.Data.Repositories.Contracts;
|
||||
using Api.Services;
|
||||
using Api.Services.Contracts;
|
||||
using Serilog;
|
||||
using System.Reflection;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Rag.Models.Settings;
|
||||
using Api.Data.Repositories.Contracts;
|
||||
using Api.Data.Repositories;
|
||||
using Api.Clients.Ai.Contracts;
|
||||
using Api.Clients.Ai;
|
||||
using Serilog;
|
||||
using Shared.Models.Settings;
|
||||
using StartupHelpers;
|
||||
|
||||
DotNetEnv.Env.Load();
|
||||
StartupExtensions.LoadDotEnvFile();
|
||||
|
||||
const string ServiceName = "rag-api";
|
||||
var appVersion = StartupExtensions.GetApplicationVersion(Assembly.GetExecutingAssembly());
|
||||
|
||||
try
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var appVersion = Assembly.GetExecutingAssembly()
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?
|
||||
.InformationalVersion
|
||||
?? Assembly.GetExecutingAssembly().GetName().Version?.ToString()
|
||||
?? "unknown";
|
||||
|
||||
builder.Host.UseSerilog((context, services, configuration) =>
|
||||
{
|
||||
configuration
|
||||
.ReadFrom.Configuration(context.Configuration)
|
||||
.ReadFrom.Services(services)
|
||||
.Enrich.FromLogContext()
|
||||
.Enrich.WithMachineName()
|
||||
.Enrich.WithEnvironmentName()
|
||||
.Enrich.WithProperty("Service", "rag-api")
|
||||
.Enrich.WithProperty("AppVersion", appVersion)
|
||||
.WriteTo.Console(new Serilog.Formatting.Json.JsonFormatter());
|
||||
});
|
||||
builder.ConfigureJsonSerilog(ServiceName, appVersion);
|
||||
Log.Information("Starting {Service} version {AppVersion}", ServiceName, appVersion);
|
||||
|
||||
Log.Information("Starting {Service} version {AppVersion}", "rag-api", appVersion);
|
||||
|
||||
// --------------------
|
||||
// Azure Key Vault Configuration
|
||||
// --------------------
|
||||
var keyVaultUri = builder.Configuration["KeyVault:VaultUri"];
|
||||
var keyVaultEnabled = builder.Configuration.GetValue<bool>("KeyVault:Enabled");
|
||||
|
||||
if (keyVaultEnabled && !string.IsNullOrWhiteSpace(keyVaultUri))
|
||||
{
|
||||
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.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Information("Azure Key Vault is disabled or not configured");
|
||||
}
|
||||
builder.AddAzureKeyVaultIfConfigured();
|
||||
|
||||
builder.Services.Configure<RagSettings>(builder.Configuration.GetSection("Rag"));
|
||||
builder.Services.Configure<Rag.Models.Settings.AiSettings>(builder.Configuration.GetSection("Ai"));
|
||||
@@ -84,28 +43,11 @@ try
|
||||
builder.Services.AddScoped<IRagService, RagService>();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen(options =>
|
||||
{
|
||||
var xmlFile = (Assembly.GetExecutingAssembly().GetName().Name ?? "rag-api") + ".xml";
|
||||
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
|
||||
if (File.Exists(xmlPath)) options.IncludeXmlComments(xmlPath);
|
||||
options.EnableAnnotations();
|
||||
});
|
||||
builder.Services.AddSwaggerWithXmlComments(Assembly.GetExecutingAssembly(), ServiceName);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
var logger = app.Services.GetRequiredService<ILogger<Program>>();
|
||||
logger.LogInformation("API starting up...");
|
||||
logger.LogInformation("Environment: {Environment}", app.Environment.EnvironmentName);
|
||||
|
||||
// Log all environment variables and configuration settings at startup
|
||||
// Can be controlled via appsettings: "LogEnvironmentOnStartup": true
|
||||
var logEnvironmentOnStartup = app.Configuration.GetValue<bool>("LogEnvironmentOnStartup", defaultValue: true);
|
||||
if (logEnvironmentOnStartup)
|
||||
{
|
||||
LogEnvironmentSettings(logger, app.Configuration, app.Environment);
|
||||
}
|
||||
app.LogStartupDiagnostics(ServiceName);
|
||||
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
@@ -113,180 +55,30 @@ try
|
||||
await repository.InitializeAsync(CancellationToken.None);
|
||||
}
|
||||
|
||||
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());
|
||||
};
|
||||
});
|
||||
|
||||
app.UseExceptionHandler(errorApp =>
|
||||
{
|
||||
errorApp.Run(async context =>
|
||||
{
|
||||
var feature = context.Features.Get<IExceptionHandlerFeature>();
|
||||
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
|
||||
if (feature?.Error is not null)
|
||||
{
|
||||
logger.LogError(feature.Error, "Unhandled exception in {Service}", "rag-api");
|
||||
}
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
context.Response.ContentType = "application/json";
|
||||
await context.Response.WriteAsJsonAsync(new { error = "Unexpected server error." });
|
||||
});
|
||||
});
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
var settings = context.RequestServices.GetRequiredService<Microsoft.Extensions.Options.IOptions<InternalApiSettings>>().Value;
|
||||
if (settings.RequireApiKey)
|
||||
{
|
||||
var header = context.Request.Headers["X-Internal-Api-Key"].ToString();
|
||||
if (string.IsNullOrWhiteSpace(settings.ApiKey) || header != settings.ApiKey)
|
||||
{
|
||||
var logger = context.RequestServices.GetRequiredService<ILogger<Program>>();
|
||||
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();
|
||||
});
|
||||
|
||||
// Swagger (typically only in Development)
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI(options =>
|
||||
{
|
||||
options.DocumentTitle = "rag-api";
|
||||
options.SwaggerEndpoint("/swagger/v1/swagger.json", "rag-api v1");
|
||||
options.RoutePrefix = "swagger";
|
||||
});
|
||||
}
|
||||
app.UseDefaultSerilogRequestLogging();
|
||||
app.UseJsonExceptionHandler(ServiceName);
|
||||
app.UseInternalApiKeyProtection();
|
||||
app.UseSwaggerInDevelopment(ServiceName, ServiceName);
|
||||
|
||||
app.MapControllers();
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok", service = "rag-api", version = appVersion, timeUtc = DateTimeOffset.UtcNow }));
|
||||
app.MapHealthEndpoint(ServiceName, appVersion);
|
||||
|
||||
Log.Information("Running EfCore DbMigrations if any");
|
||||
Log.Information("Running EF Core migrations if any");
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<RagDbContext>();
|
||||
db.Database.Migrate();
|
||||
}
|
||||
|
||||
Log.Information("{Service} startup complete", "rag-api");
|
||||
Log.Information("{Service} startup complete", ServiceName);
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "rag-api terminated unexpectedly");
|
||||
Log.Fatal(ex, "{Service} terminated unexpectedly", ServiceName);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.Information("Shutting down rag-api");
|
||||
Log.Information("Shutting down {Service}", ServiceName);
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
|
||||
static void LogEnvironmentSettings(Microsoft.Extensions.Logging.ILogger logger, IConfiguration configuration, IWebHostEnvironment environment)
|
||||
{
|
||||
logger.LogInformation("==================== ENVIRONMENT SETTINGS ====================");
|
||||
|
||||
// Environment Information
|
||||
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);
|
||||
|
||||
// Environment Variables
|
||||
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;
|
||||
|
||||
// Mask sensitive values (passwords, secrets, tokens, keys) but show last 4 characters
|
||||
if (IsSensitiveKey(key))
|
||||
{
|
||||
value = MaskValueWithLastChars(value);
|
||||
}
|
||||
|
||||
sortedEnvVars[key] = value;
|
||||
}
|
||||
|
||||
foreach (var kvp in sortedEnvVars)
|
||||
{
|
||||
logger.LogInformation(" {Key} = {Value}", kvp.Key, kvp.Value);
|
||||
}
|
||||
|
||||
// Configuration Settings
|
||||
logger.LogInformation("-------------- Configuration Settings --------------");
|
||||
LogConfigurationRecursive(logger, configuration.GetChildren(), "");
|
||||
|
||||
logger.LogInformation("===========================================================");
|
||||
}
|
||||
|
||||
static void LogConfigurationRecursive(Microsoft.Extensions.Logging.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;
|
||||
|
||||
// Mask sensitive configuration values but show last 4 characters
|
||||
if (IsSensitiveKey(key))
|
||||
{
|
||||
value = MaskValueWithLastChars(value);
|
||||
}
|
||||
|
||||
logger.LogInformation(" {Key} = {Value}", key, value);
|
||||
}
|
||||
|
||||
// Recurse into child sections
|
||||
if (section.GetChildren().Any())
|
||||
{
|
||||
LogConfigurationRecursive(logger, section.GetChildren(), key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
static string MaskValueWithLastChars(string value)
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
return "***NOT SET***";
|
||||
}
|
||||
|
||||
// If value is too short, just mask it completely
|
||||
if (value.Length <= 4)
|
||||
{
|
||||
return "***MASKED***";
|
||||
}
|
||||
|
||||
// Show last 4 characters
|
||||
var lastChars = value.Substring(value.Length - 4);
|
||||
return $"***MASKED***...{lastChars}";
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
@@ -79,5 +79,6 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\rag-api-models\rag-api-models.csproj" />
|
||||
<ProjectReference Include="..\shared-models\shared-models.csproj" />
|
||||
</ItemGroup>
|
||||
<ProjectReference Include="..\startup-helpers\startup-helpers.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
Reference in New Issue
Block a user