## Contexte La CI actuelle délègue tout à l'action composite monolithe `ci-full` de `nonobis/templates` : build → tests → Sonar → Docker → Trivy → Dependency-Check dans **un seul job, en série**. Le runner act/forgejo cache les actions composites **par URL** (`~/.cache/act` keyé par sha256, jamais invalidé) — cause racine des échecs CI récurrents d'août 2026 (ancien contenu exécuté malgré les pushs, purges hôte, runs rouges sur les 3 LXC). Objectif : **supprimer cette CI et la refaire de zéro** en workflows natifs, plusieurs jobs **parallèles** (moins long, erreurs visibles par job), avec toutes les fonctionnalités actuelles. ## Changements - [x] `.forgejo/workflows/ci.yml` — **8 jobs parallèles inline** (zéro action composite maison) : - `build` : restore + build + `dotnet format` (gate qualité rapide) - `test-unit` : Domain + Application + Agent + Api (parallèle interne) - `test-web` : bUnit Web.Tests - `test-db` : PostgreSQL CI + Infrastructure (Testcontainers) + Integration, sérialisés - `sonar` : analyse + **gate bloquant** (avec param `pullRequest` pour les PR) - `docker` : build images (main + PR), push main (latest+sha), images de test `pr-<N>`, **Trivy bloquant** (scan de l'image locale) - `dependency-check` : OWASP **bloquant** (failOnCVSS 7.0, cache NVD `/opt/dc-cache`) - `post-summary` : **commentaire PR unique** agrégé (tests unitaires + bUnit + DB) - [x] `.forgejo/workflows/release.yml` — 2 cycles release inline : `v*` (central Web) et `agent-v*` (agent, binaires natifs linux-x64/arm64/win-x64), GitVersion double, archives, release Forgejo + notes auto, push Docker Hub - [x] `scripts/ci/` — utilitaires versionnés dans le repo : résumé tests, commentaires PR, rapports CVE (Trivy/DC), injection secrets Infisical, notes de release - [x] `renovate.yml` inchangé (dernière dépendance `templates` conservée : `RENOVATE_TOKEN` via Vault — documentée dans le ticket) Seules actions par URL conservées : `checkout@v4` et `setup-dotnet@v4` (miroirs stables). Plus de checkout `.ci` / PAT `TEMPLATES_PAT` pour la CI. ## Tickets liés (obligatoire) - Fixes #129 - Refs #125 (référencement ci-full tagué — obsolète) - Refs #104 (secrets Vault → Infisical — la CI utilise le flux Infisical) - Refs #101 (SonarQube gate conservé bloquant) ## Résultats des tests (obligatoire) - [ ] Rapport QA de the-qa : à venir (commentaire) - [ ] Tous les tests passent (voir run CI + commentaire post-summary) - [ ] Coverage : voir commentaire CI ## Retours SonarQube (obligatoire) - [ ] Quality gate SonarQube **OK** (voir run CI) - [ ] Bugs / vulnérabilités : **0 non résolu** ## CVE (obligatoire) - [ ] Aucune CVE HIGH/CRITICAL nouvelle sur cette PR (voir commentaire CI) - [ ] CVE non corrigeables documentées en commentaire (si applicable) ## Checklist - [x] Commits atomiques au format conventionnel (`ci: refonte multi-workflows — ...`) - [x] Branche issue de `main`, à jour - [x] Pas de secret en clair (tokens, mots de passe) - [x] YAML des workflows validés (pyyaml) + scripts Python compilés - [ ] CI verte : build, tests, Trivy, Dependency-Check, SonarQube (à confirmer sur le run) - [x] Release notes / versioning impacté (GitVersion conservé en release) Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/130
326 lines
11 KiB
C#
326 lines
11 KiB
C#
using System.Net;
|
|
using System.Text.Json;
|
|
using Heimdall.Agent.Services;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Microsoft.Extensions.Options;
|
|
using NSubstitute;
|
|
|
|
namespace Heimdall.Agent.Tests;
|
|
|
|
public class AgentRegistrationServiceTests : IDisposable
|
|
{
|
|
/// <summary>Shared provider so the file written by the fixture can be read
|
|
/// back by the singleton state (same Data Protection key).</summary>
|
|
private static readonly EphemeralDataProtectionProvider Provider = new();
|
|
|
|
private readonly AgentOptions _options = new()
|
|
{
|
|
CentralUrl = "http://heimdall.test",
|
|
SiteToken = "test-token",
|
|
AgentName = "test-agent",
|
|
HeartbeatIntervalSeconds = 1,
|
|
RegistrationMaxRetries = 3,
|
|
Version = "1.0.0"
|
|
};
|
|
|
|
private readonly TempDir _tmp = new();
|
|
private readonly AgentState _state = new(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
private readonly SystemMetricsProvider _metrics = new();
|
|
|
|
public AgentRegistrationServiceTests()
|
|
{
|
|
_state.ConfigureStateDirectory(_tmp.Path);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_Success_SetsAgentIdAndApiKey()
|
|
{
|
|
var handler = CreateOkHandler();
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
_state.ApiKey.ShouldBe("sk_test_abc123");
|
|
_state.ApiKeyPrefix.ShouldBe("sk_test");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_WithRetry_EventuallySucceeds()
|
|
{
|
|
var attempt = 0;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
attempt++;
|
|
if (attempt < 3)
|
|
return new HttpResponseMessage(HttpStatusCode.ServiceUnavailable);
|
|
|
|
return CreateRegistrationResponse();
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
// Retry backoff: 2^1=2s, 2^2=4s → ~7s for 3 attempts.
|
|
// Poll instead of a fixed delay: under parallel CI load the
|
|
// background service can be delayed beyond 8s (flaky #2228).
|
|
var deadline = DateTime.UtcNow.AddSeconds(25);
|
|
while (DateTime.UtcNow < deadline && _state.AgentId == Guid.Empty)
|
|
await Task.Delay(250);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Registration_AllRetriesFail_LogsError()
|
|
{
|
|
var handler = new MockHttpMessageHandler(_ =>
|
|
new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
// StartAsync does not throw — the exception is caught by BackgroundService.
|
|
// Verify the service enters a faulted state.
|
|
await service.StartAsync(CancellationToken.None);
|
|
|
|
// Wait for all retries to exhaust (backoff 2+4+8s under parallel CI load).
|
|
// Poll instead of a fixed delay to avoid flaky timing.
|
|
var deadline = DateTime.UtcNow.AddSeconds(30);
|
|
while (DateTime.UtcNow < deadline && _state.ApiKey is null)
|
|
await Task.Delay(250);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
// AgentId should remain empty because registration never succeeded
|
|
_state.AgentId.ShouldBe(Guid.Empty);
|
|
_state.ApiKey.ShouldBeNull();
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExistingIdentity_SkipsRegistration()
|
|
{
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
|
saved.AgentId = Guid.NewGuid();
|
|
saved.ApiKey = "existing-key";
|
|
saved.ApiKeyPrefix = "existing";
|
|
await saved.SaveAsync();
|
|
|
|
// Also set the DI singleton state with same values
|
|
_state.AgentId = saved.AgentId;
|
|
_state.ApiKey = saved.ApiKey;
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
|
|
|
var registrationCalled = false;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
registrationCalled = true;
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
|
{
|
|
agentId = Guid.NewGuid(),
|
|
apiKey = "new-key",
|
|
apiKeyPrefix = "new"
|
|
}))
|
|
};
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
registrationCalled.ShouldBeFalse();
|
|
_state.ApiKey.ShouldBe("existing-key"); // unchanged
|
|
}
|
|
|
|
[Fact]
|
|
public async Task StopAsync_SendsOfflineHeartbeat()
|
|
{
|
|
HttpResponseMessage? lastHeartbeat = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
lastHeartbeat = new HttpResponseMessage(HttpStatusCode.OK);
|
|
return lastHeartbeat;
|
|
}
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
// Agent must be registered after the flow
|
|
_state.AgentId.ShouldNotBe(Guid.Empty);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Heartbeat_UsesXApiKeyHeader_NotBearer()
|
|
{
|
|
string? xApiKey = null;
|
|
string? authorization = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
? values.FirstOrDefault()
|
|
: null;
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
}
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
// Registration first, then heartbeat (interval 1s). Poll for the
|
|
// heartbeat instead of a fixed 500ms delay (flaky under CI load).
|
|
var deadline = DateTime.UtcNow.AddSeconds(10);
|
|
while (DateTime.UtcNow < deadline && xApiKey is null)
|
|
await Task.Delay(100);
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
xApiKey.ShouldNotBeNull(); // API key sent via X-API-Key header
|
|
authorization.ShouldBeNull(); // never as Bearer
|
|
}
|
|
|
|
[Fact]
|
|
public async Task ExistingIdentity_Heartbeat_UsesXApiKeyHeader()
|
|
{
|
|
// Pre-populate the state file so LoadAsync() finds an identity
|
|
var saved = new AgentState(Provider.CreateProtector(AgentState.KeyProtectionPurpose));
|
|
saved.ConfigureStateDirectory(_tmp.Path);
|
|
saved.AgentId = Guid.NewGuid();
|
|
saved.ApiKey = "existing-key";
|
|
saved.ApiKeyPrefix = "existing";
|
|
await saved.SaveAsync();
|
|
|
|
_state.AgentId = saved.AgentId;
|
|
_state.ApiKey = saved.ApiKey;
|
|
_state.ApiKeyPrefix = saved.ApiKeyPrefix;
|
|
|
|
string? xApiKey = null;
|
|
string? authorization = null;
|
|
var handler = new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/heartbeat") == true)
|
|
{
|
|
xApiKey = req.Headers.TryGetValues("X-API-Key", out var values)
|
|
? values.FirstOrDefault()
|
|
: null;
|
|
authorization = req.Headers.Authorization?.ToString();
|
|
}
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
|
|
var factory = CreateHttpClientFactory(handler);
|
|
var service = CreateService(factory);
|
|
|
|
await service.StartAsync(CancellationToken.None);
|
|
await Task.Delay(500);
|
|
|
|
await service.StopAsync(CancellationToken.None);
|
|
|
|
xApiKey.ShouldBe("existing-key");
|
|
authorization.ShouldBeNull();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
_tmp.Dispose();
|
|
GC.SuppressFinalize(this);
|
|
}
|
|
|
|
// --- Helpers ---
|
|
|
|
private AgentRegistrationService CreateService(
|
|
IHttpClientFactory factory,
|
|
AgentState? state = null)
|
|
{
|
|
state ??= _state;
|
|
return new AgentRegistrationService(
|
|
factory,
|
|
state,
|
|
Options.Create(_options),
|
|
_metrics,
|
|
new Logging.LogBufferService(),
|
|
NullLogger<AgentRegistrationService>.Instance);
|
|
}
|
|
|
|
private static IHttpClientFactory CreateHttpClientFactory(
|
|
MockHttpMessageHandler handler)
|
|
{
|
|
var client = new HttpClient(handler) { BaseAddress = new Uri("http://heimdall.test") };
|
|
var factory = Substitute.For<IHttpClientFactory>();
|
|
factory.CreateClient("Central").Returns(client);
|
|
factory.CreateClient("IpResolver").Returns(client);
|
|
return factory;
|
|
}
|
|
|
|
private static MockHttpMessageHandler CreateOkHandler()
|
|
{
|
|
return new MockHttpMessageHandler(req =>
|
|
{
|
|
if (req.RequestUri?.ToString().Contains("/register") == true)
|
|
return CreateRegistrationResponse();
|
|
|
|
return new HttpResponseMessage(HttpStatusCode.OK);
|
|
});
|
|
}
|
|
|
|
private static HttpResponseMessage CreateRegistrationResponse()
|
|
{
|
|
return new HttpResponseMessage(HttpStatusCode.OK)
|
|
{
|
|
Content = new StringContent(JsonSerializer.Serialize(new
|
|
{
|
|
agentId = Guid.NewGuid(),
|
|
apiKey = "sk_test_abc123",
|
|
apiKeyPrefix = "sk_test"
|
|
}))
|
|
};
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Mock HTTP handler that returns predefined responses per request.
|
|
/// </summary>
|
|
public class MockHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> handler)
|
|
: HttpMessageHandler
|
|
{
|
|
protected override Task<HttpResponseMessage> SendAsync(
|
|
HttpRequestMessage request, CancellationToken cancellationToken)
|
|
{
|
|
return Task.FromResult(handler(request));
|
|
}
|
|
}
|