Add authenticated Gateway system updates with rollback

This commit is contained in:
jhartworks committed 2026-11-24 13:46:40 +01:00
1 parent 198b1d7b78
commit 4e35a3a557
9 files changed
+423 -1

No files matched your search

@@ -3,6 +3,8 @@ namespace Gateway.Api.Options;
public sealed class GatewayOptions
{
public string DataDirectory { get; init; } = "data";
public string? UpdateSocketPath { get; init; }
public string? UpdateStatusPath { get; init; }
public BacnetBootstrapOptions Bacnet { get; init; } = new();
+42
View File
@@ -1,5 +1,6 @@
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Gateway.Api.Contracts;
using Gateway.Api.Domain;
using Gateway.Api.Options;
@@ -21,6 +22,20 @@ builder.Services.ConfigureHttpJsonOptions(options => options.SerializerOptions.C
builder.Services.AddSingleton<GatewayDatabase>();
builder.Services.AddSingleton<PasswordService>();
builder.Services.AddSingleton<SessionService>();
builder.Services.AddSingleton<SystemUpdateService>();
builder.Services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.AddPolicy("system-update-password", context =>
{
var user = context.RequestServices.GetRequiredService<SessionService>().GetUser(context.Request.Headers.Authorization);
return RateLimitPartition.GetFixedWindowLimiter(user?.User.Id.ToString() ?? "anonymous", _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 5,
Window = TimeSpan.FromMinutes(1)
});
});
});
builder.Services.AddSingleton<MappingValidator>();
builder.Services.AddSingleton<WriteJournal>();
builder.Services.AddSingleton<SecretProtector>();
@@ -81,6 +96,33 @@ app.Use(async (context, next) =>
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseRateLimiter();
app.MapGet("/api/system/update", (HttpRequest request, HttpResponse response, SessionService sessions, SystemUpdateService updates) =>
{
var user = sessions.GetUser(request.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
response.Headers.CacheControl = "no-store";
return Results.Ok(updates.GetStatus());
});
app.MapPost("/api/system/update", async (SystemUpdateRequest request, HttpRequest http, SessionService sessions,
GatewayStore store, SystemUpdateService updates, CancellationToken cancellationToken) =>
{
var user = sessions.GetUser(http.Headers.Authorization)?.User;
if (user is null) return Results.Unauthorized();
if (user.Role != "admin") return Results.StatusCode(StatusCodes.Status403Forbidden);
if (!updates.Enabled) return Results.Conflict(new { error = "Der lokale Systemupdate-Dienst ist nicht eingerichtet." });
if (request.Password is not { Length: > 0 and <= 512 } || store.Authenticate(user.Username, request.Password)?.User.Id != user.Id)
return Results.Json(new { error = "Das Administrator-Passwort stimmt nicht." }, statusCode: StatusCodes.Status403Forbidden);
if (!await updates.StartAsync(cancellationToken))
return Results.Conflict(new { error = "Ein Update läuft bereits oder der Systemupdate-Dienst ist nicht erreichbar." });
return Results.Accepted("/api/system/update", new SystemUpdateStatus("queued", "Der Systemdienst hat das Update angenommen."));
}).RequireRateLimiting("system-update-password");
app.MapGet("/api/docs", (HttpRequest request, SessionService sessions, GatewayDocumentation docs) =>
sessions.IsValid(request.Headers.Authorization) ? Results.Ok(docs.Entries) : Results.Unauthorized());
@@ -0,0 +1,53 @@
using System.Net.Sockets;
using System.Text.Json;
using Gateway.Api.Options;
using Microsoft.Extensions.Options;
namespace Gateway.Api.Services;
public sealed record SystemUpdateRequest(string Password);
public sealed record SystemUpdateStatus(string Phase, string Message, string? Commit = null, string? Target = null,
DateTimeOffset? UpdatedAt = null, string? RunId = null);
public sealed class SystemUpdateService(IOptions<GatewayOptions> options)
{
private static readonly JsonSerializerOptions StatusJson = new(JsonSerializerDefaults.Web);
public bool Enabled => OperatingSystem.IsLinux()
&& !string.IsNullOrWhiteSpace(options.Value.UpdateSocketPath)
&& !string.IsNullOrWhiteSpace(options.Value.UpdateStatusPath);
public SystemUpdateStatus GetStatus()
{
if (!Enabled) return new("disabled", "Der lokale Systemupdate-Dienst ist für dieses Gateway nicht eingerichtet.");
try
{
var status = JsonSerializer.Deserialize<SystemUpdateStatus>(File.ReadAllText(options.Value.UpdateStatusPath!), StatusJson);
if (status is not null) return status;
}
catch (FileNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
catch (DirectoryNotFoundException) { return new("ready", "Bereit für ein Update aus Git."); }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
catch (JsonException) { }
return new("unavailable", "Der Update-Status konnte nicht gelesen werden.");
}
public async Task<bool> StartAsync(CancellationToken cancellationToken)
{
if (!Enabled) return false;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
try
{
await socket.ConnectAsync(new UnixDomainSocketEndPoint(options.Value.UpdateSocketPath!), timeout.Token);
using var stream = new NetworkStream(socket);
using var response = new StreamReader(stream);
return string.Equals(await response.ReadLineAsync(timeout.Token), "accepted", StringComparison.Ordinal);
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { return false; }
catch (SocketException) { return false; }
catch (IOException) { return false; }
}
}
+2
View File
@@ -67,6 +67,7 @@ async function boot() {
await loadData();
if (!can('view_dashboard')) state.view = can('view_trends') ? 'trends' : can('manage_sources') ? 'points' : 'system';
if (can('manage_gateway') && new URLSearchParams(location.search).has('network-confirm')) state.view = 'system';
if (state.user?.user?.role === 'admin' && sessionStorage.getItem(updateReturnKey)) state.view = 'system';
renderShell();
}
@@ -404,6 +405,7 @@ function bindView(view) {
document.querySelectorAll('[data-remove-serial-port]').forEach(button => button.addEventListener('click', removeSerialPort));
}
if (view === 'system') {
if (state.user?.user?.role === 'admin') bindSystemUpdate();
document.querySelector('#password-form')?.addEventListener('submit', submitPassword);
bindInstallationSettings();
bindMqttTopicTemplateSettings();
+2 -1
View File
@@ -24,6 +24,7 @@
<script src="/mqtt-topic-browser.js?v=20261119-mqtt-browser-1" defer></script>
<script src="/vendor/markdown-it-15.0.3.min.js" defer></script>
<script src="/documentation.js?v=20261119-docs-1" defer></script>
<script src="/app.js?v=20261124-point-scroll-1" defer></script>
<script src="/system-update.js?v=20261124-update-1" defer></script>
<script src="/app.js?v=20261124-update-1" defer></script>
</body>
</html>
+83
View File
@@ -0,0 +1,83 @@
const updateReturnKey = 'seiugw-update-return';
function bindSystemUpdate() {
const content = document.querySelector('#content');
content.querySelector('.grid').insertAdjacentHTML('beforeend', `
<article class="card" id="system-update-card">
<div class="card-head"><h2>Gateway-Update</h2></div>
<p class="note" data-update-status role="status">Status wird geladen …</p>
<p class="note" data-update-versions></p>
<form class="form" hidden>
<label>Administrator-Passwort<input name="password" type="password" autocomplete="current-password" maxlength="512" required></label>
<div class="buttons"><button class="btn primary">Update starten</button></div>
<div data-update-error class="error" role="alert"></div>
</form>
</article>`);
const card = content.querySelector('#system-update-card');
const form = card.querySelector('form');
const fields = form.querySelectorAll('input, button');
const message = card.querySelector('[data-update-status]');
const versions = card.querySelector('[data-update-versions]');
const error = card.querySelector('[data-update-error]');
const activePhases = new Set(['checking', 'fetching', 'building', 'activating', 'rollingBack']);
let lastRun = '';
let queuedUntil = 0;
function setBusy(busy) {
fields.forEach(field => { field.disabled = busy; });
}
async function refresh() {
if (!card.isConnected) return;
try {
const status = await api('/api/system/update');
if (!card.isConnected) return;
if (Date.now() < queuedUntil && (status.runId || '') === lastRun && !activePhases.has(status.phase)) {
setTimeout(refresh, 1500);
return;
}
queuedUntil = 0;
lastRun = status.runId || '';
message.textContent = status.message;
versions.textContent = [status.commit && `Installiert ${status.commit.slice(0, 8)}`,
status.target && status.target !== status.commit && `Ziel ${status.target.slice(0, 8)}`].filter(Boolean).join(' · ');
form.hidden = status.phase === 'disabled';
const busy = activePhases.has(status.phase);
setBusy(busy);
if (busy) {
sessionStorage.setItem(updateReturnKey, '1');
setTimeout(refresh, 1500);
} else {
sessionStorage.removeItem(updateReturnKey);
}
} catch (failure) {
if (!card.isConnected) return;
if (sessionStorage.getItem(updateReturnKey)) {
message.textContent = 'Verbindung zum Gateway wird wieder aufgebaut …';
setTimeout(refresh, 2000);
} else {
message.textContent = failure.message;
}
}
}
form.addEventListener('submit', async event => {
event.preventDefault();
const body = JSON.stringify({ password: form.elements.password.value });
form.reset();
error.textContent = '';
setBusy(true);
try {
const status = await api('/api/system/update', { method: 'POST', body });
sessionStorage.setItem(updateReturnKey, '1');
message.textContent = status.message;
queuedUntil = Date.now() + 10000;
setTimeout(refresh, 750);
} catch (failure) {
error.textContent = failure.message;
setBusy(false);
}
});
refresh();
}