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:
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user