diff --git a/src/Heimdall.Infrastructure/DependencyInjection.cs b/src/Heimdall.Infrastructure/DependencyInjection.cs index 494f5ea..50d5f7e 100644 --- a/src/Heimdall.Infrastructure/DependencyInjection.cs +++ b/src/Heimdall.Infrastructure/DependencyInjection.cs @@ -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(sp => sp.GetRequiredService()); + // 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(); + services.AddScoped(sp => sp.GetRequiredService()); + // Health checks (spec 13.2) — PostgreSQL + dépendances optionnelles. services.AddHealthChecks() .AddDbContextCheck("postgres", tags: ["ready", "live"]) diff --git a/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs new file mode 100644 index 0000000..6922e3b --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/AlarikStorageProvider.cs @@ -0,0 +1,166 @@ +using Amazon.S3; +using Amazon.S3.Model; +using Heimdall.Application.Common; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Storage; + +/// +/// S3-compatible storage provider (Alarik / MinIO / AWS). Configured via the +/// global settings (storage.s3.endpoint, storage.s3.bucket, +/// storage.s3.accessKey, storage.s3.secretKey, …) with env-var +/// fallback (ALARIK_ENDPOINT / S3_ENDPOINT). Uploads use a +/// staging prefix then a copy (atomic move semantics for the consumers). +/// +public sealed class AlarikStorageProvider : IStorageProvider +{ + private readonly AmazonS3Client? _client; + private readonly string _bucket = string.Empty; + private readonly ILogger _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 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 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 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 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; + } + } +} diff --git a/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs new file mode 100644 index 0000000..05e0414 --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/LocalStorageProvider.cs @@ -0,0 +1,108 @@ +using Heimdall.Application.Common; +using Microsoft.Extensions.Logging; + +namespace Heimdall.Infrastructure.Storage; + +/// +/// Local filesystem storage provider. Files are written under the configured +/// root (default storage.local.path → env STORAGE__LOCAL__PATH, +/// fallback ./data/storage). Uploads are atomic: write to a staging +/// temp file, then move to the final path. +/// +public sealed class LocalStorageProvider : IStorageProvider +{ + private readonly string _root; + private readonly ILogger _logger; + + public string Provider => "Local"; + public bool IsConfigured => !string.IsNullOrEmpty(_root); + + public LocalStorageProvider(string? rootPath, ILogger 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 DownloadAsync(string key, CancellationToken ct = default) + { + var path = ResolvePath(key); + if (!File.Exists(path)) + return Task.FromResult(null); + return Task.FromResult(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 keys, CancellationToken ct = default) + { + foreach (var key in keys) + DeleteAsync(key, ct); + return Task.CompletedTask; + } + + public Task 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); + } + } +} diff --git a/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs new file mode 100644 index 0000000..021f66f --- /dev/null +++ b/src/Heimdall.Infrastructure/Storage/StorageProviderFactory.cs @@ -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; + +/// +/// Resolves the active storage provider from the global settings +/// (storage.provider = Local | S3) with env fallback +/// (STORAGE__PROVIDER). Reads the DB each resolution so a change made +/// in the UI is picked up without restart (broadcast reload on top). +/// +public sealed class StorageProviderFactory : IStorageProvider +{ + private readonly IServiceProvider _services; + private readonly ILogger _logger; + + public StorageProviderFactory(IServiceProvider services, ILogger 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 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 keys, CancellationToken ct = default) + => Resolve().DeleteBatchAsync(keys, ct); + + public Task HealthCheckAsync(CancellationToken ct = default) + => Resolve().HealthCheckAsync(ct); + + private IStorageProvider Resolve() + { + using var scope = _services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + 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>()); + 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>()); + } + + 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; + } + } +} diff --git a/src/Heimdall.Web/Components/Pages/SettingsPage.razor b/src/Heimdall.Web/Components/Pages/SettingsPage.razor index 8ad6849..2dfc59a 100644 --- a/src/Heimdall.Web/Components/Pages/SettingsPage.razor +++ b/src/Heimdall.Web/Components/Pages/SettingsPage.razor @@ -46,6 +46,9 @@ +@* ── Section Stockage dédiée (config visuelle) ───────────────────── *@ + + @if (_loading) { diff --git a/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor b/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor new file mode 100644 index 0000000..e15ec40 --- /dev/null +++ b/src/Heimdall.Web/Components/Settings/StorageSettingsSection.razor @@ -0,0 +1,162 @@ +@namespace Heimdall.Web.Components.Settings +@inject HeimdallApiClient Api +@inject ISnackbar Snackbar + + +
+ + Stockage + + @_provider +
+ + + Choisissez le mode de stockage des snapshots et enregistrements : disque local (« Fichier ») ou objet S3 (Alarik/MinIO). + + + + + + Fichier (disque local) + S3 (Alarik / MinIO) + + + + @if (_provider == "Local") + { + + + + } + else + { + + + + + + + + + + + + + + + + } + + +
+ + @(_testing ? "Test en cours…" : "Tester la connexion") + + @if (_testResult is not null) + { + + @(_testResult.Healthy == true ? "Opérationnel" : _testResult.Configured == false ? "Non configuré" : "Injoignable") + + } +
+
+ +@code { + private List _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; + } + } +} diff --git a/src/Heimdall.Web/Components/_Imports.razor b/src/Heimdall.Web/Components/_Imports.razor index 4a8ff64..521047f 100644 --- a/src/Heimdall.Web/Components/_Imports.razor +++ b/src/Heimdall.Web/Components/_Imports.razor @@ -15,3 +15,4 @@ @using Heimdall.Web.Components.Pages @using Heimdall.Web.Services @using Heimdall.Web.Components.Shared +@using Heimdall.Web.Components.Settings diff --git a/src/Heimdall.Web/Controllers/SettingsController.cs b/src/Heimdall.Web/Controllers/SettingsController.cs index 065354f..c4010ff 100644 --- a/src/Heimdall.Web/Controllers/SettingsController.cs +++ b/src/Heimdall.Web/Controllers/SettingsController.cs @@ -228,6 +228,27 @@ public class SettingsController : ControllerBase return NoContent(); } + /// + /// Test the active storage provider reachability (Admin only). + /// Returns the resolved provider name and health status. + /// + [Authorize(AuthenticationSchemes = "JwtBearer,Cookies", Policy = AppPermissions.AdminManage)] + [HttpPost("storage/test")] + [ProducesResponseType(typeof(object), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)] + public async Task TestStorage( + [FromServices] IStorageProvider storageProvider, + CancellationToken ct) + { + var ok = await storageProvider.HealthCheckAsync(ct); + return Ok(new + { + provider = storageProvider.Provider, + configured = storageProvider.IsConfigured, + healthy = ok, + }); + } + /// /// Broadcast a "ConfigReload" signal to all connected agents so they /// re-fetch their full configuration (Admin only). diff --git a/src/Heimdall.Web/Program.cs b/src/Heimdall.Web/Program.cs index d9a7ded..1364963 100644 --- a/src/Heimdall.Web/Program.cs +++ b/src/Heimdall.Web/Program.cs @@ -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 + { + ["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("Seed:DemoOnStartup", false)) { diff --git a/src/Heimdall.Web/Services/HeimdallApiClient.cs b/src/Heimdall.Web/Services/HeimdallApiClient.cs index da4405e..355a4bd 100644 --- a/src/Heimdall.Web/Services/HeimdallApiClient.cs +++ b/src/Heimdall.Web/Services/HeimdallApiClient.cs @@ -494,6 +494,16 @@ public class HeimdallApiClient return await client.DeleteAsync($"api/settings/{key}"); } + /// Test the active storage provider reachability (POST /api/settings/storage/test). + public async Task TestStorageAsync() + { + var client = CreateClient(); + var response = await client.PostAsync("api/settings/storage/test", null); + if (!response.IsSuccessStatusCode) + return null; + return await response.Content.ReadFromJsonAsync(); + } + public async Task 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, diff --git a/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs new file mode 100644 index 0000000..5341e08 --- /dev/null +++ b/tests/Heimdall.Infrastructure.Tests/LocalStorageProviderTests.cs @@ -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.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(() => + { + var t = _provider.UploadAsync("../../etc/passwd", new MemoryStream(), "text/plain"); + t.GetAwaiter().GetResult(); + }); + } + + [Fact] + public async Task HealthCheck_True() + { + (await _provider.HealthCheckAsync()).ShouldBeTrue(); + } +}