From 4e35a3a5579f04266c542f0ba88c1a59614caba9 Mon Sep 17 00:00:00 2001 From: jhartworks Date: Tue, 24 Nov 2026 13:46:40 +0100 Subject: [PATCH] Add authenticated Gateway system updates with rollback --- nix/host-hyperv.nix | 4 + nix/module.nix | 73 ++++++++ nix/system-update.sh | 162 ++++++++++++++++++ src/Gateway.Api/Options/GatewayOptions.cs | 2 + src/Gateway.Api/Program.cs | 42 +++++ .../Services/SystemUpdateService.cs | 53 ++++++ src/Gateway.Api/wwwroot/app.js | 2 + src/Gateway.Api/wwwroot/index.html | 3 +- src/Gateway.Api/wwwroot/system-update.js | 83 +++++++++ 9 files changed, 423 insertions(+), 1 deletion(-) create mode 100644 nix/system-update.sh create mode 100644 src/Gateway.Api/Services/SystemUpdateService.cs create mode 100644 src/Gateway.Api/wwwroot/system-update.js diff --git a/nix/host-hyperv.nix b/nix/host-hyperv.nix index 5c0323b..2183755 100644 --- a/nix/host-hyperv.nix +++ b/nix/host-hyperv.nix @@ -11,6 +11,10 @@ bacnet.deviceInstance = 23; bacnet.ipPort = 47808; webPort = 8088; + updates = { + enable = true; + remote = "https://git.portal.se-cloud.de/Hannes/SE-UGW"; + }; openFirewall = true; trends = { enable = true; diff --git a/nix/module.nix b/nix/module.nix index a422241..5c31242 100644 --- a/nix/module.nix +++ b/nix/module.nix @@ -12,6 +12,25 @@ let && !config.networking.useNetworkd && !config.networking.networkmanager.enable; dhcpcdBase = builtins.head (builtins.match ".* --config ([^ ]+).*" config.systemd.services.dhcpcd.serviceConfig.ExecStart); networkHelper = "${pkgs.python3}/bin/python3 ${./host-network.py}"; + updateSocket = "/run/seiugw-update/request.sock"; + updateWorker = pkgs.writeShellScript "seiugw-system-update" '' + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.git pkgs.util-linux pkgs.systemd pkgs.curl pkgs.jq pkgs.sqlite pkgs.nix ]}:/run/current-system/sw/bin + export NIX_PATH=${escapeShellArg "nixos-config=/etc/nixos/configuration.nix:nixpkgs=${pkgs.path}"} + export SEIUGW_UPDATE_REPO=${escapeShellArg cfg.updates.checkout} + export SEIUGW_UPDATE_REMOTE=${escapeShellArg cfg.updates.remote} + export SEIUGW_UPDATE_BRANCH=${escapeShellArg cfg.updates.branch} + export SEIUGW_UPDATE_DATA=${escapeShellArg cfg.dataDir} + export SEIUGW_UPDATE_HEALTH=${escapeShellArg "http://127.0.0.1:${toString cfg.webPort}"} + ${builtins.readFile ./system-update.sh} + ''; + updateTrigger = pkgs.writeShellScript "seiugw-request-update" '' + if ${pkgs.systemd}/bin/systemd-run --quiet --collect --unit=seiugw-update-worker \ + --property=Type=exec ${updateWorker} >&2; then + printf 'accepted\n' + else + printf 'unavailable\n' + fi + ''; in { options.services.seiugw = { @@ -47,6 +66,25 @@ in description = "Open the configured web and BACnet/IP ports in the NixOS firewall."; }; + updates = { + enable = mkEnableOption "local-root system updates requested by the Gateway administrator"; + checkout = mkOption { + type = types.str; + default = "/etc/nixos/seiugw"; + description = "Root-owned checkout already used by the NixOS host configuration."; + }; + remote = mkOption { + type = types.str; + default = ""; + description = "Trusted HTTPS Git URL used by the update worker."; + }; + branch = mkOption { + type = types.str; + default = "main"; + description = "Branch allowed for fast-forward gateway updates."; + }; + }; + bacnet = { interface = mkOption { type = types.str; @@ -133,6 +171,13 @@ in }; config = mkIf cfg.enable { + assertions = optionals cfg.updates.enable [ + { + assertion = builtins.match "https://[^/@]+/[^?#]+" cfg.updates.remote != null; + message = "Gateway system updates require an HTTPS Git remote without embedded credentials."; + } + ]; + users.groups.seiugw = { }; users.groups.dialout = { }; users.users.seiugw = { @@ -151,8 +196,33 @@ in "d /var/lib/seiugw-network 0700 root root -" ] ++ optionals cfg.komari.enable [ "d ${cfg.komari.installDir} 0750 root root -" + ] ++ optionals cfg.updates.enable [ + "d /var/lib/seiugw-updater 0755 root root -" ]; + systemd.sockets.seiugw-update = mkIf cfg.updates.enable { + description = "Local Gateway system update requests"; + wantedBy = [ "sockets.target" ]; + socketConfig = { + ListenStream = updateSocket; + SocketUser = "root"; + SocketGroup = "seiugw"; + SocketMode = "0660"; + Accept = true; + RemoveOnStop = true; + }; + }; + + systemd.services."seiugw-update@" = mkIf cfg.updates.enable { + description = "Start the independent Gateway update worker"; + serviceConfig = { + ExecStart = updateTrigger; + StandardInput = "socket"; + StandardOutput = "socket"; + StandardError = "journal"; + }; + }; + networking.firewall = mkIf cfg.openFirewall { allowedTCPPorts = [ cfg.webPort cfg.opcUa.port ] ++ cfg.modbusTcpPorts; allowedUDPPorts = [ cfg.bacnet.ipPort ]; @@ -240,6 +310,9 @@ in Gateway__Bacnet__DeviceInstance = toString cfg.bacnet.deviceInstance; Gateway__Bacnet__IpPort = toString cfg.bacnet.ipPort; Gateway__OpcUa__Port = toString cfg.opcUa.port; + } // lib.optionalAttrs cfg.updates.enable { + Gateway__UpdateSocketPath = updateSocket; + Gateway__UpdateStatusPath = "/var/lib/seiugw-updater/status.json"; }; serviceConfig = { diff --git a/nix/system-update.sh b/nix/system-update.sh new file mode 100644 index 0000000..45d9a8b --- /dev/null +++ b/nix/system-update.sh @@ -0,0 +1,162 @@ +set -euo pipefail +umask 077 +export GIT_TERMINAL_PROMPT=0 + +state=/var/lib/seiugw-updater +repo="$SEIUGW_UPDATE_REPO" +profile=/nix/var/nix/profiles/system +database="$SEIUGW_UPDATE_DATA/seiugw.db" +gateway_units=(seiugw.service seiugw-bacnet.service) +commit="" +previous_commit="" +target="" +step="Vorprüfung" +checkout_changed=0 +services_stopped=0 +activation_started=0 +snapshot_ready=0 + +exec 9>"$state/lock" +flock -n 9 +work=$(mktemp -d "$state/run.XXXXXX") +cd "$work" + +git_gateway() { + git -C "$repo" -c core.hooksPath=/dev/null "$@" +} + +status() { + jq -n --arg phase "$1" --arg message "$2" --arg commit "$commit" --arg target "$target" \ + --arg updatedAt "$(date --iso-8601=seconds)" --arg runId "${work##*/}" \ + '{phase:$phase,message:$message,commit:$commit,target:$target,updatedAt:$updatedAt,runId:$runId}' >"$work/status.json" + chmod 0644 "$work/status.json" + mv -f "$work/status.json" "$state/status.json" +} + +healthy() { + local attempt consecutive=0 heartbeat now + for ((attempt=0; attempt<30; attempt++)); do + now=$(date +%s%3N) + heartbeat=$(runuser -u seiugw -- sqlite3 -readonly -cmd '.timeout 1000' "$database" \ + 'SELECT heartbeat_ms FROM bacnet_runtime WHERE id=1' 2>/dev/null) || heartbeat="" + if systemctl is-active --quiet seiugw.service && + systemctl is-active --quiet seiugw-bacnet.service && + [[ $heartbeat =~ ^[0-9]{13}$ ]] && ((now - heartbeat < 5000)) && + curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/api/health" | + jq -e '.status == "ok" and .adminConfigured == true' >/dev/null && + curl -fsS --max-time 2 "$SEIUGW_UPDATE_HEALTH/" -o /dev/null; then + ((consecutive+=1)) + if ((consecutive >= 3)); then return 0; fi + else + consecutive=0 + fi + sleep 2 + done + return 1 +} + +finish() { + local code=$? restored=1 + trap - EXIT + trap '' HUP INT TERM + if ((code != 0)); then + echo "Gateway update failed during $step (exit $code)." >&2 + if ((checkout_changed || services_stopped)); then + status rollingBack "Fehler bei $step. Die vorherige Version wird wiederhergestellt." || true + if ((services_stopped)); then + if systemctl stop "${gateway_units[@]}"; then + if ((snapshot_ready)); then + runuser -u seiugw -- sqlite3 -bail "$database" ".restore '$work/gateway.db'" || restored=0 + fi + else + restored=0 + fi + fi + if ((checkout_changed)); then git_gateway reset --keep "$previous_commit" || restored=0; fi + commit=$previous_commit + if ((activation_started)); then + if [[ $(readlink -f "$profile") != "$previous_system" ]]; then + nix-env --profile "$profile" --set "$previous_system" || restored=0 + fi + "$previous_system/bin/switch-to-configuration" switch || restored=0 + fi + if ((services_stopped)); then + if ! systemctl start "${gateway_units[@]}" || ! healthy; then restored=0; fi + fi + if ((restored)); then + status rolledBack "Fehler bei $step. Die vorherige Version wurde wiederhergestellt." || true + else + status rollbackFailed "Fehler bei $step. Die Wiederherstellung konnte nicht bestätigt werden." || true + echo "Recovery files kept in $work." >&2 + exit "$code" + fi + else + status failed "Fehler bei $step. Die installierte Version läuft weiter." || true + fi + fi + rm -f -- "$work/result" "$work/gateway.db" "$work/gateway.db-wal" "$work/gateway.db-shm" "$work/status.json" + rmdir -- "$work" + exit "$code" +} +trap finish EXIT +trap 'exit 130' HUP INT TERM + +status checking "Der Repository- und Systemstand wird geprüft." +[[ $(git_gateway rev-parse --show-toplevel) == "$repo" ]] +commit=$(git_gateway rev-parse HEAD) +previous_commit=$commit +[[ $(git_gateway symbolic-ref --short HEAD) == "$SEIUGW_UPDATE_BRANCH" ]] +[[ -z $(git_gateway status --porcelain --untracked-files=all) ]] +previous_system=$(readlink -f /run/current-system) +[[ $(readlink -f "$profile") == "$previous_system" ]] + +step="Git-Abruf" +status fetching "Neue Version wird aus Git abgerufen." +timeout 120 git -C "$repo" -c core.hooksPath=/dev/null -c credential.helper= \ + fetch --no-tags -- "$SEIUGW_UPDATE_REMOTE" "refs/heads/$SEIUGW_UPDATE_BRANCH" +target=$(git_gateway rev-parse FETCH_HEAD) +if [[ $commit == "$target" ]]; then + status current "Das Gateway ist bereits auf dem aktuellen Stand." + exit 0 +fi +if git_gateway merge-base --is-ancestor "$target" "$commit"; then + status unpublished "Die installierte Version ist neuer als der veröffentlichte Stand." + exit 0 +fi +git_gateway merge-base --is-ancestor "$commit" "$target" + +step="Systembau" +status building "Die neue NixOS-Generation wird gebaut." +checkout_changed=1 +git_gateway merge --ff-only "$target" +timeout --kill-after=30s 60m nixos-rebuild build +candidate=$(readlink -f result) +[[ -x $candidate/bin/switch-to-configuration ]] + +step="Datenbanksicherung" +status activating "Das Gateway wird kurz angehalten. Die Datenbank wird gesichert." +services_stopped=1 +systemctl stop "${gateway_units[@]}" +[[ -f $database ]] +chgrp seiugw "$work" +chmod 0710 "$work" +install -o seiugw -g seiugw -m 0600 /dev/null "$work/gateway.db" +runuser -u seiugw -- sqlite3 -bail "$database" ".backup '$work/gateway.db'" +[[ $(sqlite3 -bail "$work/gateway.db" 'PRAGMA quick_check') == ok ]] +snapshot_ready=1 + +step="Aktivierung" +status activating "Die neue Version wird aktiviert und geprüft." +activation_started=1 +"$candidate/bin/switch-to-configuration" test +[[ $(readlink -f /run/current-system) == "$candidate" ]] +systemctl restart "${gateway_units[@]}" +step="Funktionsprüfung" +healthy + +step="Boot-Konfiguration" +nix-env --profile "$profile" --set "$candidate" +"$candidate/bin/switch-to-configuration" boot +[[ $(readlink -f "$profile") == "$candidate" ]] +commit=$target +status succeeded "Die neue Version ist aktiv und für den nächsten Start eingestellt." diff --git a/src/Gateway.Api/Options/GatewayOptions.cs b/src/Gateway.Api/Options/GatewayOptions.cs index f4cac00..d47a77a 100644 --- a/src/Gateway.Api/Options/GatewayOptions.cs +++ b/src/Gateway.Api/Options/GatewayOptions.cs @@ -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(); diff --git a/src/Gateway.Api/Program.cs b/src/Gateway.Api/Program.cs index bd9d244..628d584 100644 --- a/src/Gateway.Api/Program.cs +++ b/src/Gateway.Api/Program.cs @@ -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(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddRateLimiter(options => +{ + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.AddPolicy("system-update-password", context => + { + var user = context.RequestServices.GetRequiredService().GetUser(context.Request.Headers.Authorization); + return RateLimitPartition.GetFixedWindowLimiter(user?.User.Id.ToString() ?? "anonymous", _ => new FixedWindowRateLimiterOptions + { + PermitLimit = 5, + Window = TimeSpan.FromMinutes(1) + }); + }); +}); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); @@ -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()); diff --git a/src/Gateway.Api/Services/SystemUpdateService.cs b/src/Gateway.Api/Services/SystemUpdateService.cs new file mode 100644 index 0000000..5e14823 --- /dev/null +++ b/src/Gateway.Api/Services/SystemUpdateService.cs @@ -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 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(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 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; } + } +} diff --git a/src/Gateway.Api/wwwroot/app.js b/src/Gateway.Api/wwwroot/app.js index 2e10495..53418ed 100644 --- a/src/Gateway.Api/wwwroot/app.js +++ b/src/Gateway.Api/wwwroot/app.js @@ -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(); diff --git a/src/Gateway.Api/wwwroot/index.html b/src/Gateway.Api/wwwroot/index.html index 2cee068..901afd5 100644 --- a/src/Gateway.Api/wwwroot/index.html +++ b/src/Gateway.Api/wwwroot/index.html @@ -24,6 +24,7 @@ - + + diff --git a/src/Gateway.Api/wwwroot/system-update.js b/src/Gateway.Api/wwwroot/system-update.js new file mode 100644 index 0000000..0b9e951 --- /dev/null +++ b/src/Gateway.Api/wwwroot/system-update.js @@ -0,0 +1,83 @@ +const updateReturnKey = 'seiugw-update-return'; + +function bindSystemUpdate() { + const content = document.querySelector('#content'); + content.querySelector('.grid').insertAdjacentHTML('beforeend', ` +
+

Gateway-Update

+

Status wird geladen …

+

+ +
`); + 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(); +}