refactor: remove Heimdall.Api, move all routes into Heimdall.Web
Heimdall.Api controllers/hubs/filters were exact duplicates of files already in Heimdall.Web (same namespace, same content). The Api project was a leftover from before the single-image merge. Changes: - Add missing registrations to Web/Program.cs (JWT Bearer auth, rate limiting, controllers with ExceptionFilter, FluentValidation, SignalR + broadcast services, OpenAPI/Scalar, CORS, hub mappings) - Add FluentValidation.AspNetCore, Scalar.AspNetCore, Microsoft.AspNetCore.OpenApi NuGet packages to Web.csproj - Remove Heimdall.Api from solution and delete the project - All routes continue working at their existing paths
This commit is contained in:
1 parent
81da09c110
commit
d9a3ea52ba
28 files changed
+126
-2272
No files matched your search
+123
-7
@@ -1,21 +1,27 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using FluentValidation.AspNetCore;
|
||||
using Heimdall.Application;
|
||||
using Heimdall.Application.Services;
|
||||
using Heimdall.Infrastructure;
|
||||
using Heimdall.Infrastructure.Data;
|
||||
using Heimdall.Infrastructure.Jobs;
|
||||
using Heimdall.Infrastructure.Security;
|
||||
using Heimdall.Web.Components;
|
||||
using Heimdall.Api.Hubs;
|
||||
using Heimdall.Web.Services;
|
||||
using Hangfire;
|
||||
using Hangfire.PostgreSql;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using MudBlazor.Services;
|
||||
using Scalar.AspNetCore;
|
||||
|
||||
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
|
||||
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
|
||||
@@ -42,6 +48,12 @@ builder.Services.AddRazorComponents()
|
||||
// At the ASP.NET Core middleware level, we use cookie authentication
|
||||
// to persist the user session across requests.
|
||||
// The cookie is created after successful API login (see /_auth/signin).
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
||||
?? throw new InvalidOperationException("JWT:Key is not configured");
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
|
||||
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
|
||||
|
||||
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
||||
{
|
||||
@@ -54,7 +66,40 @@ builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationSc
|
||||
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
||||
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
||||
options.SlidingExpiration = true;
|
||||
});
|
||||
})
|
||||
.AddJwtBearer("JwtBearer", options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuerSigningKey = true,
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
||||
ValidateIssuer = true,
|
||||
ValidIssuer = jwtIssuer,
|
||||
ValidateAudience = true,
|
||||
ValidAudience = jwtAudience,
|
||||
ValidateLifetime = true,
|
||||
ClockSkew = TimeSpan.Zero
|
||||
};
|
||||
|
||||
// SignalR WebSocket transport sends JWT as access_token query parameter
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
var accessToken = context.Request.Query["access_token"];
|
||||
var path = context.HttpContext.Request.Path;
|
||||
|
||||
if (!string.IsNullOrEmpty(accessToken) &&
|
||||
path.StartsWithSegments("/hubs"))
|
||||
{
|
||||
context.Token = accessToken;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
};
|
||||
})
|
||||
.AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>("ApiKey", null);
|
||||
|
||||
builder.Services.AddAuthorizationCore(options =>
|
||||
{
|
||||
@@ -85,6 +130,47 @@ builder.Services.AddMudServices(config =>
|
||||
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
||||
});
|
||||
|
||||
// ── Rate Limiting (Polly/System.Threading.RateLimiting) ───────────
|
||||
builder.Services.AddRateLimiter(options =>
|
||||
{
|
||||
options.RejectionStatusCode = 429;
|
||||
|
||||
options.AddFixedWindowLimiter("Auth", opt =>
|
||||
{
|
||||
opt.PermitLimit = 10;
|
||||
opt.Window = TimeSpan.FromMinutes(1);
|
||||
opt.QueueLimit = 0;
|
||||
});
|
||||
|
||||
options.AddFixedWindowLimiter("Api", opt =>
|
||||
{
|
||||
opt.PermitLimit = 200;
|
||||
opt.Window = TimeSpan.FromMinutes(1);
|
||||
opt.QueueLimit = 0;
|
||||
});
|
||||
});
|
||||
|
||||
// ── Controllers (REST API) ────────────────────────────────────────
|
||||
builder.Services.AddControllers(options =>
|
||||
{
|
||||
options.Filters.Add<Heimdall.Api.Filters.ExceptionFilter>();
|
||||
});
|
||||
|
||||
// Auto-validation with FluentValidation
|
||||
builder.Services.AddFluentValidationAutoValidation();
|
||||
|
||||
// Global JSON serialization — string enums for API responses
|
||||
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(opts =>
|
||||
{
|
||||
opts.SerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
|
||||
});
|
||||
|
||||
builder.Services.AddSignalR();
|
||||
builder.Services.AddScoped<IEventBroadcastService, EventBroadcastService>();
|
||||
builder.Services.AddScoped<IConfigBroadcastService, ConfigBroadcastService>();
|
||||
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
// ── Application layer ─────────────────────────────────────────────
|
||||
builder.Services.AddApplication();
|
||||
|
||||
@@ -155,6 +241,42 @@ app.UseAuthorization();
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
// ── REST API controllers & SignalR hubs ───────────────────────────
|
||||
app.MapControllers();
|
||||
app.MapHub<ConfigHub>("/hubs/config");
|
||||
app.MapHub<EventsHub>("/hubs/events");
|
||||
|
||||
// ── OpenAPI / Scalar (dev only) ───────────────────────────────────
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
}
|
||||
|
||||
// ── CORS (for external agents and API clients) ────────────────────
|
||||
var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
|
||||
?? ["https://localhost:5001"];
|
||||
|
||||
app.UseCors(options =>
|
||||
{
|
||||
var isWildcard = allowedOrigins.Length == 1 && allowedOrigins[0] == "*";
|
||||
if (isWildcard)
|
||||
{
|
||||
options.AllowAnyOrigin()
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod();
|
||||
}
|
||||
else
|
||||
{
|
||||
options.WithOrigins(allowedOrigins)
|
||||
.AllowCredentials()
|
||||
.AllowAnyHeader()
|
||||
.WithMethods("GET", "POST", "PUT", "DELETE", "PATCH");
|
||||
}
|
||||
});
|
||||
|
||||
app.UseRateLimiter();
|
||||
|
||||
// ── Health check endpoints for Docker ─────────────────────────────
|
||||
app.MapGet("/healthz", () =>
|
||||
Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow }));
|
||||
@@ -180,12 +302,6 @@ app.MapGet("/readyz", async (HttpContext context) =>
|
||||
//
|
||||
// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims.
|
||||
|
||||
var jwtKey = builder.Configuration["Jwt:Key"]
|
||||
?? Environment.GetEnvironmentVariable("JWT__KEY")
|
||||
?? throw new InvalidOperationException("JWT:Key is not configured");
|
||||
var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? Environment.GetEnvironmentVariable("JWT__ISSUER") ?? "heimdall";
|
||||
var jwtAudience = builder.Configuration["Jwt:Audience"] ?? Environment.GetEnvironmentVariable("JWT__AUDIENCE") ?? "heimdall-api";
|
||||
|
||||
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger<Program> logger) =>
|
||||
{
|
||||
if (string.IsNullOrEmpty(request.AccessToken))
|
||||
|
||||
Reference in new issue
Block a user