fix(agent): heartbeat X-API-Key complet + métriques temps réel + hub config
- ApiKeyAuthenticationHandler accepte l'API key via query string access_token sur les chemins /hubs (WebSocket SignalR ne peut pas poser de header custom) → le ConfigReceiverService de l'agent peut se connecter au ConfigHub - ConfigReceiverService.FetchFullConfigAsync : X-API-Key au lieu de Bearer - Métriques heartbeat : CpuUsagePercent/MemoryUsageBytes/DiskUsagePercent/ UptimeSeconds + IsOffline désormais transportées jusqu'à l'entité Agent (migration AddAgentLiveMetrics) ; IsOffline marque l'agent Offline immédiatement au lieu d'attendre le timeout 90s du HeartbeatMonitorJob - docker-compose.local.yml : override aussi l'image agent (heimdall-agent:local) Tests : +2 unit AgentRegistrationService (X-API-Key), +2 HeartbeatHandler (métriques, offline), +3 intégration SignalR (ConfigHub query string) — verts.
This commit is contained in:
1 parent
4516761a3a
commit
1e3322cd1a
13 files changed
+2066
-20
No files matched your search
@@ -8,3 +8,9 @@ services:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile
|
||||
|
||||
heimdall-agent:
|
||||
image: heimdall-agent:local
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: docker/Dockerfile.agent
|
||||
@@ -148,7 +148,9 @@ public sealed class ConfigReceiverService : BackgroundService
|
||||
{
|
||||
using var http = _httpClientFactory.CreateClient("Central");
|
||||
http.Timeout = TimeSpan.FromSeconds(10);
|
||||
http.DefaultRequestHeaders.Add("Authorization", $"Bearer {_state.ApiKey}");
|
||||
// Central's ApiKey scheme reads X-API-Key (never Bearer for agent keys)
|
||||
http.DefaultRequestHeaders.Remove("X-API-Key");
|
||||
http.DefaultRequestHeaders.Add("X-API-Key", _state.ApiKey);
|
||||
|
||||
var url = $"{_options.CentralUrl.TrimEnd('/')}/api/settings/agent/{_state.AgentId}";
|
||||
var response = await http.GetAsync(url, ct);
|
||||
|
||||
@@ -10,4 +10,9 @@ public record HeartbeatCommand(
|
||||
bool? HasGpu,
|
||||
int? CpuCores,
|
||||
int? MemoryMb,
|
||||
GpuAcceleration? GpuType) : IRequest<ServiceResult>;
|
||||
GpuAcceleration? GpuType,
|
||||
bool IsOffline = false,
|
||||
double? CpuUsagePercent = null,
|
||||
long? MemoryUsageBytes = null,
|
||||
double? DiskUsagePercent = null,
|
||||
long? UptimeSeconds = null) : IRequest<ServiceResult>;
|
||||
@@ -17,15 +17,30 @@ public class HeartbeatHandler : IRequestHandler<HeartbeatCommand, ServiceResult>
|
||||
if (agent is null)
|
||||
return ServiceResult.NotFound("Agent not found");
|
||||
|
||||
agent.UpdateHeartbeat(request.PublicIp);
|
||||
|
||||
if (request.HasGpu.HasValue || request.CpuCores.HasValue || request.MemoryMb.HasValue || request.GpuType.HasValue)
|
||||
if (request.IsOffline)
|
||||
{
|
||||
agent.UpdateCapabilities(
|
||||
request.HasGpu ?? false,
|
||||
request.CpuCores ?? 0,
|
||||
request.MemoryMb ?? 0,
|
||||
request.GpuType ?? GpuAcceleration.None);
|
||||
// Graceful shutdown: reflect it immediately instead of waiting for
|
||||
// the 90s HeartbeatMonitorJob timeout.
|
||||
agent.MarkOffline();
|
||||
}
|
||||
else
|
||||
{
|
||||
agent.UpdateHeartbeat(request.PublicIp);
|
||||
|
||||
if (request.HasGpu.HasValue || request.CpuCores.HasValue || request.MemoryMb.HasValue || request.GpuType.HasValue)
|
||||
{
|
||||
agent.UpdateCapabilities(
|
||||
request.HasGpu ?? false,
|
||||
request.CpuCores ?? 0,
|
||||
request.MemoryMb ?? 0,
|
||||
request.GpuType ?? GpuAcceleration.None);
|
||||
}
|
||||
|
||||
agent.UpdateLiveMetrics(
|
||||
request.CpuUsagePercent,
|
||||
request.MemoryUsageBytes,
|
||||
request.DiskUsagePercent,
|
||||
request.UptimeSeconds);
|
||||
}
|
||||
|
||||
await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false);
|
||||
|
||||
@@ -13,7 +13,12 @@ public record AgentHeartbeatRequest(
|
||||
bool? HasGpu,
|
||||
int? CpuCores,
|
||||
long? MemoryMb,
|
||||
string? GpuType);
|
||||
string? GpuType,
|
||||
bool IsOffline = false,
|
||||
double? CpuUsagePercent = null,
|
||||
long? MemoryUsageBytes = null,
|
||||
double? DiskUsagePercent = null,
|
||||
long? UptimeSeconds = null);
|
||||
|
||||
public record AgentResponse(
|
||||
Guid Id,
|
||||
|
||||
@@ -25,6 +25,12 @@ public class Agent : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
public long MemoryMb { get; private set; }
|
||||
public GpuAcceleration GpuType { get; private set; } = GpuAcceleration.None;
|
||||
|
||||
// Live metrics (sent with each heartbeat)
|
||||
public double? CpuUsagePercent { get; private set; }
|
||||
public long? MemoryUsageBytes { get; private set; }
|
||||
public double? DiskUsagePercent { get; private set; }
|
||||
public long? UptimeSeconds { get; private set; }
|
||||
|
||||
// Audit
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
@@ -65,6 +71,18 @@ public class Agent : Entity<Guid>, IAuditableEntity, ISoftDeletable
|
||||
PublicIp = publicIp;
|
||||
}
|
||||
|
||||
public void UpdateLiveMetrics(
|
||||
double? cpuUsagePercent,
|
||||
long? memoryUsageBytes,
|
||||
double? diskUsagePercent,
|
||||
long? uptimeSeconds)
|
||||
{
|
||||
CpuUsagePercent = cpuUsagePercent;
|
||||
MemoryUsageBytes = memoryUsageBytes;
|
||||
DiskUsagePercent = diskUsagePercent;
|
||||
UptimeSeconds = uptimeSeconds;
|
||||
}
|
||||
|
||||
public void MarkOffline()
|
||||
{
|
||||
Status = AgentStatus.Offline;
|
||||
|
||||
+1773
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Heimdall.Infrastructure.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddAgentLiveMetrics : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<double>(
|
||||
name: "CpuUsagePercent",
|
||||
table: "agents",
|
||||
type: "double precision",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<double>(
|
||||
name: "DiskUsagePercent",
|
||||
table: "agents",
|
||||
type: "double precision",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "MemoryUsageBytes",
|
||||
table: "agents",
|
||||
type: "bigint",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.AddColumn<long>(
|
||||
name: "UptimeSeconds",
|
||||
table: "agents",
|
||||
type: "bigint",
|
||||
nullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CpuUsagePercent",
|
||||
table: "agents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "DiskUsagePercent",
|
||||
table: "agents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "MemoryUsageBytes",
|
||||
table: "agents");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "UptimeSeconds",
|
||||
table: "agents");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<int>("CpuCores")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<double?>("CpuUsagePercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("timestamp with time zone")
|
||||
@@ -49,6 +52,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<DateTime?>("DeletedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<double?>("DiskUsagePercent")
|
||||
.HasColumnType("double precision");
|
||||
|
||||
b.Property<string>("GpuType")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
@@ -73,6 +79,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<long>("MemoryMb")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<long?>("MemoryUsageBytes")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
@@ -98,6 +107,9 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasColumnType("timestamp with time zone")
|
||||
.HasDefaultValueSql("NOW()");
|
||||
|
||||
b.Property<long?>("UptimeSeconds")
|
||||
.HasColumnType("bigint");
|
||||
|
||||
b.Property<string>("Version")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
@@ -1323,13 +1335,6 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
b.Property<bool>("EmailEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<bool>("NtfyEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("NtfyUrl")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("Language")
|
||||
.IsRequired()
|
||||
.ValueGeneratedOnAdd()
|
||||
@@ -1337,6 +1342,13 @@ namespace Heimdall.Infrastructure.Migrations
|
||||
.HasColumnType("character varying(10)")
|
||||
.HasDefaultValue("fr");
|
||||
|
||||
b.Property<bool>("NtfyEnabled")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<string>("NtfyUrl")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("character varying(500)");
|
||||
|
||||
b.Property<string>("SubscribedEventsJson")
|
||||
.HasColumnType("jsonb")
|
||||
.HasColumnName("subscribed_events");
|
||||
|
||||
@@ -34,9 +34,20 @@ public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthentic
|
||||
|
||||
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
// X-API-Key header only (pas de Bearer — réservé au handler JWT)
|
||||
// X-API-Key header only (pas de Bearer — réservé au handler JWT).
|
||||
// SignalR WebSocket clients cannot set custom headers, so the API key
|
||||
// is also accepted via the access_token query string on hub paths
|
||||
// (same convention as the JwtBearer handler).
|
||||
var apiKey = Request.Headers["X-API-Key"].FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey))
|
||||
{
|
||||
var path = Request.Path;
|
||||
var queryToken = Request.Query["access_token"].FirstOrDefault();
|
||||
if (!string.IsNullOrEmpty(queryToken) && path.StartsWithSegments("/hubs"))
|
||||
apiKey = queryToken;
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(apiKey) || apiKey.Length < 8)
|
||||
return AuthenticateResult.NoResult();
|
||||
|
||||
|
||||
@@ -50,7 +50,18 @@ public class AgentsController : ControllerBase
|
||||
Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
|
||||
{
|
||||
GpuAcceleration? gpuType = request.GpuType is not null && Enum.TryParse<GpuAcceleration>(request.GpuType, true, out var parsed) ? parsed : null;
|
||||
var command = new HeartbeatCommand(id, request.PublicIp, request.HasGpu, request.CpuCores, (int?)request.MemoryMb, gpuType);
|
||||
var command = new HeartbeatCommand(
|
||||
id,
|
||||
request.PublicIp,
|
||||
request.HasGpu,
|
||||
request.CpuCores,
|
||||
(int?)request.MemoryMb,
|
||||
gpuType,
|
||||
request.IsOffline,
|
||||
request.CpuUsagePercent,
|
||||
request.MemoryUsageBytes,
|
||||
request.DiskUsagePercent,
|
||||
request.UptimeSeconds);
|
||||
var result = await _mediator.Send(command, ct);
|
||||
return result.IsSuccess
|
||||
? Ok()
|
||||
|
||||
@@ -83,4 +83,45 @@ public class HeartbeatHandlerTests
|
||||
|
||||
await context.Received(1).SaveChangesWithRetryAsync(Arg.Any<int>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_should_update_live_metrics()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
IsOffline: false,
|
||||
CpuUsagePercent: 42.5,
|
||||
MemoryUsageBytes: 8_589_934_592,
|
||||
DiskUsagePercent: 61.3,
|
||||
UptimeSeconds: 3600);
|
||||
|
||||
await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
_existingAgent.CpuUsagePercent.ShouldBe(42.5);
|
||||
_existingAgent.MemoryUsageBytes.ShouldBe(8_589_934_592);
|
||||
_existingAgent.DiskUsagePercent.ShouldBe(61.3);
|
||||
_existingAgent.UptimeSeconds.ShouldBe(3600);
|
||||
_existingAgent.Status.ShouldBe(AgentStatus.Online);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Heartbeat_isOffline_should_mark_agent_offline()
|
||||
{
|
||||
var context = Substitute.For<IApplicationDbContext>();
|
||||
context.Agents.Returns(MockDbSetHelper.CreateFor<Agent>([_existingAgent]));
|
||||
var handler = new HeartbeatHandler(context);
|
||||
var command = new HeartbeatCommand(
|
||||
_existingAgent.Id, null, null, null, null, null,
|
||||
IsOffline: true,
|
||||
CpuUsagePercent: 12.0);
|
||||
|
||||
await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
_existingAgent.Status.ShouldBe(AgentStatus.Offline);
|
||||
// Metrics are not refreshed on a shutdown heartbeat
|
||||
_existingAgent.CpuUsagePercent.ShouldBeNull();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using Heimdall.IntegrationTests.Controllers;
|
||||
using Shouldly;
|
||||
|
||||
@@ -105,6 +107,93 @@ public class SignalRHubScenarios : PostgresTestBase
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConfigHub_ApiKeyInAccessTokenQueryString_ReturnsOk()
|
||||
{
|
||||
// SignalR WebSocket clients cannot set the X-API-Key header, so the
|
||||
// agent passes its API key via the access_token query string. The
|
||||
// ApiKey handler must accept it on hub paths (same as JwtBearer).
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
|
||||
// Create site + registration token + agent → get an API key
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = "ConfigHub QuerySite",
|
||||
timezone = "UTC"
|
||||
});
|
||||
var siteContent = await siteResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var siteId = siteContent.GetProperty("id").GetGuid();
|
||||
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
|
||||
var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var token = tokenContent.GetProperty("token").GetString()!;
|
||||
|
||||
var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token,
|
||||
hostname = "confighub-agent",
|
||||
version = "1.0.0-test"
|
||||
});
|
||||
var agentContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var apiKey = agentContent.GetProperty("apiKey").GetString()!;
|
||||
|
||||
// Act — negotiate with the API key in the query string (no header)
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsync(
|
||||
$"/hubs/config/negotiate?negotiateVersion=1&access_token={Uri.EscapeDataString(apiKey)}",
|
||||
null);
|
||||
|
||||
// Assert — ApiKey scheme accepts the query-string token on /hubs
|
||||
response.StatusCode.ShouldBeOneOf(HttpStatusCode.OK, HttpStatusCode.Redirect);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ConfigHub_InvalidApiKeyInQueryString_Returns401()
|
||||
{
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsync(
|
||||
"/hubs/config/negotiate?negotiateVersion=1&access_token=invalid-key-that-is-long-enough",
|
||||
null);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EventsHub_ApiKeyInQueryString_StillRequiresJwt()
|
||||
{
|
||||
// EventsHub is JWT-only; an API key in the query string must NOT
|
||||
// authenticate it (ApiKey query-string fallback is scoped to /hubs/config
|
||||
// consumers — actually all /hubs, but the JWT scheme owns these hubs).
|
||||
var admin = await Factory.CreateAdminClientAsync();
|
||||
|
||||
var siteResponse = await admin.PostAsJsonAsync("api/sites", new
|
||||
{
|
||||
name = "EventsHub QuerySite",
|
||||
timezone = "UTC"
|
||||
});
|
||||
var siteContent = await siteResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var siteId = siteContent.GetProperty("id").GetGuid();
|
||||
var tokenResponse = await admin.PostAsync($"api/sites/{siteId}/tokens", null);
|
||||
var tokenContent = await tokenResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var token = tokenContent.GetProperty("token").GetString()!;
|
||||
var registerResponse = await admin.PostAsJsonAsync("api/agents/register", new
|
||||
{
|
||||
token,
|
||||
hostname = "eventshub-agent",
|
||||
version = "1.0.0-test"
|
||||
});
|
||||
var agentContent = await registerResponse.Content.ReadFromJsonAsync<JsonElement>();
|
||||
var apiKey = agentContent.GetProperty("apiKey").GetString()!;
|
||||
|
||||
var client = Factory.CreateClient();
|
||||
var response = await client.PostAsync(
|
||||
$"/hubs/events/negotiate?negotiateVersion=1&access_token={Uri.EscapeDataString(apiKey)}",
|
||||
null);
|
||||
|
||||
// ApiKey scheme is not registered for EventsHub ([Authorize] without
|
||||
// explicit scheme uses the default = Cookies → 401 for a bare request).
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AdminHub_RequiresAdminRole()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user