Commit Graph
9 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 1cd4e2b4b5 fix(security): enforce resource isolation across API and hubs 2026-10-20 07:16:44 +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 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 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 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