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
This commit is contained in:
Arnaud Dartois committed 2026-08-12 10:14:40 +02:00
1 parent 2e188e4dda
commit 7d6213696f
11 files changed
+685 -1

No files matched your search

@@ -12,6 +12,7 @@ using Heimdall.Infrastructure.Persistence;
using Heimdall.Infrastructure.Security;
using Heimdall.Infrastructure.Services;
using Heimdall.Infrastructure.Services.Discovery;
using Heimdall.Infrastructure.Storage;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
@@ -43,6 +44,12 @@ public static class DependencyInjection
services.AddScoped<IApplicationDbContext>(sp => sp.GetRequiredService<AppDbContext>());
// Stockage (spec Phase 8) — provider résolu depuis les settings DB
// (storage.provider = Local | S3), factory scoped (lit la config à
// chaque résolution → changement UI sans redémarrage).
services.AddSingleton<StorageProviderFactory>();
services.AddScoped<IStorageProvider>(sp => sp.GetRequiredService<StorageProviderFactory>());
// Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles.
services.AddHealthChecks()
.AddDbContextCheck<AppDbContext>("postgres", tags: ["ready", "live"])
@@ -0,0 +1,166 @@
using Amazon.S3;
using Amazon.S3.Model;
using Heimdall.Application.Common;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Storage;
/// <summary>
/// S3-compatible storage provider (Alarik / MinIO / AWS). Configured via the
/// global settings (<c>storage.s3.endpoint</c>, <c>storage.s3.bucket</c>,
/// <c>storage.s3.accessKey</c>, <c>storage.s3.secretKey</c>, …) with env-var
/// fallback (<c>ALARIK_ENDPOINT</c> / <c>S3_ENDPOINT</c>). Uploads use a
/// staging prefix then a copy (atomic move semantics for the consumers).
/// </summary>
public sealed class AlarikStorageProvider : IStorageProvider
{
private readonly AmazonS3Client? _client;
private readonly string _bucket = string.Empty;
private readonly ILogger<AlarikStorageProvider> _logger;
public string Provider => "S3";
public bool IsConfigured => _client is not null && !string.IsNullOrEmpty(_bucket);
public AlarikStorageProvider(
string? endpoint,
string? bucket,
string? accessKey,
string? secretKey,
string? region,
ILogger<AlarikStorageProvider> logger)
{
_logger = logger;
endpoint = string.IsNullOrWhiteSpace(endpoint)
? Environment.GetEnvironmentVariable("ALARIK_ENDPOINT")
?? Environment.GetEnvironmentVariable("S3_ENDPOINT")
: endpoint;
bucket = string.IsNullOrWhiteSpace(bucket) ? "heimdall" : bucket;
accessKey ??= Environment.GetEnvironmentVariable("S3_ACCESS_KEY");
secretKey ??= Environment.GetEnvironmentVariable("S3_SECRET_KEY");
region ??= Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1";
if (string.IsNullOrWhiteSpace(endpoint))
{
_logger.LogWarning("Alarik/S3 storage not configured (missing storage.s3.endpoint)");
return;
}
var config = new AmazonS3Config
{
ServiceURL = endpoint,
ForcePathStyle = true, // Alarik/MinIO exigent le style path
AuthenticationRegion = region,
};
// Credentials vides → on tente anonyme (Alarik local par défaut).
_client = string.IsNullOrEmpty(accessKey) && string.IsNullOrEmpty(secretKey)
? new AmazonS3Client(config)
: new AmazonS3Client(accessKey, secretKey, config);
_bucket = bucket;
}
private static string StagingKey(string key) => key.StartsWith("staging/", StringComparison.Ordinal)
? key
: $"staging/{key}";
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
{
if (_client is null)
throw new InvalidOperationException("Alarik/S3 storage is not configured");
// 1) upload staging
var staging = StagingKey(key);
content.Position = 0;
await _client.PutObjectAsync(new PutObjectRequest
{
BucketName = _bucket,
Key = staging,
InputStream = content,
ContentType = contentType,
}, ct).ConfigureAwait(false);
// 2) move atomique staging → final (copy + delete staging)
await _client.CopyObjectAsync(new CopyObjectRequest
{
SourceBucket = _bucket,
SourceKey = staging,
DestinationBucket = _bucket,
DestinationKey = key,
}, ct).ConfigureAwait(false);
await _client.DeleteObjectAsync(new DeleteObjectRequest
{
BucketName = _bucket,
Key = staging,
}, ct).ConfigureAwait(false);
}
public async Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
{
if (_client is null)
return null;
try
{
var response = await _client.GetObjectAsync(new GetObjectRequest
{
BucketName = _bucket,
Key = key,
}, ct).ConfigureAwait(false);
return response.ResponseStream;
}
catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
public async Task DeleteAsync(string key, CancellationToken ct = default)
{
if (_client is null)
return;
try
{
await _client.DeleteObjectAsync(new DeleteObjectRequest
{
BucketName = _bucket,
Key = key,
}, ct).ConfigureAwait(false);
}
catch (AmazonS3Exception ex)
{
_logger.LogDebug(ex, "S3 delete failed for {Key}", key);
}
}
public async Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
{
if (_client is null || keys.Count == 0)
return;
// 1000 objets max par appel (spécification Correctif D6).
foreach (var chunk in keys.Chunk(1000))
{
var request = new DeleteObjectsRequest { BucketName = _bucket };
foreach (var key in chunk)
request.AddKey(key);
await _client.DeleteObjectsAsync(request, ct).ConfigureAwait(false);
}
}
public async Task<bool> HealthCheckAsync(CancellationToken ct = default)
{
if (_client is null)
return false;
try
{
await _client.ListBucketsAsync(ct).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Alarik/S3 health check failed");
return false;
}
}
}
@@ -0,0 +1,108 @@
using Heimdall.Application.Common;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Storage;
/// <summary>
/// Local filesystem storage provider. Files are written under the configured
/// root (default <c>storage.local.path</c> → env <c>STORAGE__LOCAL__PATH</c>,
/// fallback <c>./data/storage</c>). Uploads are atomic: write to a staging
/// temp file, then move to the final path.
/// </summary>
public sealed class LocalStorageProvider : IStorageProvider
{
private readonly string _root;
private readonly ILogger<LocalStorageProvider> _logger;
public string Provider => "Local";
public bool IsConfigured => !string.IsNullOrEmpty(_root);
public LocalStorageProvider(string? rootPath, ILogger<LocalStorageProvider> logger)
{
_root = Path.GetFullPath(string.IsNullOrWhiteSpace(rootPath)
? "./data/storage"
: rootPath);
_logger = logger;
}
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)));
// Sécurité : ne jamais sortir de la racine via "..".
if (!path.StartsWith(_root, StringComparison.Ordinal))
throw new InvalidOperationException($"Storage key escapes root: {key}");
return path;
}
public async Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
{
var finalPath = ResolvePath(key);
var dir = Path.GetDirectoryName(finalPath);
if (!string.IsNullOrEmpty(dir))
Directory.CreateDirectory(dir);
// Écriture atomique : fichier temporaire + move.
var staging = finalPath + $".tmp-{Guid.NewGuid():N}";
try
{
await using (var fs = new FileStream(staging, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, useAsync: true))
{
await content.CopyToAsync(fs, ct).ConfigureAwait(false);
}
File.Move(staging, finalPath, overwrite: true);
}
catch
{
try { File.Delete(staging); } catch { /* best effort */ }
throw;
}
}
public Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
{
var path = ResolvePath(key);
if (!File.Exists(path))
return Task.FromResult<Stream?>(null);
return Task.FromResult<Stream?>(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 64 * 1024, useAsync: true));
}
public Task DeleteAsync(string key, CancellationToken ct = default)
{
var path = ResolvePath(key);
try
{
if (File.Exists(path))
File.Delete(path);
}
catch (Exception ex)
{
_logger.LogDebug(ex, "Local storage delete failed for {Key}", key);
}
return Task.CompletedTask;
}
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
{
foreach (var key in keys)
DeleteAsync(key, ct);
return Task.CompletedTask;
}
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
{
try
{
Directory.CreateDirectory(_root);
return Task.FromResult(true);
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Local storage health check failed");
return Task.FromResult(false);
}
}
}
@@ -0,0 +1,87 @@
using Heimdall.Application.Common;
using Heimdall.Application.Common.Persistence;
using Heimdall.Infrastructure.Storage;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Heimdall.Infrastructure.Storage;
/// <summary>
/// Resolves the active storage provider from the global settings
/// (<c>storage.provider</c> = Local | S3) with env fallback
/// (<c>STORAGE__PROVIDER</c>). Reads the DB each resolution so a change made
/// in the UI is picked up without restart (broadcast reload on top).
/// </summary>
public sealed class StorageProviderFactory : IStorageProvider
{
private readonly IServiceProvider _services;
private readonly ILogger<StorageProviderFactory> _logger;
public StorageProviderFactory(IServiceProvider services, ILogger<StorageProviderFactory> logger)
{
_services = services;
_logger = logger;
}
public string Provider => Resolve().Provider;
public bool IsConfigured => Resolve().IsConfigured;
public Task UploadAsync(string key, Stream content, string contentType, CancellationToken ct = default)
=> Resolve().UploadAsync(key, content, contentType, ct);
public Task<Stream?> DownloadAsync(string key, CancellationToken ct = default)
=> Resolve().DownloadAsync(key, ct);
public Task DeleteAsync(string key, CancellationToken ct = default)
=> Resolve().DeleteAsync(key, ct);
public Task DeleteBatchAsync(IReadOnlyCollection<string> keys, CancellationToken ct = default)
=> Resolve().DeleteBatchAsync(keys, ct);
public Task<bool> HealthCheckAsync(CancellationToken ct = default)
=> Resolve().HealthCheckAsync(ct);
private IStorageProvider Resolve()
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
var provider = GetSetting(db, "storage.provider")
?? Environment.GetEnvironmentVariable("STORAGE__PROVIDER")
?? "Local";
if (provider.Equals("S3", StringComparison.OrdinalIgnoreCase))
{
var s3 = new AlarikStorageProvider(
GetSetting(db, "storage.s3.endpoint"),
GetSetting(db, "storage.s3.bucket"),
GetSetting(db, "storage.s3.accessKey"),
GetSetting(db, "storage.s3.secretKey"),
GetSetting(db, "storage.s3.region"),
scope.ServiceProvider.GetRequiredService<ILogger<AlarikStorageProvider>>());
if (s3.IsConfigured)
return s3;
_logger.LogWarning("storage.provider=S3 mais S3 non configuré — fallback Local");
}
return new LocalStorageProvider(
GetSetting(db, "storage.local.path"),
scope.ServiceProvider.GetRequiredService<ILogger<LocalStorageProvider>>());
}
private static string? GetSetting(IApplicationDbContext db, string key)
{
try
{
var setting = db.AppSettings
.AsNoTracking()
.FirstOrDefault(s => s.Key == key);
return setting?.Value;
}
catch
{
return null;
}
}
}
@@ -46,6 +46,9 @@
</MudGrid>
</MudPaper>
@* ── Section Stockage dédiée (config visuelle) ───────────────────── *@
<StorageSettingsSection />
@if (_loading)
{
<MudPaper Elevation="1" Class="pa-4" Style="border-radius: var(--hmd-radius-md);">
@@ -0,0 +1,162 @@
@namespace Heimdall.Web.Components.Settings
@inject HeimdallApiClient Api
@inject ISnackbar Snackbar
<MudPaper Elevation="1" Class="pa-4 mb-4" Style="border-radius: var(--hmd-radius-lg);">
<div class="d-flex align-center mb-3">
<MudText Typo="Typo.h6" Class="flex-grow-1">
<i class="fas fa-database mr-2"></i> Stockage
</MudText>
<MudChip T="string" Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary">@_provider</MudChip>
</div>
<MudText Typo="Typo.body2" Color="Color.Secondary" Class="mb-3">
Choisissez le mode de stockage des snapshots et enregistrements : disque local (« Fichier ») ou objet S3 (Alarik/MinIO).
</MudText>
<MudGrid>
<MudItem xs="12" md="6">
<MudSelect T="string" Label="Provider" Variant="Variant.Outlined" Value="@_provider" ValueChanged="async v => await SaveProviderAsync(v)" Immediate="true">
<MudSelectItem T="string" Value="@("Local")">Fichier (disque local)</MudSelectItem>
<MudSelectItem T="string" Value="@("S3")">S3 (Alarik / MinIO)</MudSelectItem>
</MudSelect>
</MudItem>
@if (_provider == "Local")
{
<MudItem xs="12">
<MudTextField T="string" Label="Chemin racine" Variant="Variant.Outlined"
Value="@GetValue("storage.local.path")"
ValueChanged="OnLocalPathChanged"
HelperText="Dossier local où sont écrits snapshots et enregistrements." />
</MudItem>
}
else
{
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Endpoint S3" Variant="Variant.Outlined"
Value="@GetValue("storage.s3.endpoint")"
ValueChanged="OnEndpointChanged"
HelperText="Ex : http://alarik:9000" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Bucket" Variant="Variant.Outlined"
Value="@GetValue("storage.s3.bucket")"
ValueChanged="OnBucketChanged" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Clé d'accès" Variant="Variant.Outlined"
Value="@GetValue("storage.s3.accessKey")"
ValueChanged="OnAccessKeyChanged" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Clé secrète" Variant="Variant.Outlined"
Value="@GetValue("storage.s3.secretKey")" Type="InputType.Password"
ValueChanged="OnSecretKeyChanged" />
</MudItem>
<MudItem xs="12" md="6">
<MudTextField T="string" Label="Région" Variant="Variant.Outlined"
Value="@GetValue("storage.s3.region")"
ValueChanged="OnRegionChanged" />
</MudItem>
}
</MudGrid>
<div class="d-flex align-center mt-3">
<MudButton Variant="Variant.Outlined" Color="Color.Info" StartIcon="@Icons.Material.Filled.VerifiedUser"
OnClick="@TestAsync" Disabled="@_testing">
@(_testing ? "Test en cours…" : "Tester la connexion")
</MudButton>
@if (_testResult is not null)
{
<MudChip T="string" Size="Size.Small" Class="ml-3"
Color="@(_testResult.Healthy == true ? Color.Success : Color.Error)" Variant="Variant.Outlined">
@(_testResult.Healthy == true ? "Opérationnel" : _testResult.Configured == false ? "Non configuré" : "Injoignable")
</MudChip>
}
</div>
</MudPaper>
@code {
private List<AppSettingItem> _settings = [];
private string _provider = "Local";
private bool _testing;
private StorageTestResult? _testResult;
protected override async Task OnInitializedAsync()
{
try
{
_settings = await Api.GetSettingsAsync();
}
catch
{
// API indisponible (ex : test) — on reste sur les défauts.
_settings = [];
}
_provider = GetValue("storage.provider") ?? "Local";
}
private string? GetValue(string key)
=> _settings.FirstOrDefault(s => s.Key == key)?.Value;
private async Task SaveProviderAsync(string provider)
{
_provider = provider;
await SaveValueAsync("storage.provider", provider);
}
private Task OnLocalPathChanged(string v) => SaveValueAsync("storage.local.path", v);
private Task OnEndpointChanged(string v) => SaveValueAsync("storage.s3.endpoint", v);
private Task OnBucketChanged(string v) => SaveValueAsync("storage.s3.bucket", v);
private Task OnAccessKeyChanged(string v) => SaveValueAsync("storage.s3.accessKey", v);
private Task OnSecretKeyChanged(string v) => SaveValueAsync("storage.s3.secretKey", v);
private Task OnRegionChanged(string v) => SaveValueAsync("storage.s3.region", v);
private async Task SaveValueAsync(string key, string? value)
{
value ??= string.Empty;
var existing = _settings.FirstOrDefault(s => s.Key == key);
try
{
if (existing is null)
{
await Api.CreateSettingAsync(new CreateAppSettingRequest(
Key: key, Value: value, Category: "storage",
Description: key.StartsWith("storage.s3.secretKey", StringComparison.Ordinal)
? "Clé secrète S3" : key,
ValueType: "string", AllowedValues: null, AgentScoped: true));
}
else
{
await Api.UpdateSettingAsync(key, new UpdateAppSettingRequest(
Value: value, Description: existing.Description ?? key,
Category: "storage", ValueType: "string", AllowedValues: null, AgentScoped: null));
}
// Les records sont immuables : recharger plutôt que muter.
_settings = await Api.GetSettingsAsync();
Snackbar.Add($"Paramètre {key} mis à jour", Severity.Success);
}
catch (Exception ex)
{
Snackbar.Add($"Échec de la mise à jour : {ex.Message}", Severity.Error);
}
}
private async Task TestAsync()
{
_testing = true;
try
{
_testResult = await Api.TestStorageAsync();
}
catch (Exception ex)
{
Snackbar.Add($"Test impossible : {ex.Message}", Severity.Error);
}
finally
{
_testing = false;
}
}
}
@@ -15,3 +15,4 @@
@using Heimdall.Web.Components.Pages
@using Heimdall.Web.Services
@using Heimdall.Web.Components.Shared
@using Heimdall.Web.Components.Settings
@@ -228,6 +228,27 @@ public class SettingsController : ControllerBase
return NoContent();
}
/// <summary>
/// Test the active storage provider reachability (Admin only).
/// Returns the resolved provider name and health status.
/// </summary>
[Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)]
[HttpPost("storage/test")]
[ProducesResponseType(typeof(object), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
public async Task<IActionResult> TestStorage(
[FromServices] IStorageProvider storageProvider,
CancellationToken ct)
{
var ok = await storageProvider.HealthCheckAsync(ct);
return Ok(new
{
provider = storageProvider.Provider,
configured = storageProvider.IsConfigured,
healthy = ok,
});
}
/// <summary>
/// Broadcast a "ConfigReload" signal to all connected agents so they
/// re-fetch their full configuration (Admin only).
+33
View File
@@ -206,6 +206,39 @@ public partial class Program {
}
await groupDb.SaveChangesWithRetryAsync();
// Seed des paramètres de stockage (idempotent) — source de vérité DB,
// valeur initiale depuis env pour migration douce (ticket #78/#80).
var storageDefaults = new Dictionary<string, string?>
{
["storage.provider"] = Environment.GetEnvironmentVariable("STORAGE__PROVIDER") ?? "Local",
["storage.local.path"] = Environment.GetEnvironmentVariable("STORAGE__LOCAL__PATH") ?? "./data/storage",
["storage.s3.endpoint"] = Environment.GetEnvironmentVariable("ALARIK_ENDPOINT")
?? Environment.GetEnvironmentVariable("S3_ENDPOINT"),
["storage.s3.bucket"] = Environment.GetEnvironmentVariable("S3_BUCKET") ?? "heimdall",
["storage.s3.accessKey"] = Environment.GetEnvironmentVariable("S3_ACCESS_KEY"),
["storage.s3.secretKey"] = Environment.GetEnvironmentVariable("S3_SECRET_KEY"),
["storage.s3.region"] = Environment.GetEnvironmentVariable("S3_REGION") ?? "us-east-1",
};
foreach (var (key, value) in storageDefaults)
{
if (await groupDb.AppSettings.AnyAsync(s => s.Key == key))
continue;
groupDb.AppSettings.Add(new Heimdall.Domain.Entities.AppSetting(
key, value ?? string.Empty, "storage",
key switch
{
"storage.provider" => "Provider de stockage actif (Local | S3)",
"storage.local.path" => "Chemin racine du stockage local",
"storage.s3.endpoint" => "Endpoint S3 (Alarik/MinIO)",
"storage.s3.bucket" => "Bucket S3",
"storage.s3.accessKey" => "Clé d'accès S3",
"storage.s3.secretKey" => "Clé secrète S3",
"storage.s3.region" => "Région S3",
_ => key
}));
}
await groupDb.SaveChangesWithRetryAsync();
// Seed demo admin + demo site when explicitly enabled (dev & E2E hosts)
if (configuration.GetValue<bool>("Seed:DemoOnStartup", false))
{
+19 -1
View File
@@ -494,6 +494,16 @@ public class HeimdallApiClient
return await client.DeleteAsync($"api/settings/{key}");
}
/// <summary>Test the active storage provider reachability (POST /api/settings/storage/test).</summary>
public async Task<StorageTestResult?> TestStorageAsync()
{
var client = CreateClient();
var response = await client.PostAsync("api/settings/storage/test", null);
if (!response.IsSuccessStatusCode)
return null;
return await response.Content.ReadFromJsonAsync<StorageTestResult>();
}
public async Task<HttpResponseMessage> ReloadAllConfigAsync()
{
var client = CreateClient();
@@ -688,7 +698,15 @@ public class AgentLogItem
public string? Source { get; set; }
}
// ─── Settings DTOs ────────────────────────────────────────────────
// ─── Storage DTOs ──────────────────────────────────────────────────
public record StorageTestResult(
[property: JsonPropertyName("provider")] string Provider,
[property: JsonPropertyName("configured")] bool Configured,
[property: JsonPropertyName("healthy")] bool? Healthy
);
// ─── Settings DTOs ─────────────────────────────────────────────────
public record AppSettingItem(
[property: JsonPropertyName("id")] Guid Id,
@@ -0,0 +1,78 @@
using System.Text;
using Heimdall.Infrastructure.Storage;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
namespace Heimdall.Infrastructure.Tests;
public class LocalStorageProviderTests : IDisposable
{
private readonly string _root;
private readonly LocalStorageProvider _provider;
public LocalStorageProviderTests()
{
_root = Path.Combine(Path.GetTempPath(), $"heimdall-storage-{Guid.NewGuid():N}");
_provider = new LocalStorageProvider(_root, NullLogger<LocalStorageProvider>.Instance);
}
public void Dispose()
{
try { Directory.Delete(_root, recursive: true); } catch { /* best effort */ }
GC.SuppressFinalize(this);
}
[Fact]
public async Task UploadDownload_RoundTrips()
{
var bytes = Encoding.UTF8.GetBytes("hello storage");
await _provider.UploadAsync("snapshots/site1/cam1/2026-01-01/evt1.jpg",
new MemoryStream(bytes), "image/jpeg");
using var stream = await _provider.DownloadAsync("snapshots/site1/cam1/2026-01-01/evt1.jpg");
stream.ShouldNotBeNull();
using var reader = new StreamReader(stream);
(await reader.ReadToEndAsync()).ShouldBe("hello storage");
}
[Fact]
public async Task Download_Missing_ReturnsNull()
{
var stream = await _provider.DownloadAsync("snapshots/nope.jpg");
stream.ShouldBeNull();
}
[Fact]
public async Task Delete_RemovesObject()
{
await _provider.UploadAsync("x/y.jpg", new MemoryStream(Encoding.UTF8.GetBytes("data")), "image/jpeg");
await _provider.DeleteAsync("x/y.jpg");
(await _provider.DownloadAsync("x/y.jpg")).ShouldBeNull();
}
[Fact]
public async Task DeleteBatch_RemovesAll()
{
await _provider.UploadAsync("a/1.jpg", new MemoryStream(Encoding.UTF8.GetBytes("a")), "image/jpeg");
await _provider.UploadAsync("a/2.jpg", new MemoryStream(Encoding.UTF8.GetBytes("b")), "image/jpeg");
await _provider.DeleteBatchAsync(["a/1.jpg", "a/2.jpg"]);
(await _provider.DownloadAsync("a/1.jpg")).ShouldBeNull();
(await _provider.DownloadAsync("a/2.jpg")).ShouldBeNull();
}
[Fact]
public void PathTraversal_Throws()
{
Should.Throw<InvalidOperationException>(() =>
{
var t = _provider.UploadAsync("../../etc/passwd", new MemoryStream(), "text/plain");
t.GetAwaiter().GetResult();
});
}
[Fact]
public async Task HealthCheck_True()
{
(await _provider.HealthCheckAsync()).ShouldBeTrue();
}
}