Commit Graph
27 Commits
Author SHA1 Message Date
arnaud.dartois 374b7f267f fix(auth): throttle API key LastUsedAt writes (#313)
Heimdall Gitea / Detect CI scope (push) Successful in 6s
Heimdall Gitea / Build and tests (push) Successful in 26m21s
Heimdall Gitea / Build and scan agent image (push) Successful in 6m32s
Heimdall Gitea / Build and scan server image (push) Successful in 8m59s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m37s
Heimdall Gitea / Build and scan NVIDIA Agent image (push) Successful in 26m10s
Heimdall Gitea / Publish signed main release (push) Canceled after 42m57s
Heimdall Gitea / CI policy (push) Failing after 2s
## Résumé
Réduit les écritures de `LastUsedAt` à une mise à jour atomique EF Core par clé et par minute, tout en transmettant l’annulation HTTP aux requêtes de validation. Ajoute une vérification PostgreSQL concurrente et le workflow projet dans `skills/api-key-last-used-throttle/SKILL.md`.

## Tickets
Refs #200, #201, #202, #203, #205. Les tickets restent ouverts jusqu’à la vérification post-déploiement GlitchTip requise par leurs critères; les événements examinés étaient en environnement Development et ne démontrent pas une régression en production.

## Vérifications observées
- `dotnet test tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyLastUsedPostgresTests` — 1 réussi.
- `dotnet test tests/Heimdall.Web.Tests/Heimdall.Web.Tests.csproj --no-restore --filter FullyQualifiedName~ApiKeyIdentityTests` — 1 réussi.
- `python3 scripts/ci/check-efcore-usage.py` — réussi.
- Compose jetable construit depuis le commit, projet isolé `heimdall-api-key-20261109100145-12450`, image `heimdall:heimdall-api-key-20261109100145-12450-acceptance`; `/healthz` et `/api/auth/bootstrap-status` HTTP 200. Après teardown, aucune ressource Compose du projet ne subsiste et le tag exact est absent. L’image PostgreSQL et les images amont sont conservées.

## Limite d’acceptation
Le Compose vérifie le démarrage source et les routes HTTP de santé/bootstrap; le changement de persistance et la concurrence sont exercés par le test d’intégration PostgreSQL.

Reviewed-on: #313
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-09 12:36:53 +01:00
arnaud.dartois 89c4c43922 fix(identity): harden user lifecycle and permissions (#136)
Heimdall Gitea / Detect CI scope (push) Successful in 7s
Heimdall Gitea / Build and tests (push) Successful in 14m48s
Heimdall Gitea / Publish versioned release (push) Skipped
Heimdall Gitea / Build and scan server image (push) Successful in 4m27s
Heimdall Gitea / Build and scan agent image (push) Successful in 15m42s
Heimdall Gitea / Publish Docker Hub latest tags (push) Successful in 1m27s
Heimdall Gitea / CI policy (push) Successful in 2s
Co-authored-by: Arnaud Dartois <admin@tordais.cc>
2026-11-04 13:33:30 +01:00
Arnaud Dartois 8195ee4ab8 feat(auth): require initial administrator setup
Heimdall Gitea / Detect CI scope (pull_request) Successful in 4s
Heimdall Gitea / Build and tests (pull_request) Successful in 20m32s
Heimdall Gitea / Publish versioned release (pull_request) Skipped
Heimdall Gitea / Build and scan server image (pull_request) Successful in 8m36s
Heimdall Gitea / Build and scan agent image (pull_request) Successful in 11m34s
Heimdall Gitea / Publish Docker Hub latest tags (pull_request) Skipped
Heimdall Gitea / CI policy (pull_request) Successful in 2s
2026-10-27 22:19:52 +01: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 13456ab4f5 fix(security): align rate limiting and password po 2026-08-20 18:14:18 +02:00
Arnaud Dartois f7e6b0cec3 feat(vehicles): API /api/vehicles - contrôleur + recherche par plaque (#150)
Résumé

Implémentation complète de l'API Vehicles (Phase 17 spec) : contrôleur REST + handlers CQRS MediatR.

Endpoints

GET /api/vehicles - Liste avec recherche par plaque (?search=XX-XXX-XX) + pagination
GET /api/vehicles/{id} - Détail avec historique events (50 derniers) + personne associée
POST /api/vehicles - Créer un véhicule
PUT /api/vehicles/{id} - Mettre à jour + associer/dissocier une personne
DELETE /api/vehicles/{id} - Supprimer un véhicule

Fichiers modifiés/créés

- src/Heimdall.Domain/Entities/Vehicle.cs - AssignPerson accepte Guid? (permet unassign)
- src/Heimdall.Infrastructure/Security/AppPermissions.cs - VehicleRead/VehicleWrite ajoutés
- src/Heimdall.Application/DTOs/VehicleDto.cs - Response, Request, EventSummary
- src/Heimdall.Application/Vehicles/ - Commands + Queries + Mapping
- src/Heimdall.Web/Controllers/VehiclesController.cs - 5 endpoints
- tests/Heimdall.Application.Tests/Handlers/Vehicles/ - 16 tests unitaires

Tests

Build 0 erreurs 0 warnings
16 nouveaux tests unitaires
Suite complète ~1149 tests 0 échec

Closes #9

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/150
2026-08-20 07:34:49 +02:00
Arnaud Dartois b0cfd50c3f feat(api-keys): API key management endpoint + admin UI (#149)
## Summary

Adds API key management functionality to Heimdall:

- **CQRS Handlers**: CreateApiKey, ListApiKeys, RevokeApiKey
- **Controller**: ApiKeysController with admin authorization (Admin.ApiKeys policy)
- **UI**: ApiKeysPage.razor admin page with create, list, and revoke
- **Auth**: Updated ApiKeyAuthenticationHandler to reject expired keys
- **Tests**: 10 unit tests for all handlers

## Changes

- `src/Heimdall.Application/ApiKeys/` — New CQRS handlers and DTOs
- `src/Heimdall.Web/Controllers/ApiKeysController.cs` — Admin API endpoints
- `src/Heimdall.Web/Components/Pages/Admin/ApiKeysPage.razor` — Admin UI
- `src/Heimdall.Infrastructure/Security/ApiKeyAuthenticationHandler.cs` — Expiry check
- `src/Heimdall.Web/Services/HeimdallApiClient.cs` — API client methods
- `tests/Heimdall.Application.Tests/Handlers/ApiKeys/` — Unit tests

## Acceptance Criteria

- [x] POST /api/api-keys → key created (plain shown once, hash in DB)
- [x] GET /api/api-keys → prefix only (never the full key)
- [x] DELETE /api/api-keys/{id} → key revoked immediately
- [x] Expired keys rejected by auth handler
- [x] Admin UI with create, list, and revoke functionality
- [x] All tests passing (10 new tests)

Closes #10

Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/149
2026-08-19 22:47:22 +02:00
Arnaud Dartois bfe9dc6e56 fix(auth): API key acceptée en Bearer sur les hubs SignalR
Le client SignalR .NET envoie le token d'accès en header Authorization:
Bearer sur le POST negotiate HTTP (les WebSockets ne peuvent pas poser
de header custom) ; le navigateur l'envoie en query string access_token.
ConfigHub étant [Authorize(AuthenticationSchemes="ApiKey")], le handler
ApiKey doit lire les deux sur /hubs. Le fallback reste scoped aux hubs :
sur les endpoints API, un Bearer non-JWT renvoie toujours 401.

Tests : +2 intégration (Bearer sur ConfigHub OK, Bearer hors /hubs 401).
2026-08-10 10:35:15 +02:00
Arnaud Dartois 1e3322cd1a 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.
2026-08-10 10:26:31 +02:00
Arnaud Dartois 64753b9ba6 fix(ci): reparation tests integration + infrastructure
- TestHelpers.CreateAdminClientAsync: bootstrap via register normal
  (first user = admin) + active les flags public-registration et
  admin-registration.enabled
- JwtService.GetUserIdFromExpiredToken: utilise GetJwtRefreshKey()
  (methode appelee avec refresh tokens, signes avec Jwt:RefreshKey)
- AuthDataServiceTests.RevokeRefreshTokenAsync_StoresToken:
  utilise SHA256 hash (nouveau comportement ExtractJti fallback)
2026-07-28 15:14:54 +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 25f51781d4 feat: add SetSettingValueAsync to IAuthDataService 2026-07-28 12:56:18 +00:00
Arnaud Dartois 45c6ce82eb perf: add ConfigureAwait(false) to all async calls in library projects
Add ConfigureAwait(false) to all await expressions in Application and
Infrastructure projects (111 files). This follows .NET best practices
for library code to avoid potential deadlocks when consumed from
synchronization contexts (legacy, unit test runners).

Also fix 4 test assertions that check SaveChangesAsync — update to
SaveChangesWithRetryAsync to match the handler changes from Fix 4.
2026-07-27 18:59:12 +00:00
Arnaud Dartois 9e58b5bf55 fix: use SaveChangesWithRetryAsync across all handlers
Replace naked SaveChangesAsync(ct) with the project's own
SaveChangesWithRetryAsync(ct: ct) in 5 locations to handle
PostgreSQL serialization conflicts and SQLite SQLITE_BUSY
transient failures:

- UpdateCameraCommand, CreateCameraCommand, DeleteCameraCommand,
  SetCameraCredentialsCommand, AuthDataService
2026-07-27 18:40:23 +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 810900cd3e fix(auth): add JWT__RefreshKey config and env var fallback in JwtService
- Add JWT__RefreshKey to .env.example with documentation
- Add JWT__RefreshKey to docker-compose.yml and docker-compose.prod.yml
- Fix JwtService to check both IConfiguration and env vars (JWT__REFRESHKEY)
  for access token key and refresh token key, matching Program.cs pattern
- Fixes 'Jwt:RefreshKey is not configured' 500 error on register/login
2026-07-25 18:02:43 +00:00
Arnaud Dartois 6978d2e9ab fix(cqrs): implement missing auth service interfaces and fix tests
- Create RolePermissionService (delegates to AppPermissions)
- Create AuthSignInService (wraps SignInManager)
- Create AuthDataService (handles settings, first-user, token revocation)
- Register all new services in Infrastructure DI
- Fix AuthDataService RevokedRefreshToken constructor usage
- All 226 tests passing
2026-07-22 20:05:59 +00:00
Arnaud Dartois 11f7fd8d20 feat(cqrs): migrate Sites, Auth, Users, Cameras to CQRS
- Sites: CreateSite, UpdateSite, DeleteSite, GenerateToken commands + handlers
- Auth: Login, Register, RefreshToken, 2FA, ChangePassword, Logout commands
- Users: CRUD, roles, sites, lock/unlock, reset-password commands + queries
- Cameras: CRUD, SetCredentials commands + queries
- Add IApplicationDbContext abstraction for Clean Architecture
- Add ICredentialProtector, IJwtService interfaces to Application layer
- 0 build errors, 0 warnings
2026-07-22 19:43:13 +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
Arnaud Dartois 940e826865 fix(identity): corrige JWT role claims, password policy, et consistency
- JWT role claims: string.Join -> ClaimTypes.Role individuels (debloque [Authorize(Roles)])\n- Password policy: RequireUppercase=true, RequireNonAlphanumeric=true\n- JWT validation params extraits en methode partagee (anti-duplication)\n- Retours 401 uniformises avec body structure\n- Champ Langue ajoute dans le dialog d'edition utilisateur\n\nBuild: 0 errors, 0 warnings\nTests: 226/226 passed
2026-07-21 08:47:24 +00:00
Arnaud Dartois a33a436c26 chore: apply auto-fixes and code improvements
- AuthService: fix public registration logic revert
- JwtService: add ILogger dependency
- SoftDeleteInterceptor removed (merged)
- XML doc comments on all services
- Error boundary + error page in Blazor
- Optimize StatsService queries
- ApiClient error handling improvements
2026-07-20 09:50:43 +00:00
Arnaud Dartois a6f37b8e9d fix(auth): add permission claims to ApiKeyAuthenticationHandler
API keys used by camera agents were missing 'permission' claims,
causing all endpoints with ApiKey + Policy to return 403 Forbidden
(e.g. POST /api/events, POST /api/events/{id}/snapshot).

Add CameraWrite, CameraRead, CameraLive, SiteRead, EventRead
permissions — matching agent operational needs (Supervisor minus
Person permissions).
2026-07-19 16:46:32 +00:00
Arnaud Dartois 076bc58e93 fix(security): implement IDataProtector-based credential encryption for CameraCredentials
- Add ICredentialProtector/DataProtectorCredentialProtector using ASP.NET Core Data Protection
- Register AddDataProtection + ICredentialProtector in Infrastructure DI
- Update CameraCredentials XML comments to reference real protector
- Add SetCredentialsAsync to CameraService with encryption
- Update ICameraService interface
2026-07-17 20:07:03 +00:00
Arnaud Dartois ca394a9eaa fix(security): remove API key query string authentication vector
Query string (?apiKey=...) leaks credentials in server logs, referrer
headers, and browser history. Only Authorization header and X-API-Key
header are now accepted for API key authentication.
2026-07-17 19:21:25 +00:00
Arnaud Dartois b217c932e8 feat(mvp): implement MVP multi-site platform
Complete MVP implementation (Étape 1) covering:
- Domain: primitives (Entity<TId>, ValueObject), 10 entities, 6 enums
- EF Core: AppDbContext + Identity, 8 EntityTypeConfigurations, audit/soft-delete interceptors, initial migration
- Application: service interfaces, DTOs, FluentValidation, ServiceResult pattern
- Security: Identity + JWT + API Key multi-auth, role-based permissions, constant-time key validation
- API: Auth/Sites/Agents controllers with explicit auth scheme policies
- Workers: Hangfire PostgreSQL setup with schema isolation, HeartbeatMonitorJob
- Agent: registration service + 30s heartbeat loop
- Docker: multi-stage Dockerfiles for central + agent, docker-compose.yml
- CI/CD: GitHub Actions pipeline with build+test and Docker build
- Tests: 13 domain tests (Site, Agent, Camera entities)

Architecture decisions per deliberation council:
- API Key via AuthenticationHandler<T> (not middleware)
- Explicit [Authorize(AuthenticationSchemes)] on all endpoints
- Event/Recording/Person/Vehicle deferred from initial migration
- Hangfire compatible with .NET 10 (v1.8.17)
2026-07-16 20:53:56 +00:00