Commit Graph
75 Commits
Author SHA1 Message Date
Arnaud Dartois d774d28f2a refactor(settings): manage integrations through Central UI
Heimdall Gitea / Detect CI scope (pull_request) Successful in 5s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
Heimdall Gitea / Build and tests (pull_request) Canceled after 7m33s
Heimdall Gitea / CI policy (pull_request) Failing after 2s
2026-10-26 06:26:00 +01:00
Arnaud Dartois 96af711eac feat(i18n): apply saved language to shell and profile
Heimdall Gitea / Build and tests (pull_request) Failing after 7m21s
Heimdall Gitea / Build and scan server image (pull_request) Skipped
Heimdall Gitea / Build and scan agent image (pull_request) Skipped
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / Publish versioned release (pull_request) Skipped
2026-10-25 04:19:19 +01:00
Arnaud Dartois 8d5447f826 fix(agent): align failover with heartbeat intervals
Heimdall Gitea / Build and tests (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan server image (pull_request) Canceled after 0s
Heimdall Gitea / Build and scan agent image (pull_request) Canceled after 0s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Canceled after 0s
Heimdall Gitea / Publish versioned release (pull_request) Canceled after 0s
2026-10-25 02:55:31 +02:00
Arnaud Dartois f0cf011c30 Remove RabbitMQ and use existing SignalR agent channel
Heimdall Gitea / Build and tests (pull_request) Failing after 49s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
2026-10-21 17:52:53 +02:00
Arnaud Dartois 7ecf4ad247 merge: integrate access isolation into auth session security 2026-10-20 07:22:51 +02:00
Arnaud Dartois 26321bb81c fix(auth): secure 2FA challenges and session revocation 2026-10-20 07:21:28 +02:00
Arnaud Dartois 1cd4e2b4b5 fix(security): enforce resource isolation across API and hubs 2026-10-20 07:16:44 +02:00
Arnaud Dartois e068825768 feat(i18n): add localization infrastructure and configure request localization (issue #142)
- Add Localization services with ResourcesPath to Localization folder
- Configure RequestLocalizationMiddleware with fr/en support
- Query string and cookie culture providers
- Supported cultures: fr (default), en
- Build successful, all 1700+ tests pass

Note: Components need IStringLocalizer injection and @L[] usage - ready for incremental adoption
2026-10-10 22:55:26 +02:00
Arnaud Dartois 9a77a775a3 fix: suppress PendingModelChangesWarning for global query filters (#197)
## Contexte

Les migrations de base de données échouent à cause d'un warning EF Core `PendingModelChangesWarning` promu en exception lors du démarrage du conteneur.

**Cause racine** : Les filtres de requête globaux (utilisés pour le soft-delete) provoquent ce warning quand le modèle a des changements en attente. Npgsql/EF Core lève une `InvalidOperationException` au lieu de simplement logger.

## Changements

- Ajout de `warnings.Ignore(CoreEventId.PendingModelChangesWarning)` dans `OnModelCreating`
- Commentaire explicatif dans `Program.cs` sur la suppression

## Tests

- Vérifié : les migrations s'appliquent correctement
- Les filtres soft-delete continuent de fonctionner

**Note** : Le Co-authored-by est interdit dans les commits (règle projet).

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/197
2026-09-01 10:18:43 +02:00
Arnaud Dartois bf2ccad537 feat(broker): RabbitMQ + MassTransit job broker pour l'analyse inter-sites
feat(broker): add RabbitMQ + MassTransit job broker for cross-site analysis

Mutualise les ressources IA/GPU entre sites via un broker de jobs durable.
RabbitMQ + MassTransit avec connexion AMQP sortante (pas de port entrant).

- Heimdall.Contracts: contrats de messages partagés
- RabbitMQ: conteneur docker + credentials via env vars
- MassTransit Central: publication de jobs d'analyse
- MassTransit Agent: consommateur avec backpressure GPU

Fixes #72
2026-08-28 01:11:12 +02:00
Arnaud Dartois 2d1734114f feat(metrics): métriques OpenTelemetry Prometheus (spec §13.1) (#161) 2026-08-20 18:22:37 +02:00
Arnaud Dartois 13456ab4f5 fix(security): align rate limiting and password po 2026-08-20 18:14:18 +02:00
Arnaud Dartois d0e731a243 fix(sonar): réduit la complexité cognitive de Conf 2026-08-20 18:14:11 +02:00
Arnaud Dartois 4792b69e46 feat(agent): télémétrie inventaire matériel — CPU/mémoire/disque/GPU/OS/réseau (Fixes #82 #83 #84 #85) (#137)
## Contexte

Implémentation des tickets #82, #83, #84, #85 — télémétrie inventaire matériel agent. L'objectif est de fournir au central un maximum d'informations sur les machines des agents (CPU, mémoire, disques, GPU, OS, réseau, conteneur) sans SSH.

## Changements

### Nouveaux collecteurs (src/Heimdall.Agent/Services/)
- **CpuInfoProvider** : parse `/proc/cpuinfo` (vendor, modèle, cœurs physiques/logiques, fréquence, flags AVX/AVX2/FMA/AVX512, cache), topologie, détection cgroup CPU (`/sys/fs/cgroup/cpu.max` v2)
- **DiskInventoryProvider** : énumère les montages (`/proc/mounts`), capacité/libre/type SSD/HDD via `/sys/block/*/queue/rotation`
- **GpuInventoryProvider** : nvidia-smi, sysfs DRM, vainfo, rocm-smi avec fallback silencieux, multi-GPU
- **HostInfoProvider** : os-release, uname, `/proc/uptime` (uptime machine ≠ process), températures sysfs
- **ContainerInfoProvider** : détection Docker (/.dockerenv, cgroup), ID conteneur, limites CPU/mémoire

### Refonte SystemMetricsProvider
- Séparation host vs process (RAM machine ≠ RAM conteneur ≠ WorkingSet64)
- Uptime machine (`/proc/uptime`) distinct de l'uptime process
- Mémoire swap

### Entité Agent + Migration
- Champs structurés CPU/mémoire/disque/GPU/OS/réseau (tous nullable, rétrocompatible)
- Migration EF `AddAgentTelemetryInventory`

### Transport heartbeat
- Inventaire au register + refresh périodique (5 min, pas à chaque tick)
- Champs JSON pour listes (disques, GPU, interfaces réseau, températures)

### UI Admin (AgentDetail.razor)
- Sections CPU, Mémoire/Disques, GPU, Machine/Conteneur avec barres de progression et badges

### Tests
- 40+ tests unitaires : providers, handlers, entité Agent
- Total : 999 tests verts (Domain 149, Application 397, Agent 210, Web 243)

## Tickets liés
- Fixes #82 — CPU inventory
- Fixes #83 — Mémoire & disque
- Fixes #84 — GPU inventory
- Fixes #85 — OS, conteneur, réseau

## Résultats des tests
- `dotnet build` : 0 erreur, 0 warning
- Domain.Tests : 149 passed
- Application.Tests : 397 passed
- Agent.Tests : 210 passed
- Web.Tests : 243 passed
- Total : 999 tests ✅

## Checklist
- [x] `dotnet build` vert (TreatWarningsAsErrors)
- [x] Tests unitaires verts
- [x] Migration EF créée
- [x] Champs nullable (rétrocompatible)
- [x] Pas de référence Infrastructure dans les contrôleurs
- [x] Collecteurs avec fallback silencieux (pas de crash sans GPU/Docker/sysfs)

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/137
2026-08-20 14:13:06 +02:00
Arnaud Dartois 1fbeff9906 ci: refonte multi-workflows — suppression du monolithe ci-full templates (Fixes #129) (#130)
## 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
2026-08-18 08:22:47 +02:00
Arnaud Dartois 566aa84bc7 chore: auto-commit 2026-08-12 20:05 [Heimdall] src/Heimdall.Agent/Services/AgentRegistrationService.cs, src/Heimdall.Agent/Services/SnapshotPipelineService.cs, src/Heimdall.Application/DTOs/SettingDto.cs, src/Heimdall.Domain/Entities/UserNotificationConfig.cs, src/Heimdall.Infrastructure/BackgroundJobs/DependencyInjection.cs… 2026-08-12 20:05:12 +02:00
Arnaud Dartois dc8a24918d feat(settings): topic ntfy par site, SMTP/ntfy/S3 globaux, DSN GlitchTip fixe + toggle (Fixes #105 #106 #107 #108)
#105 — Topic ntfy cible par site :
- Site.NtfyTopic (migration AddSiteNtfyTopic), UI création/édition SitesPage
- NotificationService.ResolveNtfyTopicAsync : topic du site sinon heimdall_{userId}

#106 — Paramètres SMTP/ntfy/S3 GLOBAUX :
- Seed + sections UI : agentScoped=false pour ntfy.*/email.*/storage.*/sentry.*
- Migration douce au démarrage : UPDATE des clés existantes en base

#107 — GlitchTip : DSN fixes (central projet 6, agent projet 7) dans appsettings,
- plus de champ DSN éditable en UI → switch sentry.enabled (nécessite redémarrage)
- Init Sentry déplacé après AddInfrastructure, lit sentry.enabled en base (fallback true)

#108 — Composants typés : MudNumericField borné (port SMTP, rétention, heartbeat),
- switch pour booléens, select pour log.level — pas de saisie libre
2026-08-12 12:18:52 +02:00
Arnaud Dartois 83d46f0f99 fix(seed): check idempotent via HashSet en mémoire (casse ignorée)
string.Equals(..., OrdinalIgnoreCase) n'est pas traduisible par EF/Npgsql
(exception de compilation de requête au démarrage). On charge les clés
existantes une fois dans un HashSet<StringComparer.OrdinalIgnoreCase> et on
compare côté client — 1 requête, idempotent, pas de doublon possible.
2026-08-12 11:37:23 +02:00
Arnaud Dartois 733d075572 fix(seed): check idempotent storage insensible à la casse (accessKey/secretKey)
Même bug que les intégrations : storage.s3.accessKey/secretKey en camelCase
ne matchaient pas les clés lowercase en base → re-Add à chaque démarrage →
violation IX_app_settings_key → crash loop (exit 139).
2026-08-12 11:29:03 +02:00
Arnaud Dartois 87c238aa86 fix(seed): check idempotent ignore la casse (CA1862) + gitignore fichiers GitVersion générés 2026-08-12 11:19:42 +02:00
Arnaud Dartois d566c21c7f fix(seed): check idempotent en lowercase — évite les doublons au redémarrage
Le constructeur AppSetting lower-case les clés ; le AnyAsync comparait en
camelCase → à chaque redémarrage le seed re-créait les clés d'intégration →
violation IX_app_settings_key → crash (exit 139) en boucle.
2026-08-12 11:17:59 +02:00
Arnaud Dartois d527f3ccc9 feat(settings): sections visuelles IA/Notifications/Défauts agents — suppression du CRUD clé/valeur (Fixes #79)
- SettingsPage refondue : plus de création/édition clé/valeur arbitraire,
  chaque domaine a sa section dédiée (pattern StorageSettingsSection)
- NotificationSettingsSection : ntfy (baseUrl, token) + email SMTP (from,
  host, port, user, password, SSL) — secrets masqués, redaction API respectée
- AiSettingsSection : URLs CodeProject.AI/Ollama + toggle détection IA
- AgentDefaultsSection : niveau de log global (select), rétention logs,
  intervalle heartbeat, DSN Sentry
- Seed #80 étendu : ai.detection.enabled, log.level, log.retentionDays,
  heartbeat.interval.seconds, sentry.dsn (idempotent, catégories cohérentes)
- Tests bUnit : 12 tests (4 page + 8 sections) — rendu, PUT par clé, secrets
  redactés invisibles ; 221 tests Web verts
2026-08-12 10:46:09 +02:00
Arnaud Dartois a07a0cae52 feat(settings): seed clés d'intégration ntfy/email/IA en base (partiel #80)
- Seed idempotent des clés ntfy.baseUrl/ntfy.token, email.* (SMTP),
  ai.cpaiUrl, ai.ollamaUrl — catégorie 'integrations', valeurs initiales
  depuis env (migration douce env → DB)
- Prérequis backend pour l'UI de configuration des intégrations (#79/#80)
2026-08-12 10:20:55 +02:00
Arnaud Dartois 7d6213696f feat(storage): stockage configurable par l'IHM — providers Fichier + S3 (Fixes #78)
- IStorageProvider (Application) : Upload/Download/Delete/DeleteBatch/Health
- LocalStorageProvider : écriture atomique (tmp + move), anti path-traversal
- AlarikStorageProvider : S3-compatible (AWS SDK, ForcePathStyle), upload
  staging→final (atomique), batch delete 1000/appel (Correctif D6)
- StorageProviderFactory : provider résolu depuis les settings DB
  (storage.provider = Local|S3) avec fallback env, re-résolu à chaque appel
- Seed idempotent des clés storage.* (catégorie 'storage') au démarrage
- UI : section 'Stockage' dédiée dans SettingsPage (sélecteur Local/S3,
  champs conditionnels, clé secrète masquée, bouton Tester → POST
  /api/settings/storage/test)
- Tests : 6 LocalStorageProvider (roundtrip, delete, batch, traversal,
  health) ; Web 217/217, Infrastructure 177/177, Application 391/391
2026-08-12 10:14:40 +02:00
Arnaud Dartois 381410510f feat(health): health checks complets /health/ready + /health/live (Fixes #13)
- Checks enregistrés : PostgreSQL (ready+live), Alarik S3 (ready),
  CodeProject.AI/Ollama (live) — optionnels → Healthy si non configurés
- Routes : /health (alias /healthz), /health/ready (alias /readyz),
  /health/live → 503 + degradationLevel quand IA dégradée
- Fix CI : dashboard Hangfire skip en Testing (Hangfire désactivé → crash
  au démarrage WebApplicationFactory) — IntegrationTests 125/125 verts
2026-08-12 09:54:37 +02:00
Arnaud Dartois e3d14eec04 feat(jobs): jobs Hangfire rétention/cleanup + dashboard admin (Fixes #8)
- RetentionCheckJob (quotidien 3h) : purge enregistrements expirés par
  StoragePolicy via ExecuteDelete (1 requête, pas de boucle), défaut 30 j
- CleanupUnknownFacesJob (dim 5h) : personnes 'unknown' > 30 j
- CleanupLicensePlatesJob (dim 6h) : plaques non associées > 30 j
- DatabaseMaintenanceJob (dim 7h) : VACUUM events + REINDEX (VACUUM FULL
  1er dimanche)
- Dashboard Hangfire /hangfire protégé AdminJobs (filtre custom)
- S3CleanupJob dépend du ticket #7 (stockage S3) — non inclus ici
- Tests : 2 (rétention avec/sans politique)
2026-08-12 09:43:45 +02:00
Arnaud Dartois a4503e76ac fix(ci): répare 31 tests cassés — 401 API, login prerender off, culture bUnit
Trois régressions distinctes cassent la CI depuis le run 207 :

1. Auth API (29 tests d'intégration) : depuis 16d739e, les contrôleurs
   acceptent JwtBearer+Cookies ; le challenge par défaut étant le cookie,
   les requêtes API non authentifiées étaient redirigées 302 vers /login
   au lieu de répondre 401/403 (le client de test suivait → 200 OK).
   → IsApiRequest() dans OnRedirectToLogin/OnRedirectToAccessDenied :
     requête /api/* ou Accept: application/json → 401/403 direct.

2. Get_LoginPage_ReturnsOk : depuis db703be (prerender:false), /login sert
   le shell Blazor sans le contenu du composant en SSR. Le test vérifie
   désormais le shell (_framework/blazor.web.js) au lieu de 'Se connecter'.

3. Tests bUnit (2) : le runner CI a une locale fr-FR → {Confidence:P0}
   rend '87 %' au lieu de '87%'. MudTestBase force en-US (statique +
   thread courant) pour un rendu déterministe partout.

Vérifié : 1042/1042 tests verts, y compris sous LANG=fr_FR.UTF-8.
2026-08-11 12:35:45 +02:00
Arnaud Dartois c2ff225e59 fix(web): appels API du circuit authentifiés après reload — cookie SSR propagé, purge au login/logout (Fixes #45) 2026-08-11 11:59:18 +02:00
Arnaud Dartois 17ed0a19a1 feat(web): navigation & layout responsive — drawer adaptatif, badge notif, dark toggle (Fixes #33)
- Drawer : Breakpoint.Sm + mini-variant (64px) — responsive mobile/desktop.
- Nav restructurée : Événements et Snapshots SORTIS de la section
  Administration (bug d'accès : masqués aux non-admin alors que les pages
  sont autorisées) — section Navigation pour tous les connectés.
- Badge notifications temps réel : NotificationsHubClient (SignalR,
  access_token JWT, reconnexion auto, fallback silencieux) +
  NotificationBadge dans l'AppBar (compteur non lues, clic → /events).
- Toggle clair/sombre dans l'AppBar (IsDarkMode du MudThemeProvider).
- PageTestBase : enregistre NotificationsHubClient pour les tests bUnit.
172 tests Web verts.
2026-08-10 22:49:37 +02:00
Arnaud Dartois 462a748d5f fix(api): sérialise les enums en string dans les réponses MVC
Le JsonStringEnumConverter n'était configuré que sur Http.Json.JsonOptions
(liaison de requêtes), pas sur AddControllers → les réponses API
renvoyaient les enums en nombre (ex. "status": 1 pour Agent.Status).
Le client Blazor (AgentItem.Status est un string) échouait en
désérialisation → la page Agents affichait une erreur JSON et le
dashboard comptait 0 agent en ligne.

AddJsonOptions sur AddControllers corrige toutes les réponses
(agents, caméras, sites...).
2026-08-10 10:40:17 +02:00
Arnaud Dartois 53b6240a3e fix(auth): répare l'authentification de bout en bout (cookie + JWT + rendu Blazor)
Anomalies corrigées :
- MudPopoverProvider manquant dans les layouts → circuit Blazor mourait sur
  l'ouverture de menus/popovers (dashboard jamais rendu après login)
- AddIdentity redéfinissait le schéma par défaut sur Identity.Application
  alors que /_auth/signin signait avec Cookies → cookie posé mais jamais
  validé, tout rechargement de page redirigeait vers /login. Forçage du
  schéma par défaut sur Cookies + schémas JwtBearer explicites sur les
  endpoints API d'AuthController et SettingsController
- Policy 'AdminUsers' utilisée par register-admin mais jamais enregistrée
  → 500 à l'appel. Ajoutée (RequireRole Admin)
- HeimdallAuthStateProvider ne lisait que le sessionStorage navigateur :
  pendant le prerender SSR, HttpContext.User (cookie) n'était pas utilisé
  → pages protégées redirigées vers /login. Fallback cookie ajouté
- SameOriginHttpMessageHandler : résolution de l'origine via
  IServerAddressesFeature quand IHttpContextAccessor est null (circuit
  Blazor post-hydratation) au lieu de heimdall.local → DNS cassé
- UpdateUserValidator rejetait le thème 'Auto' (défaut de l'UI) → 400
  à l'édition. Accepte désormais auto (case-insensitive)

Tests :
- E2E Playwright complets (login/logout/register/user management) : 33/33
- Integration (Testcontainers PostgreSQL) : 120/120 (valeur 'bool' du
  valueType, bootstrap admin via /register auto-admin, header X-API-Key,
  /proc/meminfo optionnel pour les LXC restreints)
- Exécution E2E séquentielle (xunit.runner.json) pour éliminer le flakiness
2026-08-09 23:43:11 +02:00
Arnaud Dartois 094567234f fix: disable demo seeding by default and skip in tests
- Change Seed:DemoOnStartup default from true to false (safe upgrade)
- Add Seed:DemoOnStartup=false in appsettings.Testing.json
  (prevents 120 integration test failures due to missing admin password)
- Update diagnostic log message accordingly
2026-07-29 14:48:08 +00:00
Arnaud Dartois afc1b2e032 fix: resolve demo admin seeding, Sentry DSN pass-through, and add startup diagnostics
- Replace IsDevelopment() guard with Seed:DemoOnStartup config flag
  (default: true, disable via SEED__DEMO_ON_STARTUP=false)
- Add Seed:AdminLogin (env SEED__ADMIN_LOGIN) to customize demo admin email
- Add Seed:AdminDisplayName (env SEED__ADMIN_DISPLAYNAME) to customize display name
- Add Sentry__Dsn env var to docker-compose files (matches .env convention)
- Increase Heimdall log level to Debug for startup diagnostics
- Add [DIAG] startup logs for Sentry DSN, Data Protection keys, environment
- Add Data Protection key directory diagnostic in DependencyInjection
2026-07-29 14:21:16 +00:00
Arnaud Dartois 450e019617 feat(infra): intégration Sentry/GlitchTip complète
- Upgrade Sentry.AspNetCore v6.7.0 → v6.8.0
- Ajout Sentry base package à Infrastructure (pour SentryErrorReporter)
- Configuration SDK enrichie dans Web et Agent:
  - AutoSessionTracking=false (GlitchTip ne supporte pas)
  - EnableLogs=true (logs structurés)
  - CaptureBlockingCalls=true (détection .Result/.Wait())
  - CaptureFailedRequests=true (capture 4xx/5xx HttpClient)
  - IncludeActivityData=true (DiagnosticSource)
  - SetBeforeSend pour nettoyage PII (password, token, secret)
  - SetBeforeBreadcrumb pour filtrage breadcrumbs
  - SampleRate, AttachStacktrace, MaxBreadcrumbs configurés
  - Release depuis la config, Environment auto
  - StackTraceMode.Enhanced
  - double.Parse avec CultureInfo.InvariantCulture
  - UseSentry avec type explicite SentryAspNetCoreOptions
- Abstraction IErrorReporter dans Application (0 dép. Sentry)
- Implémentation SentryErrorReporter dans Infrastructure
- Enregistrement DI dans Infrastructure
- DSN de développement dans appsettings.Development.json
- .env.example avec Sentry__Dsn et Sentry__TracesSampleRate
2026-07-28 14:52:52 +00:00
Arnaud Dartois 234c158a69 fix(auth): audit de securite complet - 12 correctifs
# Fix #28: ProtectedLocalStorage -> ProtectedSessionStorage
#   (donnees token jamais exposees au JS client en Blazor Server)
# Fix #3: GetUserIdFromExpiredToken valide maintenant la signature
#   (plus de ReadJwtToken sans validation)
# Fix #5: API Key handler X-API-Key uniquement (plus de Bearer ambiguité)
# Fix #7: MarkUsed() persiste via SaveChangesAsync()
# Fix #8: Hardcoded permissions (documenté — nécessite migration DB)
# Fix #12: Race condition registration — try/catch DbUpdateException
# Fix #13: Public registration DESACTIVEE par defaut (pas de setting = disabled)
# Fix #15/17: Enable2fa genere et retourne shared key + QR code URI
# Fix #16: Rate limiting specifique 2FA (5 req/min) et RegisterAdmin
# Fix #22/23: RevokeRefreshToken stocke jti (pas token brut)
# Fix #24: Rotation refresh token — ancien token revoque apres refresh
# Fix #39: Audit logging des echecs de login (via IUserRepository)

Breaking: Enable2fa retourne maintenant Enable2faResponse au lieu de Ok()
2026-07-28 14:37:52 +00:00
Arnaud Dartois edc739dffe fix(sentry): use config pipeline for DSN, add MaxRequestBodySize and ProfilesSampleRate
- Heimdall.Web/Program.cs: use Sentry:Dsn from IConfiguration as primary
  source with legacy SENTRY_DSN env var as fallback (no hardcoded DSN)
- Heimdall.Agent/Program.cs: same pattern applied
- Both: add MaxRequestBodySize=Small and ProfilesSampleRate=0.05
  (previously missing); lower TracesSampleRate to 0.05
- appsettings.json: add Sentry:Dsn entry for discoverability

Resolves codify signal: hardcoded-sdk-credentials (C1)
2026-07-28 10:14:34 +00:00
Arnaud Dartois 87eb0982a7 refactor: replace URI string concatenation with EndsWith check
Replace new Uri(url.TrimEnd('/') + "/") pattern with explicit
EndsWith('/') check to avoid string concatenation inside URI
construction. Applies to 3 locations:
- Program.cs (Heimdall.Web) - HttpClient base address
- TokenRefreshHandler.cs - raw HttpClient for token refresh
- Program.cs (Heimdall.Agent) - Central service client
2026-07-27 18:43:25 +00:00
Arnaud Dartois 80b592ba04 fix: remove hardcoded admin seed password from Program.cs
Replace the 'Admin123!Pass' fallback with an InvalidOperationException
that requires Seed:AdminPassword from config or SEED__ADMIN_PASSWORD env
variable. Keeps the env var fallback as second option before throwing.
2026-07-27 18:39:07 +00:00
Arnaud Dartois f9be0f1e0d feat: implémenter SignalR hubs (Monitoring, Notifications, Admin) + système de notifications complet
SignalR Hubs:
- MonitoringHub (/hubs/monitoring) — statuts agents/caméras/stockage/GPU jobs
- NotificationsHub (/hubs/notifications) — notifications in-app badge temps réel
- AdminHub (/hubs/admin) — broadcast changements config (Admin only)

Notification System:
- Nouvelles entités: Notification, NotificationTemplate, UserNotificationConfig
- CQRS/MediatR: 6 handlers (list, unread, mark-read, mark-all, config get/update)
- Infrastructure: NotificationService orchestrator + EmailService + GotifyService
- Rate limiter IMemoryCache (20 events/min/camera/type)
- Hangfire jobs: SendNotification, DailyDigest, WeeklyDigest
- NotificationsController API (6 endpoints)
- Blazor UI: NotificationsPage + NotificationBadge
- Migration AddNotifications (3 nouvelles tables)
- 644 nouveaux tests (Domain: 131, Application: 321, Infra: 151, Integration: 120, +autres)
2026-07-26 20:45:35 +00:00
Arnaud Dartois ef3ea9d1ca fix: resolve 7 code quality issues from audit
- Add CancellationTokenSource timeout to DB migration loop (5 min)
- Make seed admin password configurable via env/config
- Improve ExceptionFilter with typed exception handling (409/499/500)
- Document Hangfire.PostgreSql CS0618 pragma with upgrade link
- Narrow CredentialProtector fallback catch to non-empty ciphertext
- Fix ApiBaseUrl in appsettings.json (:5000 -> :8080) for Docker consistency
- Improve HTTPS reverse proxy comment in middleware config

Build: 0 errors, 0 warnings | Tests: 799/799 passed
2026-07-26 19:49:42 +00:00
Arnaud Dartois 50507ad86a fix(auth): move ConfigureApplicationCookie after AddInfrastructure
AddIdentity (called by AddInfrastructure) sets default cookie paths
(/Account/Login) that override our custom paths. Move
ConfigureApplicationCookie after AddInfrastructure to ensure our
custom paths (/login) take precedence.
2026-07-24 19:29:02 +00:00
Arnaud Dartois a379f2b136 feat(logging): add comprehensive authentication logging
- Add cookie authentication event logging in Program.cs (redirect to login, access denied, principal validation)
- Add logging in RedirectToLogin.razor for redirection tracking
- Add detailed logging in Login.razor for login attempts, 2FA verification, and authentication completion
- Add structured logging in AuthController for all authentication endpoints (register, login, 2fa, refresh, change-password, logout, etc.)
- Use appropriate log levels (Information, Warning, Error, Debug) based on event importance
2026-07-24 18:25:33 +00:00
Arnaud Dartois 550c621f35 fix(auth): move ConfigureApplicationCookie to Program.cs to override Identity defaults
Move ConfigureApplicationCookie configuration from DependencyInjection.cs
to Program.cs, ensuring it's called AFTER AddAuthentication().AddCookie().
This prevents Identity default paths (/Account/Login) from overriding
custom login paths (/login).
2026-07-24 18:15:56 +00:00
Arnaud Dartois 261f922ad1 fix(web): disable HTTPS redirection when not configured
The application forced HTTPS redirection and secure cookies
even in HTTP-only mode (Docker deployment), preventing
plain HTTP connections.

Make UseHttpsRedirection() conditional on ASPNETCORE_URLS
and change CookieSecurePolicy from Always to SameAsRequest.
2026-07-24 13:52:22 +00:00
Arnaud Dartois a94afed6b5 test(e2e): add Playwright E2E tests for Blazor pages; refactor Program.cs to support test server 2026-07-23 18:12:47 +00:00
Arnaud Dartois 1d1ac8387e feat(cqrs): update controllers, add AutoMapper profiles, SignalR notifications, Hangfire config
- 13 controllers migrated from service DI to IMediator dispatch
- 11 AutoMapper mapping profiles (Sites, Cameras, Auth, Users, Agents, Events, Assignments, Settings, Groups, Persons, Discovery)
- SignalR notifications bridged via MediatR INotificationHandler
- Hangfire config moved from Program.cs to Infrastructure/BackgroundJobs
- 0 build errors, 0 warnings
2026-07-22 19:54:55 +00:00
Arnaud Dartois e309611f80 fix(ci): skip Hangfire en Testing pour eviter crash PostgreSQL
- Ajout isTesting = builder.Environment.IsEnvironment("Testing")\n  Les tests WebApplicationFactory n'ont pas de PostgreSQL\n- Hangfire DI + recurring jobs skips si isTesting\n- Compatible avec appsettings.Testing.json (Hangfire:Enabled=false retire)\n\nFix le CI qui plantait: 'Failed to connect to 127.0.0.1:5432'\nTests: 226/226 passed
2026-07-21 10:16:19 +00:00
Arnaud Dartois 27b6025565 fix(startup): Hangfire toujours actif en prod, migrations auto, crash boucle corrige
- Hangfire: retire le flag Hangfire:Enabled (toujours actif si DATABASE_URL\n  est defini, skip automatiquement en test sans config)\n- Database:MigrateOnStartup: default true en Production (.IsProduction())\n  Plus besoin de variable d'env pour que les migrations s'executent\n- Recurring jobs registers dans if(connectionString) pour eviter le\n  crash 'No service for IRecurringJobManager' quand Hangfire est skip\n- Corrige le crash boucle 'relation roles does not exist' apres reset DB\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
2026-07-21 09:57:22 +00:00
Arnaud Dartois 7a02a87e4c fix(startup): migration automatique en Production meme sans config
- Database:MigrateOnStartup default now true in Production\n  (GetValue<bool?> null-coalesce app.Environment.IsProduction())\n  Evite le crash 'relation roles does not exist' apres reset DB\n- En Testing: reste false (comportement inchange)
2026-07-21 09:46:33 +00:00
Arnaud Dartois 7be5d42e85 fix(identity): DB refresh tokens, auto-refresh handler, 2FA endpoints, JWT fix
- DB-backed RevokedRefreshToken entity + migration (remplace ConcurrentDictionary\n  en memoire, fonctionne en multi-instance et survive aux redemarrages)\n- TokenRefreshHandler: auto-refresh des JWT 401 via DelegatingHandler\n  (avec SemaphoreSlim pour eviter les refresh storms)\n- Fix: GenerateRefreshToken genere maintenant un JWT valide au lieu de\n  bytes aleatoires (ValidateRefreshToken attendait un JWT - flux casse)\n- Fix: Login.razor gere Requires2fa correctement (affiche champ code 2FA)\n- Ajout: endpoints POST /api/auth/2fa/enable et /2fa/disable\n- Ajout: Disable2faAsync dans IAuthService\n- Fix: GenerateTemporaryPassword garantit les 4 categories de charactere\n  (uppercase, lowercase, digit, non-alphanumeric)\n- Fix: TestFactory ajoute Jwt:RefreshKey manquant\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
2026-07-21 08:57:53 +00:00