M6: REST API + API-key auth + OpenAPI

- Minimal API under /api/v1 (SDD §9): POST /readings (idempotent HA push), GET /meters,
  /energy-types, /consumption, /cost, /dashboard/summary, POST /events (records + recomputes),
  GET+POST /tariffs, GET /sources/status.
- IngestionService.IngestByMeterAsync for direct REST push (batch-safe upsert via Local cache).
- ApiKeyFilter: X-Api-Key enforced against configured keys (open only when none set).
- ReverseProxyTrust middleware: adopt X-Forwarded-User/Remote-User behind Authelia/Traefik.
- Swagger/OpenAPI (Swashbuckle) at /swagger.
- Tests: push rejected without key (401), accepted + persisted with key; meters + swagger live.

94 tests green (56 Core + 38 integration).

Claude-Session: https://claude.ai/code/session_01WujdMtMJPbxDpDnMeK22rr
This commit is contained in:
2026-07-13 12:16:49 +02:00
parent d5419729e5
commit 9abc2937c2
9 changed files with 325 additions and 13 deletions
+43
View File
@@ -0,0 +1,43 @@
using System.Security.Claims;
using MeterVault.Infrastructure.Options;
using Microsoft.Extensions.Options;
namespace MeterVault.App.Api;
/// <summary>
/// When enabled (SDD §10), trusts an authenticating reverse proxy (Authelia/Traefik) by adopting
/// the user it asserts via <c>X-Forwarded-User</c> / <c>Remote-User</c>. This lets the homelab run
/// MeterVault behind existing SSO without built-in accounts. Only enable when the app is not
/// directly reachable — any client could otherwise spoof the header.
/// </summary>
public static class ReverseProxyTrust
{
private static readonly string[] UserHeaders = ["X-Forwarded-User", "Remote-User", "X-Forwarded-Preferred-Username"];
public static IApplicationBuilder UseReverseProxyTrust(this WebApplication app)
{
var options = app.Services.GetRequiredService<IOptions<MeterVaultOptions>>().Value;
if (!options.ReverseProxyTrust)
{
return app;
}
app.Use(async (context, next) =>
{
foreach (var header in UserHeaders)
{
var user = context.Request.Headers[header].ToString();
if (!string.IsNullOrWhiteSpace(user))
{
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, user)], "ReverseProxy");
context.User = new ClaimsPrincipal(identity);
break;
}
}
await next(context).ConfigureAwait(false);
});
return app;
}
}