fix(multiple): auth, workers, EF Core, MudTheme fixes

- Auth: AssignmentsController auth bug, ReleaseCamera result, logout endpoint
- Security: open redirect fix
- Workers: AgentState thread-safety, CameraStreamService async, HttpClientFactory
- EF Core: AddCameraDiscoveryFields migration, DI interceptors, retry helper
- UI: MudTheme palette config, aria-labels on icon buttons
This commit is contained in:
Arnaud Dartois committed 2026-07-19 19:58:45 +00:00
1 parent 4b83e35df0
commit 153be535d4
17 files changed
+1944 -32

No files matched your search

+32 -5
View File
@@ -5,10 +5,18 @@ namespace Heimdall.Agent.Services;
/// <summary>
/// Persisted identity of this agent instance. Survives restarts so the Central
/// server sees the same AgentId across reboots (no orphaned agents).
/// Uses an immutable snapshot pattern with <see cref="Interlocked"/> for
/// thread-safe concurrent reads/writes from multiple services.
/// </summary>
public class AgentState
public sealed class AgentState
{
private string _stateDir = "/var/lib/heimdall";
private AgentSnapshot _snapshot = AgentSnapshot.Default;
private sealed record AgentSnapshot(Guid AgentId, string? ApiKey, string? ApiKeyPrefix, string? PublicIp)
{
public static readonly AgentSnapshot Default = new(Guid.Empty, null, null, null);
}
/// <summary>
/// Sets the directory for the state file. Called during DI setup.
@@ -20,10 +28,29 @@ public class AgentState
private string StatePath => Path.Combine(_stateDir, "agent-state.json");
public Guid AgentId { get; set; }
public string? ApiKey { get; set; }
public string? ApiKeyPrefix { get; set; }
public string? PublicIp { get; set; }
public Guid AgentId
{
get => _snapshot.AgentId;
set => Interlocked.Exchange(ref _snapshot, _snapshot with { AgentId = value });
}
public string? ApiKey
{
get => _snapshot.ApiKey;
set => Interlocked.Exchange(ref _snapshot, _snapshot with { ApiKey = value });
}
public string? ApiKeyPrefix
{
get => _snapshot.ApiKeyPrefix;
set => Interlocked.Exchange(ref _snapshot, _snapshot with { ApiKeyPrefix = value });
}
public string? PublicIp
{
get => _snapshot.PublicIp;
set => Interlocked.Exchange(ref _snapshot, _snapshot with { PublicIp = value });
}
/// <summary>
/// Loads a previously saved identity, or returns null if none exists.
@@ -1,3 +1,4 @@
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
@@ -78,16 +79,16 @@ public sealed class CameraStreamService : IDisposable
/// <summary>Number of currently active streams.</summary>
public int ActiveStreamCount => _sessions.Count;
private Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
private async Task ReadFramesLoop(Guid cameraId, StreamSession session, CancellationToken ct)
{
var buffer = ArrayPool<byte>.Shared.Rent(256 * 1024);
try
{
var buffer = new byte[256 * 1024]; // 256KB buffer
var stream = session.Process.StandardOutput.BaseStream;
while (!ct.IsCancellationRequested && !session.IsCancelled && !session.Process.HasExited)
{
var bytesRead = stream.Read(buffer, 0, buffer.Length);
var bytesRead = await stream.ReadAsync(buffer.AsMemory(), ct);
if (bytesRead == 0) break;
// Frame available for analysis — will be passed to FrameAnalyzerService
@@ -101,10 +102,9 @@ public sealed class CameraStreamService : IDisposable
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
CleanupSession(cameraId, session);
}
return Task.CompletedTask;
}
private void CleanupSession(Guid cameraId, StreamSession session)
@@ -13,16 +13,19 @@ public sealed class ConfigReceiverService : BackgroundService
private readonly AgentState _state;
private readonly AgentOptions _options;
private readonly ILogger<ConfigReceiverService> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private HubConnection? _connection;
public ConfigReceiverService(
AgentState state,
IOptions<AgentOptions> options,
ILogger<ConfigReceiverService> logger)
ILogger<ConfigReceiverService> logger,
IHttpClientFactory httpClientFactory)
{
_state = state;
_options = options.Value;
_logger = logger;
_httpClientFactory = httpClientFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -143,7 +146,8 @@ public sealed class ConfigReceiverService : BackgroundService
{
try
{
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
using var http = _httpClientFactory.CreateClient("Central");
http.Timeout = TimeSpan.FromSeconds(10);
http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}");
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
@@ -17,7 +17,7 @@ namespace Heimdall.Api.Controllers;
[ApiController]
[Route("api/assignments")]
[EnableRateLimiting("Api")]
[Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.CameraWrite)]
[Authorize(AuthenticationSchemes = "JwtBearer")]
public class AssignmentsController : ControllerBase
{
private readonly ICameraAssignmentService _assignmentService;
@@ -29,6 +29,7 @@ public class AssignmentsController : ControllerBase
/// <summary>Assign a single camera to a specific agent.</summary>
[HttpPost]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> AssignCamera([FromBody] AssignRequest request, CancellationToken ct)
@@ -42,6 +43,7 @@ public class AssignmentsController : ControllerBase
/// <summary>Assign all cameras in a site using a strategy.</summary>
[HttpPost("site/{siteId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(AssignmentResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> AssignSiteCameras(Guid siteId, [FromQuery] string strategy = "RoundRobin", CancellationToken ct = default)
@@ -58,6 +60,7 @@ public class AssignmentsController : ControllerBase
/// <summary>Trigger failover for an offline agent — reassign its cameras.</summary>
[HttpPost("failover/{agentId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(typeof(FailoverResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> FailoverAgent(Guid agentId, CancellationToken ct)
@@ -111,10 +114,14 @@ public class AssignmentsController : ControllerBase
/// <summary>Release a camera from its current agent.</summary>
[HttpDelete("camera/{cameraId:guid}")]
[Authorize(Policy = AppPermissions.CameraWrite)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status404NotFound)]
public async Task<IActionResult> ReleaseCamera(Guid cameraId, CancellationToken ct)
{
var result = await _assignmentService.ReleaseCameraAsync(cameraId, ct);
return Ok();
return result.IsSuccess
? Ok()
: StatusCode(result.StatusCode ?? 404, new { error = result.Error });
}
}
@@ -1,4 +1,5 @@
using System.Security.Claims;
using Heimdall.Application.Common;
using Heimdall.Application.DTOs;
using Heimdall.Application.Services;
using Heimdall.Infrastructure.Security;
@@ -110,4 +111,18 @@ public class AuthController : ControllerBase
? Ok(result.Data)
: StatusCode(result.StatusCode ?? 400, new { error = result.Error });
}
/// <summary>Logout — revoke the current refresh token.</summary>
[Authorize]
[HttpPost("logout")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> Logout([FromBody] LogoutRequest request, CancellationToken ct)
{
var userIdClaim = User.FindFirstValue(ClaimTypes.NameIdentifier);
if (userIdClaim is null || !Guid.TryParse(userIdClaim, out var userId))
return Unauthorized();
await _authService.LogoutAsync(userId, request.RefreshToken, ct);
return Ok();
}
}
+2
View File
@@ -37,3 +37,5 @@ public record CreateApiKeyResponse(
DateTime? ExpiresAt);
public record ChangePasswordRequest(string CurrentPassword, string NewPassword);
public record LogoutRequest(string RefreshToken);
@@ -9,7 +9,17 @@ namespace Heimdall.Infrastructure.Data;
public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
private readonly AuditInterceptor _auditInterceptor;
private readonly SoftDeleteInterceptor _softDeleteInterceptor;
public AppDbContext(
DbContextOptions<AppDbContext> options,
AuditInterceptor auditInterceptor,
SoftDeleteInterceptor softDeleteInterceptor) : base(options)
{
_auditInterceptor = auditInterceptor;
_softDeleteInterceptor = softDeleteInterceptor;
}
// Domain entities
public DbSet<Site> Sites => Set<Site>();
@@ -67,8 +77,8 @@ public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.AddInterceptors(
new AuditInterceptor(),
new SoftDeleteInterceptor());
_auditInterceptor,
_softDeleteInterceptor);
// Suppress informational EF Core messages that create noise in
// error tracking (GlitchTip #538). Redundant index warnings are
@@ -1,3 +1,4 @@
using Heimdall.Infrastructure.Data.Interceptors;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
@@ -19,6 +20,9 @@ public class AppDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
optionsBuilder.UseNpgsql(connectionString, npgsql =>
npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "public"));
return new AppDbContext(optionsBuilder.Options);
return new AppDbContext(
optionsBuilder.Options,
new AuditInterceptor(),
new SoftDeleteInterceptor());
}
}
@@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore;
namespace Heimdall.Infrastructure.Data;
public static class DbContextExtensions
{
public static async Task SaveChangesWithRetryAsync(this DbContext context,
int maxRetries = 3, CancellationToken ct = default)
{
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
await context.SaveChangesAsync(ct);
return;
}
catch (Exception ex) when (attempt < maxRetries && IsTransient(ex))
{
await Task.Delay(TimeSpan.FromMilliseconds(100 * Math.Pow(2, attempt - 1)), ct);
}
}
}
private static bool IsTransient(Exception ex)
{
if (ex is Npgsql.NpgsqlException npgsqlEx)
{
return npgsqlEx.SqlState is "40001" or "40P01";
}
return false;
}
}
@@ -2,6 +2,7 @@ using System.IO;
using Heimdall.Application.Services;
using Heimdall.Domain.Entities;
using Heimdall.Infrastructure.Data;
using Heimdall.Infrastructure.Data.Interceptors;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Services;
using Heimdall.Infrastructure.Services.Discovery;
@@ -23,6 +24,10 @@ public static class DependencyInjection
var env = environmentName ?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var isTesting = env == "Testing";
// EF Core interceptors (registered as singletons — they are stateless)
services.AddSingleton<AuditInterceptor>();
services.AddSingleton<SoftDeleteInterceptor>();
if (isTesting)
{
var dbName = configuration.GetValue<string>("InMemoryDbName") ?? "HeimdallTestDb";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,202 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Heimdall.Infrastructure.Migrations
{
/// <inheritdoc />
public partial class AddCameraDiscoveryFields : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Capabilities",
table: "cameras",
type: "character varying(64)",
unicode: false,
maxLength: 64,
nullable: false,
defaultValue: "None");
migrationBuilder.AddColumn<string>(
name: "DetectedType",
table: "cameras",
type: "character varying(20)",
unicode: false,
maxLength: 20,
nullable: false,
defaultValue: "Standard");
migrationBuilder.AddColumn<string>(
name: "DiscoveryMethod",
table: "cameras",
type: "character varying(20)",
unicode: false,
maxLength: 20,
nullable: false,
defaultValue: "Manual");
migrationBuilder.AddColumn<int>(
name: "HttpPort",
table: "cameras",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "IpAddress",
table: "cameras",
type: "character varying(45)",
maxLength: 45,
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "LastDiscoveredAt",
table: "cameras",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "LastStreamTestAt",
table: "cameras",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "LastTestedCodecs",
table: "cameras",
type: "character varying(200)",
unicode: false,
maxLength: 200,
nullable: true);
migrationBuilder.AddColumn<int>(
name: "LastTestedHeight",
table: "cameras",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<long>(
name: "LastTestedLatencyMs",
table: "cameras",
type: "bigint",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "LastTestedWidth",
table: "cameras",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "MacAddress",
table: "cameras",
type: "character varying(17)",
maxLength: 17,
nullable: true);
migrationBuilder.AddColumn<int>(
name: "OnvifPort",
table: "cameras",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "RtspPort",
table: "cameras",
type: "integer",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "SubRtspUrl",
table: "cameras",
type: "character varying(1000)",
unicode: false,
maxLength: 1000,
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_cameras_IpAddress",
table: "cameras",
column: "IpAddress");
migrationBuilder.CreateIndex(
name: "IX_cameras_MacAddress",
table: "cameras",
column: "MacAddress");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_cameras_IpAddress",
table: "cameras");
migrationBuilder.DropIndex(
name: "IX_cameras_MacAddress",
table: "cameras");
migrationBuilder.DropColumn(
name: "Capabilities",
table: "cameras");
migrationBuilder.DropColumn(
name: "DetectedType",
table: "cameras");
migrationBuilder.DropColumn(
name: "DiscoveryMethod",
table: "cameras");
migrationBuilder.DropColumn(
name: "HttpPort",
table: "cameras");
migrationBuilder.DropColumn(
name: "IpAddress",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastDiscoveredAt",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastStreamTestAt",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastTestedCodecs",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastTestedHeight",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastTestedLatencyMs",
table: "cameras");
migrationBuilder.DropColumn(
name: "LastTestedWidth",
table: "cameras");
migrationBuilder.DropColumn(
name: "MacAddress",
table: "cameras");
migrationBuilder.DropColumn(
name: "OnvifPort",
table: "cameras");
migrationBuilder.DropColumn(
name: "RtspPort",
table: "cameras");
migrationBuilder.DropColumn(
name: "SubRtspUrl",
table: "cameras");
}
}
}
@@ -44,22 +44,23 @@ public sealed class CameraEventService : ICameraEventService
"Camera event {EventId}: {Type} (confidence={Conf}) for camera {CameraId}",
ev.Id, ev.Type, ev.Confidence, ev.CameraId);
// Fire-and-forget broadcast to connected SignalR clients
var broadcastCt = ct;
// Fire-and-forget broadcast to connected SignalR clients.
// Use CancellationToken.None — the broadcast must outlive the HTTP request
// lifecycle so SignalR clients receive the notification even after the
// response is sent.
_ = Task.Run(async () =>
{
try
{
using var scope = _serviceProvider.CreateScope();
var broadcast = scope.ServiceProvider.GetRequiredService<IEventBroadcastService>();
await broadcast.NotifyEventCreated(MapResponse(ev), broadcastCt);
await broadcast.NotifyEventCreated(MapResponse(ev), CancellationToken.None);
}
catch (OperationCanceledException) when (broadcastCt.IsCancellationRequested) { }
catch (Exception ex)
{
_logger.LogWarning(ex, "Failed to broadcast event {EventId}", ev.Id);
}
}, broadcastCt);
}, CancellationToken.None);
return ServiceResult<CameraEventResponse>.Success(MapResponse(ev));
}
@@ -4,13 +4,13 @@
@inject HeimdallAuthStateProvider AuthStateProvider
@inject IJSRuntime JsRuntime
<MudThemeProvider />
<MudThemeProvider Theme="@_theme" />
<MudDialogProvider />
<MudSnackbarProvider />
<MudLayout>
<MudAppBar Elevation="1">
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit"
<MudIconButton Icon="@Icons.Material.Filled.Menu" Color="Color.Inherit" aria-label="Menu"
@onclick="@(() => _drawerOpen = !_drawerOpen)" />
<MudText Typo="Typo.h6" Class="ml-2">Heimdall</MudText>
@@ -23,11 +23,11 @@
<MudSpacer />
@if (Auth.IsLoggedIn)
{
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit"
<MudIconButton Icon="@Icons.Material.Filled.Notifications" Color="Color.Inherit" aria-label="Notifications"
OnClick="@(() => Navigation.NavigateTo("/events"))" />
<MudMenu AnchorOrigin="Origin.BottomRight">
<ActivatorContent>
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle" Color="Color.Inherit" />
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle" Color="Color.Inherit" aria-label="Profil" />
</ActivatorContent>
<ChildContent>
<MudMenuItem>
@@ -110,6 +110,51 @@
@code {
private bool _drawerOpen = true;
private string _searchQuery = "";
private readonly MudTheme _theme = new()
{
PaletteLight = new PaletteLight
{
Primary = "#1976D2",
Secondary = "#9E9E9E",
Tertiary = "#009688",
AppbarBackground = "#1565C0",
AppbarText = "#FFFFFF",
Background = "#F5F5F5",
Surface = "#FFFFFF",
DrawerBackground = "#FFFFFF",
DrawerText = "#424242",
TextPrimary = "#212121",
TextSecondary = "#616161",
TextDisabled = "#BDBDBD",
Dark = "#0D47A1",
DarkLighten = "#1976D2",
Info = "#42A5F5",
Warning = "#FF9800",
Error = "#F44336",
Success = "#4CAF50",
},
PaletteDark = new PaletteDark
{
Primary = "#64B5F6",
Secondary = "#BDBDBD",
Tertiary = "#80CBC4",
AppbarBackground = "#212121",
AppbarText = "#FFFFFF",
Background = "#121212",
Surface = "#424242",
DrawerBackground = "#424242",
DrawerText = "#BDBDBD",
TextPrimary = "#E0E0E0",
TextSecondary = "#BDBDBD",
TextDisabled = "#757575",
Dark = "#1A237E",
DarkLighten = "#1976D2",
Info = "#42A5F5",
Warning = "#FFA726",
Error = "#EF5350",
Success = "#66BB6A",
}
};
private async Task Logout()
{
@@ -85,7 +85,7 @@
if (query.TryGetValue("returnUrl", out var returnUrl))
{
var raw = returnUrl.FirstOrDefault() ?? "/dashboard";
if (raw.StartsWith('/') && !raw.Contains("://", StringComparison.Ordinal))
if (raw.StartsWith('/') && !raw.StartsWith("//") && !raw.Contains("://", StringComparison.Ordinal))
_returnUrl = raw;
}
}
@@ -163,8 +163,13 @@ public class CameraAssignmentServiceTests
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext() => new(opts);
private static readonly Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor Audit
= new();
private static readonly Heimdall.Infrastructure.Data.Interceptors.SoftDeleteInterceptor SoftDelete
= new();
public AppDbContext CreateDbContext() => new(opts, Audit, SoftDelete);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts));
=> Task.FromResult(new AppDbContext(opts, Audit, SoftDelete));
}
}
@@ -186,8 +186,13 @@ public class CameraEventServiceTests
private sealed class TestDbContextFactory(DbContextOptions<AppDbContext> opts)
: IDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext() => new(opts);
private static readonly Heimdall.Infrastructure.Data.Interceptors.AuditInterceptor Audit
= new();
private static readonly Heimdall.Infrastructure.Data.Interceptors.SoftDeleteInterceptor SoftDelete
= new();
public AppDbContext CreateDbContext() => new(opts, Audit, SoftDelete);
public Task<AppDbContext> CreateDbContextAsync(CancellationToken ct = default)
=> Task.FromResult(new AppDbContext(opts));
=> Task.FromResult(new AppDbContext(opts, Audit, SoftDelete));
}
}