From cef3434c3c8c760ff461566cb001c4f14f5c6bb4 Mon Sep 17 00:00:00 2001 From: Arnaud Dartois Date: Tue, 20 Oct 2026 02:27:03 +0200 Subject: [PATCH] fix(ops): confine local storage and repair maintenance jobs (Refs #1) --- .env.example | 13 +- docker/docker-compose.backup.yml | 2 +- docker/docker-compose.prod.yml | 6 +- docker/docker-compose.yml | 26 +-- docs/audits/2026-10-20-ops-tests.json | 167 ++++++++++++++++++ docs/audits/2026-10-20-preuves-ops.md | 33 ++++ scripts/ci/validate-compose.sh | 12 ++ .../BackgroundJobs/JobSetup.cs | 2 +- .../Jobs/AnalysisJobDispatcherJob.cs | 30 +--- .../Jobs/PartitionManagerJob.cs | 59 ++++--- .../Storage/LocalStorageProvider.cs | 34 +++- .../Heimdall.Infrastructure.Tests.csproj | 3 +- .../LocalStorageProviderTests.cs | 61 +++++++ .../MaintenanceScheduleTests.cs | 75 ++++++++ .../PartitionManagerJobTests.cs | 90 ++++++++++ 15 files changed, 536 insertions(+), 77 deletions(-) create mode 100644 docs/audits/2026-10-20-ops-tests.json create mode 100644 docs/audits/2026-10-20-preuves-ops.md create mode 100644 scripts/ci/validate-compose.sh create mode 100644 tests/Heimdall.Infrastructure.Tests/MaintenanceScheduleTests.cs create mode 100644 tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs diff --git a/.env.example b/.env.example index 4f5f68b..ca433e2 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,10 @@ # PRODUCTION: Use Docker secrets (docker/secrets/) for sensitive values. # See docker-compose.prod.yml header for instructions. +# Development example only: replace all credentials before exposure. # Database +POSTGRES_PASSWORD=heimdall +RABBITMQ_PASSWORD=heimdall-development-only DATABASE_URL=Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall # JWT (change in production!) @@ -41,11 +44,11 @@ Sentry__TracesSampleRate=0.05 Sentry__Release=heimdall@1.0.0 # Agent (set per agent instance) -Agent__CentralUrl=http://heimdall:8080 -Agent__SiteToken=replace-with-actual-token -Agent__AgentName=agent-01 -Agent__HeartbeatIntervalSeconds=30 -Agent__RegistrationMaxRetries=5 +HEIMDALL_CENTRAL_URL=http://localhost:5000 +HEIMDALL_SITE_TOKEN=replace-with-actual-token +HEIMDALL_AGENT_NAME=agent-01 +HEIMDALL_HEARTBEAT_INTERVAL=30 +HEIMDALL_REGISTRATION_RETRIES=5 # Email (SMTP) — notifications EMAIL__SMTP_HOST=smtp.example.com diff --git a/docker/docker-compose.backup.yml b/docker/docker-compose.backup.yml index 2b46899..5caae7d 100644 --- a/docker/docker-compose.backup.yml +++ b/docker/docker-compose.backup.yml @@ -21,7 +21,7 @@ services: POSTGRES_PORT: "5432" POSTGRES_DB: ${POSTGRES_DB:-heimdall} POSTGRES_USER: ${POSTGRES_USER:-heimdall} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-heimdall} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} # S3/Alarik config (optional — backup works local-only without these) ALARIK_ENDPOINT: ${ALARIK_ENDPOINT:-} ALARIK_ACCESS_KEY: ${ALARIK_ACCESS_KEY:-${S3_ACCESS_KEY:-}} diff --git a/docker/docker-compose.prod.yml b/docker/docker-compose.prod.yml index 3ef9e9e..2b47666 100644 --- a/docker/docker-compose.prod.yml +++ b/docker/docker-compose.prod.yml @@ -98,8 +98,8 @@ services: # Database (password from secret, rest from env) DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} # JWT (keys from secrets) - JWT__Issuer: ${JWT__Issuer:-heimdall} - JWT__Audience: ${JWT__Audience:-heimdall-api} + JWT__Issuer: ${JWT__ISSUER:-heimdall} + JWT__Audience: ${JWT__AUDIENCE:-heimdall-api} # ASP.NET ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 @@ -176,7 +176,7 @@ services: RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost} RABBITMQ__PORT: ${RABBITMQ_PORT:-5672} RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} - RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required} # ONNX Runtime GPU provider selection ORT_PROVIDER: ${AGENT_ORT_PROVIDER:-CUDA} ORT_CUDA_DEVICE_ID: ${AGENT_CUDA_DEVICE_ID:-0} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 7d41cab..3a97d37 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -20,7 +20,7 @@ services: environment: POSTGRES_DB: ${POSTGRES_DB:-heimdall} POSTGRES_USER: ${POSTGRES_USER:-heimdall} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-heimdall} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} ports: - "${POSTGRES_PORT:-5432}:5432" volumes: @@ -45,8 +45,8 @@ services: API_BASE_URL: ${ALARIK_API_BASE_URL:-http://localhost:9000} CONSOLE_BASE_URL: ${ALARIK_CONSOLE_BASE_URL:-http://localhost:9001} ADMIN_USERNAME: ${ALARIK_ADMIN_USERNAME:-heimdall} - ADMIN_PASSWORD: ${ALARIK_ADMIN_PASSWORD:-heimdall123} - JWT: ${ALARIK_JWT:-ChangeMeAtLeast32BytesLongKeyInProd!} + ADMIN_PASSWORD: ${ALARIK_ADMIN_PASSWORD:?ALARIK_ADMIN_PASSWORD is required} + JWT: ${ALARIK_JWT:?ALARIK_JWT is required} ALLOW_ACCOUNT_CREATION: false volumes: - alarik_storage:/app/Storage @@ -79,14 +79,14 @@ services: RABBITMQ__HOST: rabbitmq RABBITMQ__PORT: "5672" RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} - RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required} # Database - DATABASE_URL: ${DATABASE_URL:-Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall} + DATABASE_URL: ${DATABASE_URL:?DATABASE_URL is required} # JWT - JWT__Key: ${JWT__Key} - JWT__RefreshKey: ${JWT__RefreshKey} - JWT__Issuer: ${JWT__Issuer:-heimdall} - JWT__Audience: ${JWT__Audience:-heimdall-api} + JWT__Key: ${JWT__KEY:?JWT__KEY is required} + JWT__RefreshKey: ${JWT__REFRESHKEY:?JWT__REFRESHKEY is required} + JWT__Issuer: ${JWT__ISSUER:-heimdall} + JWT__Audience: ${JWT__AUDIENCE:-heimdall-api} # ASP.NET ASPNETCORE_ENVIRONMENT: ${ASPNETCORE_ENVIRONMENT:-Production} ASPNETCORE_URLS: http://+:8080 @@ -148,7 +148,7 @@ services: # Host network: Docker DNS names don't resolve → reach the Central via # a host-reachable URL (same machine: http://localhost:5010) Agent__CentralUrl: ${HEIMDALL_CENTRAL_URL:-http://localhost:5010} - Agent__SiteToken: ${HEIMDALL_SITE_TOKEN} + Agent__SiteToken: ${HEIMDALL_SITE_TOKEN:?HEIMDALL_SITE_TOKEN is required} Agent__AgentName: ${HEIMDALL_AGENT_NAME:-agent-01} Agent__HeartbeatIntervalSeconds: ${HEIMDALL_HEARTBEAT_INTERVAL:-30} Agent__StateDirectory: /var/lib/heimdall @@ -157,7 +157,7 @@ services: RABBITMQ__HOST: ${RABBITMQ_HOST:-localhost} RABBITMQ__PORT: ${RABBITMQ_PORT:-5672} RABBITMQ__USER: ${RABBITMQ_USER:-heimdall} - RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:-heimdall123} + RABBITMQ__PASSWORD: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required} # ONNX Runtime GPU provider selection ORT_PROVIDER: ${AGENT_ORT_PROVIDER:-CUDA} ORT_CUDA_DEVICE_ID: ${AGENT_CUDA_DEVICE_ID:-0} @@ -203,7 +203,7 @@ services: hostname: rabbitmq environment: RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-heimdall} - RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:-heimdall123} + RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?RABBITMQ_PASSWORD is required} ports: - "${RABBITMQ_PORT:-5672}:5672" - "${RABBITMQ_MGMT_PORT:-15672}:15672" @@ -226,7 +226,7 @@ services: image: coturn/coturn:4.6 command: > -n --use-auth-secret - --static-auth-secret=${COTURN_SECRET:-ChangeMeAtLeast32BytesLongCoturnSecret!} + --static-auth-secret=${COTURN_SECRET:?COTURN_SECRET is required} --realm=${COTURN_REALM:-heimdall.local} --fingerprint --no-tlsv1 diff --git a/docs/audits/2026-10-20-ops-tests.json b/docs/audits/2026-10-20-ops-tests.json new file mode 100644 index 0000000..9858b90 --- /dev/null +++ b/docs/audits/2026-10-20-ops-tests.json @@ -0,0 +1,167 @@ +{ + "suite": "ops targeted", + "sdk": "10.0.112", + "postgres": "17-alpine via Testcontainers", + "passed": 39, + "failed": 0, + "skipped": 0, + "trx_sha256": "53a74f1711738bb65383f71ebe3df69ceba4d523b6cad321ec4ae11d70681171", + "tests": [ + { + "name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_NoAgents_JobsStayPending", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_PendingJobs_DispatchesToAgents", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteAsync_SecurityJobDispatchedBeforeBackground", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteTimeoutSweepAsync_HealthyJobs_Ignored", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.AnalysisJobDispatcherJobTests.ExecuteTimeoutSweepAsync_TimedOutJob_RetriesOrDeadLetters", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DeleteBatch_RemovesAll", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.Delete_RemovesObject", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DirectoryLinks_IncludingDangling_AreRejected(dangling: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.DirectoryLinks_IncludingDangling_AreRejected(dangling: True)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.Download_Missing_ReturnsNull", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.HealthCheck_True", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \".\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"../sibling/file\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"/absolute/file\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"C:/absolute/file\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a/..\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a/./b\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a//b\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.InvalidKeys_AreRejectedByEveryOperation(key: \"a\\\\b\")", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.LeafAndRootLinks_AreRejected", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.PathTraversal_Throws", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.SiblingWithRootPrefix_IsRejected", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.LocalStorageProviderTests.UploadDownload_RoundTrips", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.MaintenanceScheduleTests.Dispatch_DoesNotRunASecondTimeoutSweep", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.MaintenanceScheduleTests.TimeoutSweep_HasMinuteOccurrencesAndDistributedLock", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionManagerJobTests.Execute_DropsOnlyExpiredAttachedPartitions_AndClosesReaderBeforeDdl", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"Camera_events_2025_01\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_+025_01\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_0000_01\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_0001_12\", valid: True)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025-01\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_00\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01\", valid: True)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01_extra\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_1\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_13\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.PartitionNameTests.NamesAreStrict(name: \"camera_events_2025_01\", valid: False)", + "outcome": "Passed" + }, + { + "name": "Heimdall.Infrastructure.Tests.SweepLockTests.PostgreSqlLock_ExcludesAnotherWorker_AndIsReleased", + "outcome": "Passed" + } + ] +} diff --git a/docs/audits/2026-10-20-preuves-ops.md b/docs/audits/2026-10-20-preuves-ops.md new file mode 100644 index 0000000..abb4714 --- /dev/null +++ b/docs/audits/2026-10-20-preuves-ops.md @@ -0,0 +1,33 @@ +# Correctifs d’exploitation indépendants — PR A + +Périmètre : SEC-08 (confinement local), OPS-03, OPS-04 et OPS-06 du rapport et du plan du 20 octobre 2026. Ce document ne clôture ni l’audit complet ni le lot 7. + +## Changements + +- Stockage local : seules des clés relatives à segments non vides, séparés par `/`, sont acceptées. Racine, `.`/`..`, chemins absolus Unix/Windows, antislashs et préfixes de lecteurs sont refusés. La vérification porte sur la relation au répertoire racine, sans comparaison de simple préfixe. Les liens symboliques/reparse points sont refusés sur la racine, ses ancêtres, les dossiers et les feuilles, y compris les liens pendants. Les uploads gardent staging et renommage atomique. +- Partitions : format exact `camera_events_YYYY_MM`, chiffres ASCII et date valide ; seuls les enfants du parent `public.camera_events` sont candidats. Le reader est libéré avant le DDL. La connexion reste la propriété du DbContext. Une table indépendante portant un nom conforme est préservée. +- Timeouts : cron cinq champs `* * * * *`, suppression du sweep redondant du dispatcher et verrou distribué Hangfire PostgreSQL sur le sweep dédié. Les appels directs hors Hangfire ne passent pas par son filtre ; les appelants de production sont les jobs configurés. Le verrou évite le chevauchement des sweeps, pas les autres transitions métier du scheduler (lots 3/6). +- Compose : interpolation JWT en majuscules alignée sur `.env.example`, noms `HEIMDALL_*` alignés pour l’agent, secrets indispensables sans fallback dans la référence de développement. La production conserve ses fichiers secrets. Le mot de passe RabbitMQ de l’agent doit correspondre au fichier secret du broker. `DATABASE_URL` et `POSTGRES_PASSWORD` doivent désigner les mêmes credentials. Les exemples sont exclusivement destinés au développement ; ils ne démontrent pas un déploiement sécurisé. + +## Vérification reproductible + +```sh +bash scripts/ci/validate-compose.sh +dotnet test tests/Heimdall.Infrastructure.Tests -m:2 \ + --filter 'FullyQualifiedName~LocalStorageProviderTests|FullyQualifiedName~Partition|FullyQualifiedName~MaintenanceScheduleTests|FullyQualifiedName~SweepLockTests|FullyQualifiedName~AnalysisJobDispatcherJobTests' \ + --logger 'trx;LogFileName=ops-targeted.trx' +``` + +Le script Compose valide silencieusement la référence, la production et l’overlay backup ; il exige aussi l’échec de chaque variable indispensable vide. Il ne démarre aucun service et ne prouve pas la disponibilité des fichiers secrets en production. + +Résultats locaux : **39 réussis, 0 échoué, 0 ignoré** (.NET SDK 10.0.112, PostgreSQL 17 Testcontainers, durée tests 52 s). Les contrôles Compose positifs et négatifs passent. Le détail compact est dans `2026-10-20-ops-tests.json`. Une première exécution avait révélé une interaction de fixtures (tables Hangfire empêchant EnsureCreated) ; le test de verrou utilise désormais sa propre base jetable, comme le test de partitions. Aucun test distant de cette PR n’est revendiqué : la branche principale ne contient aucun workflow. + +## Conditions et travaux restants + +Le stockage et ses ancêtres doivent être modifiables uniquement par le compte de service et les administrateurs de confiance. Les contrôles managés de liens ne constituent pas une protection contre un processus local hostile ayant le droit de remplacer des répertoires entre vérification et ouverture (TOCTOU). Aucune nouvelle API média n’est exposée par cette PR. + +La purge des objets, les tombstones/outbox et la résolution des providers historiques restent dépendants du contrat d’objets du lot 4. OPS-01/OPS-02, staging/orphelins, restauration mesurée, RPO/RTO et campagne de métriques ne sont pas déclarés corrigés. Les lots auth, accès et pipeline/scoring sont hors périmètre. + +## Inventaire distant (lecture seule, sans valeurs secrètes) + +API Gitea consultée avec les credentials existants : version `28.1.0`, Actions activé, branche principale `main`, trois runners d’instance en ligne (`runner-odin`, `runner-murin`, `runner-hugin`, label `ubuntu-latest`). Aucun runner propre au dépôt, secret/variable Actions de dépôt ni protection de branche. Les listes de packages conteneurs du propriétaire, releases et artefacts du dépôt sont vides à la consultation. L’API ne donne pas la configuration hôte effective des runners ni leur accès Docker. Aucun secret n’a été imprimé. Aucun déploiement ni tag/release de test déclenché. diff --git a/scripts/ci/validate-compose.sh b/scripts/ci/validate-compose.sh new file mode 100644 index 0000000..472fbf3 --- /dev/null +++ b/scripts/ci/validate-compose.sh @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +set -euo pipefail +# Never print the rendered configuration: it contains credentials. +docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet +docker compose --env-file .env.example -f docker/docker-compose.prod.yml config --quiet +docker compose --env-file .env.example -f docker/docker-compose.yml -f docker/docker-compose.backup.yml config --quiet +for required in JWT__KEY JWT__REFRESHKEY HEIMDALL_SITE_TOKEN DATABASE_URL POSTGRES_PASSWORD RABBITMQ_PASSWORD ALARIK_ADMIN_PASSWORD ALARIK_JWT COTURN_SECRET; do + if env "$required=" docker compose --env-file .env.example -f docker/docker-compose.yml config --quiet >/dev/null 2>&1; then + echo "Compose accepted missing required variable: $required" >&2 + exit 1 + fi +done diff --git a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs index a346b8b..eea66fc 100644 --- a/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs +++ b/src/Heimdall.Infrastructure/BackgroundJobs/JobSetup.cs @@ -63,7 +63,7 @@ public static class JobSetup manager.AddOrUpdate( "analysis-job-timeout-sweep", job => job.ExecuteTimeoutSweepAsync(CancellationToken.None), - "*/1 * * * * *"); // Every 60 seconds + "* * * * *"); // Every minute manager.AddOrUpdate( "partition-manager", diff --git a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs index 261863d..d1c2ad1 100644 --- a/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/AnalysisJobDispatcherJob.cs @@ -1,3 +1,4 @@ +using Hangfire; using Heimdall.Application.Services; using Heimdall.Domain.Enums; using Heimdall.Infrastructure.Data; @@ -36,7 +37,7 @@ public sealed class AnalysisJobDispatcherJob } /// - /// Main dispatcher tick: process pending jobs and clean up timed-out jobs. + /// Main dispatcher tick: process pending jobs. Timeouts belong to the minute sweep. /// Called every 30 seconds by Hangfire recurring job. /// public async Task ExecuteAsync(CancellationToken ct = default) @@ -46,35 +47,14 @@ public sealed class AnalysisJobDispatcherJob .ProcessPendingJobsAsync(MaxDispatchPerTick, ct) .ConfigureAwait(false); - // 2. Clean up timed-out jobs - var timedOutJobs = await _schedulerService - .GetTimedOutJobsAsync(ct) - .ConfigureAwait(false); - - foreach (var job in timedOutJobs) - { - _logger.LogWarning( - "Analysis job {JobId} timed out (status={Status}, dispatched={DispatchedAt})", - job.Id, job.Status, job.DispatchedAt); - - await _schedulerService.FailJobAsync( - job.Id, - $"Execution exceeded timeout of {job.MaxExecutionTime.TotalSeconds}s", - ct) - .ConfigureAwait(false); - } - - if (dispatched > 0 || timedOutJobs.Count > 0) - { - _logger.LogInformation( - "Analysis dispatcher: {Dispatched} dispatched, {TimedOut} timed out", - dispatched, timedOutJobs.Count); - } + if (dispatched > 0) + _logger.LogInformation("Analysis dispatcher: {Dispatched} dispatched", dispatched); } /// /// Timeout sweep only — runs less frequently (every 60s) to catch stuck jobs. /// + [DisableConcurrentExecution(timeoutInSeconds: 60)] public async Task ExecuteTimeoutSweepAsync(CancellationToken ct = default) { var timedOutJobs = await _schedulerService diff --git a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs index 84927f5..40f6634 100644 --- a/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs +++ b/src/Heimdall.Infrastructure/Jobs/PartitionManagerJob.cs @@ -31,6 +31,25 @@ public class PartitionManagerJob _logger = logger; } + public static bool TryParsePartitionDate(string name, out DateTime date) + { + date = default; + const string prefix = "camera_events_"; + if (name.Length != 21 || !name.StartsWith(prefix, StringComparison.Ordinal) || + name[18] != '_' || !IsDigits(name.AsSpan(14, 4)) || + !IsDigits(name.AsSpan(19, 2))) + return false; + return DateTime.TryParseExact(name.AsSpan(14), "yyyy_MM", InvariantCulture, + DateTimeStyles.None, out date); + } + + private static bool IsDigits(ReadOnlySpan value) + { + foreach (var ch in value) + if (ch is < '0' or > '9') return false; + return true; + } + public async Task ExecuteAsync(CancellationToken ct) { await using var db = await _dbFactory.CreateDbContextAsync(ct); @@ -46,8 +65,8 @@ public class PartitionManagerJob var partitionName = $"camera_events_{from.ToString("yyyy_MM", InvariantCulture)}"; var sql = $@" - CREATE TABLE IF NOT EXISTS ""{partitionName}"" - PARTITION OF ""camera_events"" + CREATE TABLE IF NOT EXISTS public.""{partitionName}"" + PARTITION OF public.""camera_events"" FOR VALUES FROM ('{from.ToString("yyyy-MM-dd", InvariantCulture)}') TO ('{to.ToString("yyyy-MM-dd", InvariantCulture)}'); "; @@ -69,39 +88,35 @@ public class PartitionManagerJob // ── Drop old partitions beyond retention ──────────────────────────── var cutoff = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddMonths(-RetentionMonths); - // List existing partitions via pg_tables + // Only consider actual partitions of the intended public parent table. const string listSql = @" - SELECT tablename FROM pg_tables - WHERE schemaname = 'public' - AND tablename LIKE 'camera_events_%' - ORDER BY tablename; + SELECT child.relname + FROM pg_inherits inheritance + JOIN pg_class parent ON parent.oid = inheritance.inhparent + JOIN pg_namespace parent_schema ON parent_schema.oid = parent.relnamespace + JOIN pg_class child ON child.oid = inheritance.inhrelid + JOIN pg_namespace child_schema ON child_schema.oid = child.relnamespace + WHERE parent_schema.nspname = 'public' AND parent.relname = 'camera_events' + AND child_schema.nspname = 'public' + ORDER BY child.relname; "; try { - await using var connection = db.Database.GetDbConnection(); + var connection = db.Database.GetDbConnection(); await connection.OpenAsync(ct).ConfigureAwait(false); await using var cmd = connection.CreateCommand(); cmd.CommandText = listSql; - await using var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false); var partitionsToDrop = new List(); - - while (await reader.ReadAsync(ct).ConfigureAwait(false)) + await using (var reader = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false)) { - var tableName = reader.GetString(0); - // Parse year_month from camera_events_YYYY_MM - if (tableName.Length >= 22 && - tableName.StartsWith("camera_events_", StringComparison.Ordinal) && - int.TryParse(tableName.AsSpan(15, 4), out var year) && - int.TryParse(tableName.AsSpan(20, 2), out var month)) + while (await reader.ReadAsync(ct).ConfigureAwait(false)) { - var partitionDate = new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Utc); - if (partitionDate < cutoff) - { + var tableName = reader.GetString(0); + if (TryParsePartitionDate(tableName, out var partitionDate) && partitionDate < cutoff) partitionsToDrop.Add(tableName); - } } } @@ -112,7 +127,7 @@ public class PartitionManagerJob // Partition name is validated above (alphanumeric + underscore only) #pragma warning disable EF1002 // DDL — table name cannot be parameterized await db.Database.ExecuteSqlRawAsync( - $"DROP TABLE IF EXISTS \"{partition}\";", ct).ConfigureAwait(false); + $"DROP TABLE IF EXISTS public.\"{partition}\";", ct).ConfigureAwait(false); #pragma warning restore EF1002 dropped++; _logger.LogInformation("Dropped old partition {Partition}", partition); diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs index 05e0414..45a24c3 100644 --- a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -27,17 +27,34 @@ public sealed class LocalStorageProvider : IStorageProvider private string ResolvePath(string key) { - // Clé "snapshots/{site}/{camera}/{date}/{id}.jpg" → chemin sous la racine. - var safe = key.Replace('\\', '/').TrimStart('/'); - var path = Path.GetFullPath(Path.Combine(_root, safe.Replace('/', Path.DirectorySeparatorChar))); + // Object keys are portable relative paths, never filesystem paths. + if (string.IsNullOrWhiteSpace(key) || key.Contains('\\') || key.Contains(':') || + Path.IsPathRooted(key) || key.Split('/').Any(part => part is "" or "." or "..")) + throw new InvalidOperationException("Invalid local storage key."); - // Sécurité : ne jamais sortir de la racine via "..". - if (!path.StartsWith(_root, StringComparison.Ordinal)) - throw new InvalidOperationException($"Storage key escapes root: {key}"); + var path = Path.GetFullPath(Path.Combine(_root, key)); + var relative = Path.GetRelativePath(_root, path); + if (relative == "." || Path.IsPathRooted(relative) || relative == ".." || + relative.StartsWith(".." + Path.DirectorySeparatorChar, StringComparison.Ordinal)) + throw new InvalidOperationException("Storage key escapes root."); + EnsureNoLinks(path); return path; } + // Reject links in the configured root, its ancestors, directories and leaf, + // including dangling links. The storage tree must be writable only by this service. + private static void EnsureNoLinks(string path) + { + for (string? current = path; current is not null; current = Path.GetDirectoryName(current)) + { + if (new FileInfo(current).LinkTarget is not null || + (File.Exists(current) || Directory.Exists(current)) && + (File.GetAttributes(current) & FileAttributes.ReparsePoint) != 0) + throw new InvalidOperationException("Symbolic links are forbidden in local storage paths."); + } + } + public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default) { var finalPath = ResolvePath(key); @@ -45,6 +62,8 @@ public sealed class LocalStorageProvider : IStorageProvider if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + EnsureNoLinks(finalPath); + // Écriture atomique : fichier temporaire + move. var staging = finalPath + $".tmp-{Guid.NewGuid():N}"; try @@ -53,6 +72,7 @@ public sealed class LocalStorageProvider : IStorageProvider { await content.CopyToAsync(fs, ct).ConfigureAwait(false); } + EnsureNoLinks(finalPath); File.Move(staging, finalPath, overwrite: true); } catch @@ -96,7 +116,9 @@ public sealed class LocalStorageProvider : IStorageProvider { try { + EnsureNoLinks(_root); Directory.CreateDirectory(_root); + EnsureNoLinks(_root); return Task.FromResult(true); } catch (Exception ex) diff --git a/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj b/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj index 7419346..4e10829 100644 --- a/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj +++ b/tests/Heimdall.Infrastructure.Tests/Heimdall.Infrastructure.Tests.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -8,6 +8,7 @@ + diff --git a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs index 5341e08..f31ba6c 100644 --- a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs +++ b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs @@ -70,6 +70,67 @@ public class LocalStorageProviderTests : IDisposable }); } + [Theory] + [InlineData("")] + [InlineData(".")] + [InlineData("a/..")] + [InlineData("../sibling/file")] + [InlineData("/absolute/file")] + [InlineData("C:/absolute/file")] + [InlineData("a\\b")] + [InlineData("a//b")] + [InlineData("a/./b")] + public async Task InvalidKeys_AreRejectedByEveryOperation(string key) + { + await Should.ThrowAsync(() => _provider.UploadAsync(key, new MemoryStream(), "text/plain")); + await Should.ThrowAsync(() => _provider.DownloadAsync(key)); + await Should.ThrowAsync(() => _provider.DeleteAsync(key)); + } + + [Fact] + public async Task SiblingWithRootPrefix_IsRejected() + { + var key = "../" + Path.GetFileName(_root) + "-sibling/object"; + await Should.ThrowAsync(() => _provider.UploadAsync(key, new MemoryStream(), "text/plain")); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task DirectoryLinks_IncludingDangling_AreRejected(bool dangling) + { + Directory.CreateDirectory(_root); + var outside = _root + "-outside"; + if (!dangling) Directory.CreateDirectory(outside); + try + { + Directory.CreateSymbolicLink(Path.Combine(_root, "link"), outside); + await Should.ThrowAsync(() => _provider.UploadAsync("link/file", new MemoryStream(), "text/plain")); + await Should.ThrowAsync(() => _provider.DownloadAsync("link/file")); + await Should.ThrowAsync(() => _provider.DeleteAsync("link/file")); + } + finally { if (Directory.Exists(outside)) Directory.Delete(outside, true); } + } + + [Fact] + public async Task LeafAndRootLinks_AreRejected() + { + Directory.CreateDirectory(_root); + File.CreateSymbolicLink(Path.Combine(_root, "leaf"), Path.Combine(_root, "missing")); + await Should.ThrowAsync(() => _provider.DownloadAsync("leaf")); + await Should.ThrowAsync(() => _provider.UploadAsync("leaf", new MemoryStream(), "text/plain")); + await Should.ThrowAsync(() => _provider.DeleteAsync("leaf")); + var linkRoot = _root + "-link"; + Directory.CreateSymbolicLink(linkRoot, _root); + try + { + var linked = new LocalStorageProvider(linkRoot, NullLogger.Instance); + await Should.ThrowAsync(() => linked.UploadAsync("file", new MemoryStream(), "text/plain")); + (await linked.HealthCheckAsync()).ShouldBeFalse(); + } + finally { Directory.Delete(linkRoot); } + } + [Fact] public async Task HealthCheck_True() { diff --git a/tests/Heimdall.Infrastructure.Tests/MaintenanceScheduleTests.cs b/tests/Heimdall.Infrastructure.Tests/MaintenanceScheduleTests.cs new file mode 100644 index 0000000..15ae926 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/MaintenanceScheduleTests.cs @@ -0,0 +1,75 @@ +using Hangfire; +using Hangfire.Common; +using Heimdall.Application.Services; +using Heimdall.Infrastructure.BackgroundJobs; +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Jobs; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public class MaintenanceScheduleTests +{ + [Fact] + public void TimeoutSweep_HasMinuteOccurrencesAndDistributedLock() + { + var manager = Substitute.For(); + JobSetup.ConfigureRecurringJobs(manager); + var call = manager.ReceivedCalls().Single(c => c.GetArguments()[0]?.ToString() == "analysis-job-timeout-sweep"); + var cron = call.GetArguments().OfType().Last(); + cron.ShouldBe("* * * * *"); + var schedule = Cronos.CronExpression.Parse(cron); + var start = new DateTime(2026, 10, 20, 0, 0, 0, DateTimeKind.Utc); + schedule.GetOccurrences(start, start.AddMinutes(3)).Count().ShouldBe(3); + var method = typeof(AnalysisJobDispatcherJob).GetMethod(nameof(AnalysisJobDispatcherJob.ExecuteTimeoutSweepAsync))!; + method.GetCustomAttributes(typeof(DisableConcurrentExecutionAttribute), true).ShouldHaveSingleItem(); + } + + [Fact] + public async Task Dispatch_DoesNotRunASecondTimeoutSweep() + { + var scheduler = Substitute.For(); + var dispatcher = new AnalysisJobDispatcherJob(Substitute.For>(), scheduler, + NullLogger.Instance); + await dispatcher.ExecuteAsync(); + await scheduler.DidNotReceive().GetTimedOutJobsAsync(Arg.Any()); + } +} + +[Collection("PostgresInfra")] +public class SweepLockTests(Heimdall.TestCommon.PostgreSqlContainerFixture postgres) +{ + [Fact] + public async Task PostgreSqlLock_ExcludesAnotherWorker_AndIsReleased() + { + var database = "sweep_test_" + Guid.NewGuid().ToString("N"); + await using var admin = new Npgsql.NpgsqlConnection(postgres.ConnectionString); + await admin.OpenAsync(); + await using (var create = new Npgsql.NpgsqlCommand($"CREATE DATABASE {database}", admin)) + await create.ExecuteNonQueryAsync(); + var builder = new Npgsql.NpgsqlConnectionStringBuilder(postgres.ConnectionString) + { Database = database, Pooling = false }; + try + { + var storage = new Hangfire.PostgreSql.PostgreSqlStorage(builder.ConnectionString, null, + new Hangfire.PostgreSql.PostgreSqlStorageOptions()); + using var firstWorker = storage.GetConnection(); + using var secondWorker = storage.GetConnection(); + const string resource = "Heimdall.Infrastructure.Jobs.AnalysisJobDispatcherJob.ExecuteTimeoutSweepAsync"; + using (firstWorker.AcquireDistributedLock(resource, TimeSpan.FromSeconds(2))) + { + Should.Throw(() => + secondWorker.AcquireDistributedLock(resource, TimeSpan.Zero)); + } + using var next = secondWorker.AcquireDistributedLock(resource, TimeSpan.FromSeconds(2)); + } + finally + { + await using var drop = new Npgsql.NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", admin); + await drop.ExecuteNonQueryAsync(); + } + } +} diff --git a/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs new file mode 100644 index 0000000..1edb3f4 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/PartitionManagerJobTests.cs @@ -0,0 +1,90 @@ +using Heimdall.Infrastructure.Data; +using Heimdall.Infrastructure.Data.Interceptors; +using Heimdall.Infrastructure.Jobs; +using Heimdall.TestCommon; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Shouldly; + +namespace Heimdall.Infrastructure.Tests; + +public class PartitionNameTests +{ + [Theory] + [InlineData("camera_events_2025_01", true)] + [InlineData("camera_events_0001_12", true)] + [InlineData("camera_events_2025_00", false)] + [InlineData("camera_events_2025_13", false)] + [InlineData("camera_events_0000_01", false)] + [InlineData("camera_events_2025_1", false)] + [InlineData("camera_events_2025_01_extra", false)] + [InlineData("camera_events_2025-01", false)] + [InlineData("camera_events_+025_01", false)] + [InlineData("camera_events_2025_01", false)] + [InlineData("Camera_events_2025_01", false)] + public void NamesAreStrict(string name, bool valid) + => PartitionManagerJob.TryParsePartitionDate(name, out _).ShouldBe(valid); +} + +[Collection("PostgresInfra")] +public class PartitionManagerJobTests(PostgreSqlContainerFixture postgres) +{ + [Fact] + public async Task Execute_DropsOnlyExpiredAttachedPartitions_AndClosesReaderBeforeDdl() + { + // Use an isolated database: the application fixtures create a nonpartitioned table. + var database = "partition_test_" + Guid.NewGuid().ToString("N"); + await using var admin = new NpgsqlConnection(postgres.ConnectionString); + await admin.OpenAsync(); + await using (var create = new NpgsqlCommand($"CREATE DATABASE {database}", admin)) + await create.ExecuteNonQueryAsync(); + var builder = new NpgsqlConnectionStringBuilder(postgres.ConnectionString) { Database = database, Pooling = false }; + try + { + var opts = new DbContextOptionsBuilder().UseNpgsql(builder.ConnectionString).Options; + var factory = new Factory(opts); + await using var db = factory.CreateDbContext(); + var now = DateTime.UtcNow; + var month = new DateTime(now.Year, now.Month, 1, 0, 0, 0, DateTimeKind.Utc); + var old = month.AddMonths(-13); + var boundary = month.AddMonths(-12); + var expiredName = $"camera_events_{old:yyyy_MM}"; + var boundaryName = $"camera_events_{boundary:yyyy_MM}"; + var unrelatedName = $"camera_events_{old.AddMonths(-2):yyyy_MM}"; +#pragma warning disable EF1002 // Test DDL identifiers generated exclusively from dates. + await db.Database.ExecuteSqlRawAsync($""" + CREATE TABLE camera_events (occurred_at timestamptz NOT NULL) PARTITION BY RANGE (occurred_at); + CREATE TABLE "{expiredName}" PARTITION OF camera_events FOR VALUES FROM ('{old:yyyy-MM-dd}') TO ('{old.AddMonths(1):yyyy-MM-dd}'); + CREATE TABLE "{boundaryName}" PARTITION OF camera_events FOR VALUES FROM ('{boundary:yyyy-MM-dd}') TO ('{boundary.AddMonths(1):yyyy-MM-dd}'); + CREATE TABLE camera_events_bad PARTITION OF camera_events DEFAULT; + CREATE TABLE "{unrelatedName}" (id int); + """); +#pragma warning restore EF1002 + await new PartitionManagerJob(factory, NullLogger.Instance).ExecuteAsync(CancellationToken.None); + // A second execution must be harmless. + await new PartitionManagerJob(factory, NullLogger.Instance).ExecuteAsync(CancellationToken.None); + await using var conn = new NpgsqlConnection(builder.ConnectionString); + await conn.OpenAsync(); + await using var cmd = new NpgsqlCommand("SELECT tablename FROM pg_tables WHERE schemaname = 'public'", conn); + await using var reader = await cmd.ExecuteReaderAsync(); + var tables = new List(); + while (await reader.ReadAsync()) tables.Add(reader.GetString(0)); + tables.ShouldNotContain(expiredName); + tables.ShouldContain(boundaryName); + tables.ShouldContain(unrelatedName); + tables.ShouldContain("camera_events_bad"); + for (var i = 0; i <= 2; i++) tables.ShouldContain($"camera_events_{month.AddMonths(i):yyyy_MM}"); + } + finally + { + await using var drop = new NpgsqlCommand($"DROP DATABASE {database} WITH (FORCE)", admin); + await drop.ExecuteNonQueryAsync(); + } + } + + private sealed class Factory(DbContextOptions options) : IDbContextFactory + { + public AppDbContext CreateDbContext() => new(options, new AuditInterceptor()); + } +} -- 2.54.1