2026-07-20 09:50:43 +00:00
|
|
|
using System.IdentityModel.Tokens.Jwt;
|
2026-07-16 21:19:16 +00:00
|
|
|
using System.Security.Claims;
|
2026-07-20 09:50:43 +00:00
|
|
|
using System.Text;
|
2026-07-20 20:22:30 +00:00
|
|
|
using FluentValidation.AspNetCore;
|
2026-07-20 17:22:56 +00:00
|
|
|
using Heimdall.Application;
|
2026-07-20 20:22:30 +00:00
|
|
|
using Heimdall.Application.Services;
|
2026-07-20 17:22:56 +00:00
|
|
|
using Heimdall.Infrastructure;
|
2026-07-20 17:12:16 +00:00
|
|
|
using Heimdall.Infrastructure.Data;
|
2026-07-20 17:22:56 +00:00
|
|
|
using Heimdall.Infrastructure.Jobs;
|
2026-07-19 07:04:25 +00:00
|
|
|
using Heimdall.Infrastructure.Security;
|
2026-07-16 19:09:28 +00:00
|
|
|
using Heimdall.Web.Components;
|
2026-07-20 20:22:30 +00:00
|
|
|
using Heimdall.Api.Hubs;
|
2026-07-16 21:19:16 +00:00
|
|
|
using Heimdall.Web.Services;
|
2026-07-20 17:22:56 +00:00
|
|
|
using Hangfire;
|
|
|
|
|
using Hangfire.PostgreSql;
|
2026-07-18 20:59:38 +00:00
|
|
|
using Microsoft.AspNetCore.Authentication;
|
|
|
|
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
2026-07-20 20:22:30 +00:00
|
|
|
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
2026-07-16 21:19:16 +00:00
|
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
2026-07-20 20:22:30 +00:00
|
|
|
using Microsoft.AspNetCore.RateLimiting;
|
2026-07-20 17:22:56 +00:00
|
|
|
using Microsoft.EntityFrameworkCore;
|
2026-07-20 09:50:43 +00:00
|
|
|
using Microsoft.IdentityModel.Tokens;
|
2026-07-16 21:19:16 +00:00
|
|
|
using MudBlazor.Services;
|
2026-07-20 20:22:30 +00:00
|
|
|
using Scalar.AspNetCore;
|
2026-07-16 19:09:28 +00:00
|
|
|
|
2026-07-19 19:33:10 +00:00
|
|
|
// ── Sentry (GlitchTip) — DSN from env var only ───────────────────
|
|
|
|
|
var sentryDsn = Environment.GetEnvironmentVariable("SENTRY_DSN");
|
2026-07-18 19:41:57 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var builder = WebApplication.CreateBuilder(args);
|
|
|
|
|
|
2026-07-18 19:41:57 +00:00
|
|
|
// ── Sentry ────────────────────────────────────────────────────────
|
2026-07-19 19:33:10 +00:00
|
|
|
if (sentryDsn is not null)
|
2026-07-18 19:41:57 +00:00
|
|
|
{
|
2026-07-19 19:33:10 +00:00
|
|
|
builder.WebHost.UseSentry(options =>
|
|
|
|
|
{
|
|
|
|
|
options.Dsn = sentryDsn;
|
|
|
|
|
options.MinimumBreadcrumbLevel = LogLevel.Debug;
|
|
|
|
|
options.MinimumEventLevel = LogLevel.Error;
|
|
|
|
|
options.TracesSampleRate = 0.1;
|
|
|
|
|
});
|
|
|
|
|
}
|
2026-07-18 19:41:57 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
builder.Services.AddRazorComponents()
|
|
|
|
|
.AddInteractiveServerComponents();
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Authentication (Microsoft Identity pattern: cookie auth) ──────
|
|
|
|
|
// The app uses JWT auth via the Heimdall API at the application level.
|
|
|
|
|
// 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).
|
2026-07-20 20:22:30 +00:00
|
|
|
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";
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
|
|
|
|
|
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
|
|
|
|
|
{
|
|
|
|
|
options.LoginPath = "/login";
|
|
|
|
|
options.LogoutPath = "/_auth/signout";
|
|
|
|
|
options.AccessDeniedPath = "/not-found";
|
|
|
|
|
options.Cookie.Name = ".Heimdall.Auth";
|
|
|
|
|
options.Cookie.HttpOnly = true;
|
|
|
|
|
options.Cookie.SameSite = SameSiteMode.Lax;
|
|
|
|
|
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
|
|
|
|
|
options.ExpireTimeSpan = TimeSpan.FromDays(7);
|
|
|
|
|
options.SlidingExpiration = true;
|
2026-07-20 20:22:30 +00:00
|
|
|
})
|
|
|
|
|
.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);
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-19 07:04:25 +00:00
|
|
|
builder.Services.AddAuthorizationCore(options =>
|
|
|
|
|
{
|
|
|
|
|
// Register all permission-based policies from AppPermissions
|
|
|
|
|
var allPermissions = AppPermissions.RolePermissions.Values
|
|
|
|
|
.SelectMany(p => p).Distinct();
|
|
|
|
|
foreach (var permission in allPermissions)
|
|
|
|
|
{
|
|
|
|
|
options.AddPolicy(permission, policy =>
|
|
|
|
|
policy.RequireClaim("permission", permission));
|
|
|
|
|
}
|
|
|
|
|
});
|
2026-07-18 18:58:20 +00:00
|
|
|
builder.Services.AddCascadingAuthenticationState();
|
2026-07-16 21:19:16 +00:00
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// Blazor auth state provider (reads JWT from ProtectedLocalStorage)
|
2026-07-18 21:08:08 +00:00
|
|
|
// Register the concrete type so @inject HeimdallAuthStateProvider works in pages,
|
|
|
|
|
// then make the base AuthenticationStateProvider resolve to the same instance.
|
|
|
|
|
builder.Services.AddScoped<HeimdallAuthStateProvider>();
|
|
|
|
|
builder.Services.AddScoped<AuthenticationStateProvider>(
|
|
|
|
|
sp => sp.GetRequiredService<HeimdallAuthStateProvider>());
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
// ── MudBlazor ─────────────────────────────────────────────────────
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddMudServices(config =>
|
|
|
|
|
{
|
|
|
|
|
config.SnackbarConfiguration.PositionClass = "mud-alert-center-top";
|
|
|
|
|
config.SnackbarConfiguration.PreventDuplicates = true;
|
|
|
|
|
config.SnackbarConfiguration.ShowCloseIcon = true;
|
|
|
|
|
config.SnackbarConfiguration.VisibleStateDuration = 4000;
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-20 20:22:30 +00:00
|
|
|
// ── 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();
|
|
|
|
|
|
2026-07-20 17:22:56 +00:00
|
|
|
// ── Application layer ─────────────────────────────────────────────
|
|
|
|
|
builder.Services.AddApplication();
|
|
|
|
|
|
|
|
|
|
// ── Infrastructure layer ──────────────────────────────────────────
|
|
|
|
|
builder.Services.AddInfrastructure(builder.Configuration,
|
|
|
|
|
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
|
|
|
|
|
|
|
|
|
|
// ── Database connection string (for Hangfire) ─────────────────────
|
|
|
|
|
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
|
|
|
|
|
?? builder.Configuration.GetConnectionString("Default")
|
|
|
|
|
?? throw new InvalidOperationException(
|
|
|
|
|
"DATABASE_URL is not configured. Set the DATABASE_URL environment variable " +
|
|
|
|
|
"or configure a Default connection string in appsettings.json. " +
|
|
|
|
|
"Example: Host=host;Port=5432;Database=heimdall;Username=user;Password=password");
|
|
|
|
|
|
|
|
|
|
// ── Hangfire ──────────────────────────────────────────────────────
|
|
|
|
|
#pragma warning disable CS0618
|
|
|
|
|
builder.Services.AddHangfire(config =>
|
|
|
|
|
{
|
|
|
|
|
config.UsePostgreSqlStorage(connectionString, new PostgreSqlStorageOptions
|
|
|
|
|
{
|
|
|
|
|
SchemaName = "hangfire"
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
#pragma warning restore CS0618
|
|
|
|
|
|
|
|
|
|
builder.Services.AddHangfireServer(options =>
|
|
|
|
|
{
|
|
|
|
|
options.WorkerCount = 2;
|
|
|
|
|
options.Queues = ["default", "heartbeat"];
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ── Jobs ──────────────────────────────────────────────────────────
|
|
|
|
|
builder.Services.AddScoped<HeartbeatMonitorJob>();
|
|
|
|
|
builder.Services.AddScoped<AgentFailoverJob>();
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── HTTP client for Heimdall API ──────────────────────────────────
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddScoped<HeimdallApiClient>();
|
2026-07-17 13:22:02 +00:00
|
|
|
var apiBaseUrl = builder.Configuration.GetValue<string>("ApiBaseUrl")
|
|
|
|
|
?? Environment.GetEnvironmentVariable("API_BASE_URL")
|
2026-07-20 20:09:24 +00:00
|
|
|
?? "http://localhost:8080";
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddHttpClient("HeimdallApi", client =>
|
|
|
|
|
{
|
2026-07-17 13:22:02 +00:00
|
|
|
client.BaseAddress = new Uri(apiBaseUrl.TrimEnd('/') + "/");
|
2026-07-16 21:19:16 +00:00
|
|
|
client.Timeout = TimeSpan.FromSeconds(30);
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// Auth state (shared between services and components)
|
2026-07-16 21:19:16 +00:00
|
|
|
builder.Services.AddScoped<AuthState>();
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
var app = builder.Build();
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Middleware pipeline ────────────────────────────────────────────
|
2026-07-16 19:09:28 +00:00
|
|
|
if (!app.Environment.IsDevelopment())
|
|
|
|
|
{
|
|
|
|
|
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
|
|
|
|
app.UseHsts();
|
|
|
|
|
}
|
2026-07-16 21:19:16 +00:00
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
|
|
|
|
app.UseHttpsRedirection();
|
|
|
|
|
app.UseAntiforgery();
|
2026-07-19 18:37:52 +00:00
|
|
|
app.UseStaticFiles();
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
app.UseAuthentication();
|
|
|
|
|
app.UseAuthorization();
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.MapRazorComponents<App>()
|
|
|
|
|
.AddInteractiveServerRenderMode();
|
|
|
|
|
|
2026-07-20 20:22:30 +00:00
|
|
|
// ── 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();
|
|
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
// ── Health check endpoints for Docker ─────────────────────────────
|
|
|
|
|
app.MapGet("/healthz", () =>
|
|
|
|
|
Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow }));
|
|
|
|
|
|
|
|
|
|
app.MapGet("/readyz", async (HttpContext context) =>
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var scope = context.RequestServices.CreateScope();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
|
_ = await db.Database.CanConnectAsync();
|
|
|
|
|
return Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow });
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return Results.StatusCode(503);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-18 20:59:38 +00:00
|
|
|
// ── Cookie auth endpoints (called from Blazor via JS fetch) ───────
|
2026-07-20 09:50:43 +00:00
|
|
|
// /_auth/signin — Validates the JWT access token and creates an auth cookie
|
2026-07-18 20:59:38 +00:00
|
|
|
// /_auth/signout — Clears the authentication cookie on logout
|
2026-07-20 09:50:43 +00:00
|
|
|
//
|
|
|
|
|
// IMPORTANT: The JWT is validated server-side — never trust client-supplied claims.
|
|
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
app.MapPost("/_auth/signin", async (HttpContext httpContext, SignInRequest request, ILogger<Program> logger) =>
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 09:50:43 +00:00
|
|
|
if (string.IsNullOrEmpty(request.AccessToken))
|
2026-07-20 17:12:16 +00:00
|
|
|
{
|
|
|
|
|
logger.LogWarning("Signin attempt without access token");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = "AccessToken is required" });
|
2026-07-20 17:12:16 +00:00
|
|
|
}
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
// Validate the JWT server-side — extract claims from the validated token, not from client
|
|
|
|
|
try
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 09:50:43 +00:00
|
|
|
var handler = new JwtSecurityTokenHandler();
|
|
|
|
|
var validationParams = new TokenValidationParameters
|
|
|
|
|
{
|
|
|
|
|
ValidateIssuerSigningKey = true,
|
|
|
|
|
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
|
|
|
|
|
ValidateIssuer = true,
|
|
|
|
|
ValidIssuer = jwtIssuer,
|
|
|
|
|
ValidateAudience = true,
|
|
|
|
|
ValidAudience = jwtAudience,
|
|
|
|
|
ValidateLifetime = true,
|
|
|
|
|
ClockSkew = TimeSpan.Zero
|
|
|
|
|
};
|
2026-07-18 20:59:38 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
var principal = handler.ValidateToken(request.AccessToken, validationParams, out _);
|
2026-07-19 07:04:25 +00:00
|
|
|
|
2026-07-20 09:50:43 +00:00
|
|
|
// Extract claims from the validated JWT only
|
|
|
|
|
var userId = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
|
|
|
|
var email = principal.FindFirst(ClaimTypes.Email)?.Value;
|
|
|
|
|
var displayName = principal.FindFirst(ClaimTypes.Name)?.Value;
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(email))
|
2026-07-20 17:12:16 +00:00
|
|
|
{
|
|
|
|
|
logger.LogWarning("Signin attempt with valid JWT but missing user claims: UserId={UserId}, Email={Email}", userId, email);
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = "Invalid token: missing user claims" });
|
2026-07-20 17:12:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
logger.LogInformation("Signing in user {Email} ({UserId}) — creating auth cookie", email, userId);
|
2026-07-20 09:50:43 +00:00
|
|
|
|
|
|
|
|
// Re-build claims identity from validated token claims (never from client body)
|
|
|
|
|
var claims = new List<Claim>
|
|
|
|
|
{
|
|
|
|
|
new(ClaimTypes.NameIdentifier, userId),
|
|
|
|
|
new(ClaimTypes.Email, email),
|
|
|
|
|
new(ClaimTypes.Name, displayName ?? email),
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
foreach (var role in principal.FindAll(ClaimTypes.Role))
|
|
|
|
|
claims.Add(new Claim(ClaimTypes.Role, role.Value));
|
|
|
|
|
|
|
|
|
|
foreach (var permission in principal.FindAll("permission"))
|
|
|
|
|
claims.Add(new Claim("permission", permission.Value));
|
|
|
|
|
|
|
|
|
|
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
|
var cookiePrincipal = new ClaimsPrincipal(identity);
|
|
|
|
|
|
|
|
|
|
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, cookiePrincipal);
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogInformation("Auth cookie created for {Email} ({UserId})", email, userId);
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.Ok();
|
|
|
|
|
}
|
|
|
|
|
catch (SecurityTokenExpiredException)
|
|
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogWarning("Signin attempt with expired JWT");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.Unauthorized();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
logger.LogError(ex, "Signin failed — JWT validation error");
|
2026-07-20 09:50:43 +00:00
|
|
|
return Results.BadRequest(new { error = $"Token validation failed: {ex.Message}" });
|
2026-07-18 20:59:38 +00:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-20 17:12:16 +00:00
|
|
|
app.MapPost("/_auth/signout", async (HttpContext httpContext, ILogger<Program> logger) =>
|
2026-07-18 20:59:38 +00:00
|
|
|
{
|
2026-07-20 17:12:16 +00:00
|
|
|
var email = httpContext.User.FindFirst(ClaimTypes.Email)?.Value ?? "(anonymous)";
|
|
|
|
|
logger.LogInformation("Signing out user {Email}", email);
|
2026-07-18 20:59:38 +00:00
|
|
|
await httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
|
|
|
|
return Results.Ok();
|
|
|
|
|
});
|
|
|
|
|
|
2026-07-20 17:22:56 +00:00
|
|
|
// ── Apply pending database migrations ────────────────────────────────
|
|
|
|
|
// Retry with exponential backoff to handle container startup races where
|
|
|
|
|
// PostgreSQL accepts TCP connections but isn't ready to serve queries yet.
|
|
|
|
|
using (var scope = app.Services.CreateScope())
|
|
|
|
|
{
|
|
|
|
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
|
|
|
|
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
|
|
|
|
var maxRetries = 5;
|
|
|
|
|
var retryDelay = TimeSpan.FromSeconds(2);
|
|
|
|
|
|
|
|
|
|
for (var attempt = 1; attempt <= maxRetries; attempt++)
|
|
|
|
|
{
|
2026-07-20 19:58:32 +00:00
|
|
|
try
|
2026-07-20 17:22:56 +00:00
|
|
|
{
|
2026-07-20 19:58:32 +00:00
|
|
|
logger.LogInformation("Applying database migrations (attempt {Attempt}/{MaxRetries})...", attempt, maxRetries);
|
2026-07-20 17:22:56 +00:00
|
|
|
db.Database.Migrate();
|
|
|
|
|
logger.LogInformation("Database migrations applied successfully");
|
2026-07-20 19:58:32 +00:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (attempt < maxRetries)
|
|
|
|
|
{
|
|
|
|
|
logger.LogWarning(ex,
|
|
|
|
|
"Database migration attempt {Attempt}/{MaxRetries} failed. Retrying in {Delay}s...",
|
|
|
|
|
attempt, maxRetries, retryDelay.TotalSeconds);
|
|
|
|
|
await Task.Delay(retryDelay);
|
|
|
|
|
retryDelay = TimeSpan.FromSeconds(retryDelay.TotalSeconds * 2);
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
logger.LogCritical(ex, "Failed to apply database migrations after {MaxRetries} attempts.", maxRetries);
|
|
|
|
|
throw;
|
2026-07-20 17:22:56 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ── Register recurring Hangfire jobs ─────────────────────────────────
|
|
|
|
|
using (var scope = app.Services.CreateScope())
|
|
|
|
|
{
|
|
|
|
|
var manager = scope.ServiceProvider.GetRequiredService<IRecurringJobManager>();
|
|
|
|
|
|
|
|
|
|
manager.AddOrUpdate<HeartbeatMonitorJob>(
|
|
|
|
|
"heartbeat-monitor",
|
|
|
|
|
job => job.ExecuteAsync(CancellationToken.None),
|
|
|
|
|
"*/1 * * * *"); // Every minute
|
|
|
|
|
|
|
|
|
|
manager.AddOrUpdate<AgentFailoverJob>(
|
|
|
|
|
"agent-failover",
|
|
|
|
|
job => job.ExecuteAsync(CancellationToken.None),
|
|
|
|
|
"*/1 * * * *"); // Every minute — checks for stale heartbeats
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-16 19:09:28 +00:00
|
|
|
app.Run();
|
2026-07-18 20:59:38 +00:00
|
|
|
|
|
|
|
|
// ─── DTO for the cookie sign-in request ───────────────────────────
|
|
|
|
|
|
|
|
|
|
internal sealed record SignInRequest(
|
2026-07-20 09:50:43 +00:00
|
|
|
string AccessToken);
|