From fc21daeb60d584930db025c5a0ffb66eb9574583 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Wed, 4 Nov 2026 21:33:49 +0100 Subject: [PATCH] fix(privacy): bound biometric and plate data inputs --- skills/vision-identity/SKILL.md | 33 +++++++++++++++++++ .../RegisterFace/RegisterFaceCommand.cs | 7 ++-- src/Heimdall.Domain/Entities/LicensePlate.cs | 13 +++++++- src/Heimdall.Domain/Entities/Person.cs | 17 +++++++++- .../Services/PersonService.cs | 4 +++ .../Controllers/PersonsController.cs | 2 ++ .../Persons/RegisterFaceHandlerTests.cs | 31 +++++++++++++++++ .../Entities/BusinessEntityTests.cs | 26 +++++++++++++++ .../Entities/PersonTests.cs | 27 +++++++++++++++ .../PersonServiceTests.cs | 25 ++++++++++++++ todo.md | 2 +- 11 files changed, 181 insertions(+), 6 deletions(-) create mode 100644 skills/vision-identity/SKILL.md diff --git a/skills/vision-identity/SKILL.md b/skills/vision-identity/SKILL.md new file mode 100644 index 0000000..1f96f68 --- /dev/null +++ b/skills/vision-identity/SKILL.md @@ -0,0 +1,33 @@ +--- +name: vision-identity +description: Extend Heimdall's person, face-embedding, vehicle, and license-plate data paths without logging biometric data or shipping unapproved model weights. +--- + +# Heimdall vision identity data + +## Current project behavior + +- `AnalysisJobPollingService` currently executes only `ObjectDetection`; do not describe the current Agent as performing face recognition or license-plate OCR. +- `KnownFace` is a manually registered vector record, not a face detector or recognition model. Inputs are limited to 4,096 finite float values, copied on construction, and the API body is capped at 256 KiB. Never log or include vector values in audit data. +- `LicensePlate` is a persisted observation record. Its text limit must match the PostgreSQL column (20 characters); confidence must be finite and in `[0,1]`. +- Face embeddings, plate text, and source images are sensitive. Preserve per-person deletion/cascade behavior, keep event camera authorization at API and application boundaries, and do not send frames or embeddings to external services. + +## Model review gate + +Before adding inference, record the exact model artifact URL/version, checksum, training-data terms, model-weight license, code/runtime license, regions/languages represented, preprocessing, hardware/runtime requirements, and an offline installation path. A repository code license alone does not establish the license of its pretrained weights. + +Review findings as of 2026-11-04: + +- [InsightFace model-zoo license notice](https://github.com/deepinsight/insightface/blob/master/python-package/docs/model_zoo.md) says its pretrained models are for non-commercial research; do not ship them for this product without separate permission. +- [FaceONNX model README](https://github.com/FaceONNX/FaceONNX.Models/blob/main/README.md) licenses the library as MIT but links models via Google Drive without specifying a separate model-weight license; treat weights as unresolved. +- [PaddleOCR license page](https://www.paddleocr.ai/v2.10.0/en/index.html) states Apache-2.0 for the project. It does not, by itself, establish rights for a particular license-plate model artifact; verify that artifact's own license and training data. +- [LdDl license-plate-recognition](https://github.com/LdDl/license_plate_recognition) declares Apache-2.0 for the repository and says its pretrained networks were trained on Russian plates. The repository does not separately establish weight rights or accuracy for Heimdall's target regions. + +Do not download or bundle model files until their artifact-level rights and target-region accuracy are reviewed. Keep accuracy claims open until validated on an appropriately licensed, representative dataset and camera conditions. + +## Acceptance + +1. Run Domain, Application, Infrastructure, and Web tests for changed layers; test EF translation/deletion behavior with PostgreSQL when persistence semantics change. +2. For a new model, test model verification/hash rejection, explicit opt-in, CPU fallback, and no outbound frame/embedding requests. Keep the exact artifact out of the repo unless its license and source are approved. +3. Exercise person and vehicle access through the authenticated API/UI, including deletion of the person and the documented retention behavior of linked event history and embeddings. +4. For behavior changes, run the disposable Compose acceptance from `skills/compose-disposable-recipe/SKILL.md`; keep generated data and credentials isolated and remove only that project. diff --git a/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs b/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs index 8565a4e..5cb881a 100644 --- a/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs +++ b/src/Heimdall.Application/Persons/Commands/RegisterFace/RegisterFaceCommand.cs @@ -19,9 +19,10 @@ public class RegisterFaceCommandHandler : IRequestHandler> Handle(RegisterFaceCommand request, CancellationToken ct) { - // Validate input before checking existence so empty embeddings return 400, not 404. - if (request.Embedding is null || request.Embedding.Length == 0) - return ServiceResult.Failure("Embedding is required and must not be empty.", 400); + // Bound user-provided biometric vectors before EF serializes them to JSONB. + if (!KnownFace.IsValidEmbedding(request.Embedding)) + return ServiceResult.Failure( + $"Embedding must contain between 1 and {KnownFace.MaxEmbeddingDimensions} finite values.", 400); var person = await _db.Persons .Include(p => p.Faces) diff --git a/src/Heimdall.Domain/Entities/LicensePlate.cs b/src/Heimdall.Domain/Entities/LicensePlate.cs index 064305a..8a79abd 100644 --- a/src/Heimdall.Domain/Entities/LicensePlate.cs +++ b/src/Heimdall.Domain/Entities/LicensePlate.cs @@ -8,6 +8,7 @@ namespace Heimdall.Domain.Entities; /// public class LicensePlate : Entity, IAuditableEntity { + public const int MaxPlateTextLength = 20; public string PlateText { get; private set; } = string.Empty; public Guid? VehicleId { get; private set; } public Guid? PersonId { get; private set; } @@ -24,6 +25,11 @@ public class LicensePlate : Entity, IAuditableEntity public LicensePlate(string plateText, Guid? vehicleId = null, Guid? personId = null, double confidence = 0) : base(Guid.NewGuid()) { + if (string.IsNullOrWhiteSpace(plateText) || plateText.Length > MaxPlateTextLength) + throw new ArgumentException($"Plate text must contain between 1 and {MaxPlateTextLength} characters.", nameof(plateText)); + if (!double.IsFinite(confidence) || confidence is < 0 or > 1) + throw new ArgumentOutOfRangeException(nameof(confidence), "Confidence must be finite and between 0 and 1."); + PlateText = plateText; VehicleId = vehicleId; PersonId = personId; @@ -32,5 +38,10 @@ public class LicensePlate : Entity, IAuditableEntity public void AssignVehicle(Guid vehicleId) => VehicleId = vehicleId; public void AssignPerson(Guid personId) => PersonId = personId; - public void UpdateConfidence(double confidence) => Confidence = confidence; + public void UpdateConfidence(double confidence) + { + if (!double.IsFinite(confidence) || confidence is < 0 or > 1) + throw new ArgumentOutOfRangeException(nameof(confidence), "Confidence must be finite and between 0 and 1."); + Confidence = confidence; + } } diff --git a/src/Heimdall.Domain/Entities/Person.cs b/src/Heimdall.Domain/Entities/Person.cs index e16640c..8bd5ee5 100644 --- a/src/Heimdall.Domain/Entities/Person.cs +++ b/src/Heimdall.Domain/Entities/Person.cs @@ -49,6 +49,8 @@ public class Person : Entity, IAuditableEntity /// public class KnownFace : Entity { + public const int MaxEmbeddingDimensions = 4096; + public Guid PersonId { get; private set; } public string? ThumbnailUrl { get; private set; } public float[] Embedding { get; private set; } = []; @@ -62,9 +64,22 @@ public class KnownFace : Entity public KnownFace(Guid personId, float[] embedding, string? thumbnailUrl = null, string? sourceEventId = null) : base(Guid.NewGuid()) { + if (personId == Guid.Empty) + throw new ArgumentException("Person ID is required.", nameof(personId)); + if (!IsValidEmbedding(embedding)) + throw new ArgumentException($"Embedding must contain between 1 and {MaxEmbeddingDimensions} finite values.", nameof(embedding)); + if (thumbnailUrl?.Length > 2000) + throw new ArgumentException("Thumbnail URL exceeds the maximum length.", nameof(thumbnailUrl)); + if (sourceEventId?.Length > 100) + throw new ArgumentException("Source event ID exceeds the maximum length.", nameof(sourceEventId)); + PersonId = personId; - Embedding = embedding; + Embedding = embedding.ToArray(); ThumbnailUrl = thumbnailUrl; SourceEventId = sourceEventId; } + + public static bool IsValidEmbedding(float[]? embedding) => + embedding is { Length: > 0 and <= MaxEmbeddingDimensions } && + embedding.All(float.IsFinite); } diff --git a/src/Heimdall.Infrastructure/Services/PersonService.cs b/src/Heimdall.Infrastructure/Services/PersonService.cs index 3800115..0196eaa 100644 --- a/src/Heimdall.Infrastructure/Services/PersonService.cs +++ b/src/Heimdall.Infrastructure/Services/PersonService.cs @@ -77,6 +77,10 @@ public sealed class PersonService : IPersonService public async Task> RegisterFaceAsync(RegisterFaceRequest request, CancellationToken ct) { + if (!KnownFace.IsValidEmbedding(request.Embedding)) + return ServiceResult.Failure( + $"Embedding must contain between 1 and {KnownFace.MaxEmbeddingDimensions} finite values.", 400); + await using var db = await _dbFactory.CreateDbContextAsync(ct); var person = await db.Persons.Include(p => p.Faces).FirstOrDefaultAsync(p => p.Id == request.PersonId, ct).ConfigureAwait(false); if (person is null) return ServiceResult.NotFound("Person not found"); diff --git a/src/Heimdall.Web/Controllers/PersonsController.cs b/src/Heimdall.Web/Controllers/PersonsController.cs index 0b26eca..833b79f 100644 --- a/src/Heimdall.Web/Controllers/PersonsController.cs +++ b/src/Heimdall.Web/Controllers/PersonsController.cs @@ -20,6 +20,7 @@ namespace Heimdall.Api.Controllers; [EnableRateLimiting("Api")] public class PersonsController : ControllerBase { + private const int MaxFaceRegistrationBytes = 256 * 1024; private readonly IMediator _mediator; public PersonsController(IMediator mediator) => _mediator = mediator; @@ -71,6 +72,7 @@ public class PersonsController : ControllerBase [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.PersonWrite)] [HttpPost("{personId:guid}/faces")] + [RequestSizeLimit(MaxFaceRegistrationBytes)] public async Task RegisterFace(Guid personId, [FromBody] RegisterFaceRequest request, CancellationToken ct) { if (!this.TryGetUserId(out var actorId)) return Unauthorized(); diff --git a/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs b/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs index 4f47557..15b3ab7 100644 --- a/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs +++ b/tests/Heimdall.Application.Tests/Handlers/Persons/RegisterFaceHandlerTests.cs @@ -46,6 +46,37 @@ public class RegisterFaceHandlerTests result.StatusCode.ShouldBe(404); } + [Theory] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + public async Task Register_face_should_reject_non_finite_embedding_before_database_lookup(float value) + { + var context = Substitute.For(); + var handler = new RegisterFaceCommandHandler(context); + + var result = await handler.Handle( + new RegisterFaceCommand(Guid.NewGuid(), [value]), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + await context.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task Register_face_should_reject_embedding_over_limit_before_database_lookup() + { + var context = Substitute.For(); + var handler = new RegisterFaceCommandHandler(context); + + var result = await handler.Handle( + new RegisterFaceCommand(Guid.NewGuid(), new float[KnownFace.MaxEmbeddingDimensions + 1]), + CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + await context.DidNotReceive().SaveChangesWithRetryAsync(Arg.Any(), Arg.Any()); + } + [Fact] public async Task Register_face_should_record_audit_log() { diff --git a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs index bdbb362..552ea4d 100644 --- a/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/BusinessEntityTests.cs @@ -112,6 +112,32 @@ public class BusinessEntityTests plate.PersonId.ShouldBe(personId); } + [Theory] + [InlineData(0.0)] + [InlineData(1.0)] + public void LicensePlate_should_accept_confidence_bounds(double confidence) + { + var plate = new LicensePlate("AB-123-CD", confidence: confidence); + + plate.Confidence.ShouldBe(confidence); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(-0.01)] + [InlineData(1.01)] + public void LicensePlate_should_reject_invalid_confidence(double confidence) + { + Should.Throw(() => new LicensePlate("AB-123-CD", confidence: confidence)); + } + + [Fact] + public void LicensePlate_should_reject_text_over_database_limit() + { + Should.Throw(() => new LicensePlate(new string('A', LicensePlate.MaxPlateTextLength + 1))); + } + // ─── CameraEvent — relations enrichies (spec 2.2) ───────────── [Fact] diff --git a/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs b/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs index d1f3368..50d7d38 100644 --- a/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs +++ b/tests/Heimdall.Domain.Tests/Entities/PersonTests.cs @@ -91,4 +91,31 @@ public class KnownFaceTests face.ThumbnailUrl.ShouldBeNull(); face.SourceEventId.ShouldBeNull(); } + + [Fact] + public void Create_knownface_should_copy_embedding_to_prevent_mutation() + { + var input = new[] { 0.1f, 0.2f }; + var face = new KnownFace(Guid.NewGuid(), input); + + input[0] = 0.9f; + + face.Embedding[0].ShouldBe(0.1f); + } + + [Theory] + [InlineData(float.NaN)] + [InlineData(float.PositiveInfinity)] + public void Create_knownface_should_reject_non_finite_values(float invalidValue) + { + Should.Throw(() => new KnownFace(Guid.NewGuid(), [invalidValue])); + } + + [Fact] + public void Create_knownface_should_reject_embedding_over_limit() + { + var embedding = new float[KnownFace.MaxEmbeddingDimensions + 1]; + + Should.Throw(() => new KnownFace(Guid.NewGuid(), embedding)); + } } diff --git a/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs b/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs index 9d6b146..49b4fcb 100644 --- a/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/PersonServiceTests.cs @@ -136,6 +136,31 @@ public class PersonServiceTests : IDisposable result.Data[2].DisplayName.ShouldBe("Charlie"); } + [Fact] + public async Task RegisterFaceAsync_RejectsOversizedEmbedding() + { + var service = new PersonService(_dbFactory, _logger); + + var result = await service.RegisterFaceAsync( + new RegisterFaceRequest(Guid.NewGuid(), new float[KnownFace.MaxEmbeddingDimensions + 1]), + CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } + + [Fact] + public async Task RegisterFaceAsync_RejectsNonFiniteEmbedding() + { + var service = new PersonService(_dbFactory, _logger); + + var result = await service.RegisterFaceAsync( + new RegisterFaceRequest(Guid.NewGuid(), [0.1f, float.NaN]), CancellationToken.None); + + result.IsSuccess.ShouldBeFalse(); + result.StatusCode.ShouldBe(400); + } + [Fact] public async Task UpdateAsync_ExistingPerson_UpdatesFields() { diff --git a/todo.md b/todo.md index 542db8c..6284530 100644 --- a/todo.md +++ b/todo.md @@ -47,7 +47,7 @@ Ce fichier remplace les rapports de `docs/audits/` et constitue le suivi courant - [ ] **PWA** PR #64 livre le manifeste, les icônes et le shell hors connexion limité à trois fichiers publics. Cette évolution ajoute l’aide d’installation progressive (`beforeinstallprompt` ou consignes navigateur), laisse le nouveau service worker en attente jusqu’à l’action explicite « Recharger », et ajoute Playwright pour le manifeste, les icônes, le contenu exact de CacheStorage et le fallback hors ligne (2/2 réussis sur PostgreSQL jetable local). `docs/pwa.md` décrit ces comportements ; `skills/pwa/SKILL.md` fixe le workflow. La recette Compose source a été interrompue avant son build/acceptance pour libérer le daemon Docker d’un autre chantier ; elle reste requise avant fusion. Restent également l’installation sur appareils Android/iOS/desktop, HTTPS/proxy, veille/changement de réseau mobile, mise à jour/rollback sur déploiement et Web Push. Ne jamais mettre les données privées en cache. - [ ] **FEAT-01** Définir codecs, spectateurs et budget latence ; implémenter live WebRTC/ICE/TURN, sessions autorisées, audio/PTZ compatibles et libération des ressources. Tester LAN et réseau externe. - [ ] **FEAT-02** Implémenter enregistrement continu/événement, segments et index temporel, upload repris, replay/range/export autorisés, quotas et purge complète. -- [ ] **FEAT-03 / UI-02** Évaluer modèles/licences visage et plaques, persister `PersonId`/`VehicleId` et lier les événements ; vérifier historique paginé sans confusion d'identité, conservation et suppression des données biométriques. +- [ ] **FEAT-03 / UI-02** Les entités Person/KnownFace/Vehicle/LicensePlate et l’historique filtrable par `PersonId` existent, mais l’Agent ne traite encore que `ObjectDetection`; aucune reconnaissance faciale ni OCR plaque n’est livré. Durcissement local du 4 novembre 2026 : vecteurs d’embedding bornés à 4 096 valeurs finies et copiés, corps d’API limité à 256 Kio, plaque bornée à 20 caractères selon le schéma et confiance finie dans [0,1]. Validation : Domain 191/191, handlers Application 6/6, PersonService SQLite 13/13 et Web 414/414. Aucun poids de modèle n’est embarqué : InsightFace réserve ses poids pré-entraînés à la recherche non commerciale; FaceONNX n’indique pas de licence distincte des poids; PaddleOCR ne clarifie pas les droits du modèle plaque précis; le dépôt LdDl est orienté plaques russes et ne précise pas séparément les droits des poids. Garder le statut ouvert jusqu’au choix d’un modèle avec droits vérifiés, tests d’exactitude sur données représentatives, inférence locale opt-in et validation des règles de conservation/suppression biométrique. Recette Compose de cette évolution en attente du créneau Docker coordonné. - [ ] **GPU #77** Les Compose CPU n'exigent plus NVIDIA et n'annoncent plus un `ORT_PROVIDER=CUDA` ignoré. Des overlays optionnels exposent NVIDIA/AMD/Intel à l'inventaire; l'inférence ONNX de l'image Agent reste CPU. Restent une image/runtime GPU, la détection du fournisseur réellement attaché à la session, et les validations GPU réel + fallback CPU. - [x] **Inventaire #86** La PR #84 livre les échantillons Central idempotents toutes les 5 min, l’horodatage distinct de réception, les agrégats API bornés (5 min/30 min) avec trous conservés, l’historique agent, la capacité par site, les graphiques 24 h/7 j, l’index et la purge en lots à 8 jours. La migration, les tests et scans d’images ont passé dans le run PR #273. Les températures GPU sont disponibles lorsque l’Agent remonte un inventaire GPU. - [ ] **mDNS #81** La PR #78 fait de l'Agent la source unique des probes HomeKit sur le LAN caméra ; Central persiste et restitue catégorie, appairage et port, et la fusion conserve l'annonce mDNS même si le scan TCP a vu l'IP d'abord. Le client partagé assemble PTR/SRV/TXT/A, décode `ci` et `sf`, et filtre les catégories 17/18. La CI #246 a passé build, tests et scans d'images ; reste une validation sur LAN avec caméra/sonnette réelles.