diff --git a/crates/server/src/jobs.rs b/crates/server/src/jobs.rs index 9494baf..39b2f8b 100644 --- a/crates/server/src/jobs.rs +++ b/crates/server/src/jobs.rs @@ -1629,8 +1629,6 @@ mod windows_contract_tests { crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(), ), }; - crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1]) - .await; let mut request = input(); request.targets.asset_ids = assets.clone(); let view = plan(&state, &principal, tenant, request.clone()) @@ -1729,6 +1727,8 @@ mod windows_contract_tests { .execute(&admin) .await .unwrap(); + crate::script_library::tests::revision_plan_contract(&state, &principal, assets[0], assets[1]) + .await; let view = plan(&state, &principal, tenant, profiled).await.unwrap(); let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap(); let bytes: Vec = diff --git a/crates/server/src/script_library.rs b/crates/server/src/script_library.rs index b2fa0da..500b6a4 100644 --- a/crates/server/src/script_library.rs +++ b/crates/server/src/script_library.rs @@ -259,7 +259,58 @@ pub(crate) mod tests { ) { let tenant = p.tenant; let initial = list(s, p, tenant, PageQuery::default()).await.unwrap(); - let template = &initial["items"][0]; + let items = initial["items"].as_array().unwrap(); + assert_eq!(items.len(), 13); + let template = items + .iter() + .find(|item| item["name"] == "Windows-Updates installieren") + .unwrap(); + for (prefix, interpreter, asset) in [ + ("Linux · ", "posix_sh", linux), + ("Windows · ", "powershell", windows), + ] { + let revisions: Vec<_> = items + .iter() + .filter(|item| item["name"].as_str().unwrap().starts_with(prefix)) + .collect(); + assert_eq!(revisions.len(), 6); + for row in revisions { + let identity = if row["name"] == "Windows · Betriebssystem-Updatebedarf anzeigen" { + "system" + } else { + "agent_service" + }; + assert_eq!(row["interpreter"], interpreter); + assert_eq!(row["execution_identity"], identity); + assert_eq!(row["version"], 1); + let id = Uuid::parse_str(row["revision_id"].as_str().unwrap()).unwrap(); + let selection = Selection { + targets: Targets { + asset_ids: vec![asset], + }, + schedule: Schedule { + not_before: Utc::now(), + start_before: Utc::now() + Duration::minutes(30), + }, + rollout: Rollout { + max_parallel: 1, + halt_after_failures: 1, + }, + reason: "standard diagnostic library contract".into(), + max_runtime_seconds: 120, + max_output_bytes: 65536, + }; + let planned = plan(s, p, tenant, id, selection).await; + if identity == "system" { + assert_eq!(planned.unwrap_err().0, StatusCode::FORBIDDEN); + } else { + assert_eq!( + planned.unwrap()["plan_payload"]["script_revision"]["script_sha256"], + row["script_sha256"] + ); + } + } + } assert_eq!(template["name"], "Windows-Updates installieren"); assert_eq!(template["interpreter"], "powershell"); let native = script( diff --git a/docs/mvp-completion-plan.md b/docs/mvp-completion-plan.md index da7522a..a3fdb3c 100644 --- a/docs/mvp-completion-plan.md +++ b/docs/mvp-completion-plan.md @@ -21,7 +21,7 @@ | --- | --- | --- | | Server, WebUI und MCP | Dedizierter ARM64-Server mit TLS, getrenntem Gerätegateway und öffentlicher Verwaltung mit Passwort/TOTP und scoped MCP-Tokens. Die WebUI genehmigte je eine feste Skriptrevision auf Linux und Windows. MCP und WebUI lieferten dieselbe Ausgabe und dieselbe Versuch-ID. | [Ergebnisse beider Geräte](evidence/script-library-acceptance-20261117.json) | | Linux- und Windows-Client | Auf beiden Gästen HTTPS-Polling mit mehreren echten Kontakten. Ein Leerlaufkontakt übermittelt Inventar und Heartbeats auch bei leerer Auftragsliste. | [Bereinigung und Geräteabgleich](evidence/dev-cleanup-pull-20261117.json) | -| Skriptbibliothek | Versionierte, mandantengebundene Skripte, feste Revision im Plan, WebUI und MCP. Die Windows-Update-Vorlage ist enthalten. | KB890830 v5.147 über den festen SYSTEM-Bibliotheksauftrag installiert. [Installationsbeleg](evidence/windows-update-installation-20261117.json) | +| Skriptbibliothek | Versionierte, mandantengebundene Skripte, feste Revision im Plan, WebUI und MCP. KB890830 v5.147 über den festen SYSTEM-Bibliotheksauftrag installiert. [Installationsbeleg](evidence/windows-update-installation-20261117.json) | Zwölf lesende Standardvorlagen und typisierte Neustartplanung für beide Plattformen. PostgreSQL prüfte Anlage, Mandantengrenze, feste Revisionen und die verweigerte SYSTEM-Planung ohne passende Rechte. Je fünf Diagnosen liefen nativ erfolgreich. Linux meldete fehlenden Journalzugriff, Windows verweigerte die Updatesuche als LocalService. Die Vorlage verlangt deshalb SYSTEM und die passende Wartungsrichtlinie. Beide Neustartentwürfe im lokalen Browser geprüft, tatsächliche Neustarts brauchen einen konkreten Zielauftrag. Bereitstellung läuft. [Katalogmigration](../migrations/0033_standard_diagnostic_scripts.sql) | | Veröffentlichung und Erstaufnahme | Auf dem dedizierten Server liegen signierte Linux- und Windows-GNU-Releases. Beide öffentlichen Installer wurden mit einem per WebUI erzeugten Einmalcode auf den Testgästen erfolgreich ausgeführt. | Regulärer PowerShell-Auftrag auf dem frisch aufgenommenen Windows-Gerät mit Exitcode 0. | | Selbstupdate | Linux wechselte auf `0.1.0-mvp.2`, der frische Windows-GNU-Client nach seinem Skriptauftrag auf `0.1.3` und anschließend `0.1.4`. Prozesshash und Geräteidentität wurden nativ geprüft. | [Linux](evidence/linux-public-installer-update-20261117.json) · [Windows](evidence/windows-https-release-20261117.json) | | Entwicklungsbereitstellung | Linux-, Windows- und ARM64-Builder nutzen feste Git-Revisionen. SSH-Staging prüft den übertragenen Hash. Der Serverrunner prüft laufende Binärdatei, Migrationen, beide TLS-Healthchecks und die ausgelieferte WebUI. | Siehe [Entwicklungsbefehle](development.md). | diff --git a/docs/public-access.md b/docs/public-access.md index 42d9881..efdc3b8 100644 --- a/docs/public-access.md +++ b/docs/public-access.md @@ -38,6 +38,10 @@ Der Entwicklungsoperator kann dem bereits eingerichteten lokalen Betreiberkonto 4. Unter **Genehmigungen → Offen** den Antrag öffnen, Skript, Zielgeräte, Rechte und Zeitfenster prüfen und genehmigen oder ablehnen. Der Verlauf zeigt die entschiedenen und abgelaufenen Anträge. 5. Unter **Aufträge** den Eintrag öffnen. Der Bereich **Skriptinhalt** zeigt den beim Einreichen gespeicherten Code samt Version oder Kennzeichnung als einmaliges Skript. Bei einem einzelnen Gerät erscheint die Ausgabe sofort. Bei mehreren Geräten öffnet **Ergebnis anzeigen** die Ausgabe direkt beim gewählten Gerät. +Die Standarddiagnosen stehen unter **Skripte** mit getrennten Versionen für Linux und Windows bereit. Die Windows-Updatesuche verwendet `SYSTEM` und benötigt die passende Wartungsrichtlinie im internen Entwicklungsprofil. Auf Linux hängt die Logabfrage von den Journalrechten des Agent-Dienstkontos ab. + +Für einen Neustart unter **Aufträge → Neuer Auftrag** ein Gerät wählen und **Gerät neu starten** auswählen. Der feste Plan verwendet auf Linux `root` und auf Windows `SYSTEM`. Der Neustart benötigt den passenden Helper, die Wartungsrichtlinie und das interne Entwicklungsprofil. Einreichung und Genehmigung erfolgen über denselben Auftragsablauf. Der Erfolg wird anhand eines authentisierten Wiederkontakts mit neuer Boot-ID geprüft. + ## Entwicklung und Deployment Der öffentliche API-Dienst `public-api` läuft unprivilegiert auf `127.0.0.1:18445`, im Produktionsprofil mit lokalem Passwort/TOTP und ohne Entwicklungszugänge. Der private Entwicklungsdienst bleibt auf `127.0.0.1:18443`. PostgreSQL hat keinen veröffentlichten Port. Der Reverseproxy verifiziert das TLS-Zertifikat des jeweiligen internen Dienstes. Öffentliche Anmeldung und MCP gehen an `public-api`, die vorhandenen Bootstrapdownloads an das Gerätegateway. diff --git a/migrations/0033_standard_diagnostic_scripts.sql b/migrations/0033_standard_diagnostic_scripts.sql new file mode 100644 index 0000000..e59186e --- /dev/null +++ b/migrations/0033_standard_diagnostic_scripts.sql @@ -0,0 +1,421 @@ +-- Give existing and newly created customers the same editable starting revisions. +CREATE FUNCTION seed_standard_diagnostic_scripts(target_tenant uuid) RETURNS void +LANGUAGE plpgsql SET search_path = pg_catalog, public AS $seed$ +DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), ''); +BEGIN + PERFORM set_config('app.tenant_id', target_tenant::text, true); + INSERT INTO public.script_revisions(tenant_id, name, version, interpreter, execution_identity, created_by, script_utf8) + SELECT target_tenant, name, 1, interpreter, execution_identity, 'system:bootstrap', body + FROM (VALUES + ('Linux · Agent und Updater prüfen', 'posix_sh', 'agent_service', $linux_agent$#!/bin/sh +set -eu +printf 'Ausführungskonto: %s\n' "$(id -un)" +version=$(python3 -I -c 'import json; print(json.load(open("/opt/rust-discovery-client/current/manifest.json"))["version"])' 2>/dev/null) || + version='unbekannt (Release-Manifest nicht lesbar)' +printf 'Agent-Release auf dem Datenträger: %s\n' "$version" +systemctl show --no-pager -p Id -p LoadState -p ActiveState -p SubState rmm-discovery-agent.service +systemctl show --no-pager -p Id -p LoadState -p ActiveState -p LastTriggerUSec -p NextElapseUSecRealtime rmm-discovery-update.timer +systemctl list-timers --all --no-pager rmm-discovery-update.timer +systemctl show --no-pager -p Id -p LoadState -p Result rmm-discovery-update.service +$linux_agent$), + ('Windows · Agent und Updater prüfen', 'powershell', 'agent_service', $windows_agent$$ErrorActionPreference = 'Stop' +Write-Output ('Ausfuehrungskonto: ' + [Security.Principal.WindowsIdentity]::GetCurrent().Name) +$agent = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryWindows'" +$updater = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoveryReleasePull'" +foreach ($entry in @( + @{ Name = 'RmmDiscoveryWindows'; Service = $agent } + @{ Name = 'RmmDiscoveryReleasePull'; Service = $updater } +)) { + $service = $entry.Service + if ($null -eq $service) { + Write-Output ($entry.Name + ': fehlt') + } else { + Write-Output ('{0}: {1}; Starttyp: {2}; Dienstkonto: {3}' -f $service.Name, $service.State, $service.StartMode, $service.StartName) + } +} +if ($agent.PathName -match '^"([^"]+)"') { + $manifest = Join-Path (Split-Path -Parent $Matches[1]) 'manifest.json' + try { + $release = Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json + if (-not $release.version) { throw 'Version fehlt.' } + Write-Output ('Agent-Release auf dem Datentraeger: ' + $release.version) + } catch { + Write-Output 'Agent-Release: unbekannt (Release-Manifest nicht lesbar)' + } +} else { + Write-Output 'Agent-Release: unbekannt (Dienstpfad fehlt oder hat ein anderes Format)' +} +$windows_agent$), + ('Linux · Speicherengpässe prüfen', 'posix_sh', 'agent_service', $linux_storage$#!/bin/sh +set -eu +export LC_ALL=C +rows=$(df --local --block-size=1 --output=size,avail,pcent,itotal,iavail,ipcent,fstype,target) +printf 'Lokale Dateisysteme (Warnung ab 90 Prozent Block- oder Inode-Auslastung)\n' +printf '%s\n' "$rows" | awk ' + NR > 1 && $1 > 0 && ($7 !~ /^(tmpfs|devtmpfs|ramfs|squashfs|iso9660)$/ || $8 == "/") { + blocks = $3 + 0 + inodes = $6 + 0 + score = blocks > inodes ? blocks : inodes + mount = $0 + for (i = 1; i <= 7; i++) sub(/^[[:space:]]*[^[:space:]]+[[:space:]]+/, "", mount) + printf "%d\t%s\t%s\t%s/%s Byte frei (%s belegt)\tInodes frei: %s/%s (%s belegt)\n", + score, (score >= 90 ? "WARNUNG" : "OK"), mount, $2, $1, $3, $5, $4, $6 + } +' | sort -t "$(printf '\t')" -k1,1nr | awk -F '\t' ' + NR <= 40 { sub(/^[^\t]+\t/, ""); print } + END { + if (NR == 0) { print "Keine lokalen Dateisysteme gefunden"; exit 1 } + if (NR > 40) print "Weitere Dateisysteme: " NR - 40 + } +' +$linux_storage$), + ('Windows · Speicherengpässe prüfen', 'powershell', 'agent_service', $windows_storage$$ErrorActionPreference = 'Stop' +$volumes = @(Get-CimInstance -ClassName Win32_Volume -Filter 'DriveType=3' | + Where-Object { $_.Capacity -gt 0 -and $null -ne $_.FreeSpace } | + ForEach-Object { + [pscustomobject]@{ + Volume = $_.Name + Capacity = $_.Capacity + Free = $_.FreeSpace + Used = 100.0 * ($_.Capacity - $_.FreeSpace) / $_.Capacity + } + } | Sort-Object Used -Descending) +if ($volumes.Count -eq 0) { throw 'Keine lokalen Volumes mit Kapazitaetswerten gefunden.' } +Write-Output 'Lokale Volumes (Warnung ab 90 Prozent Auslastung)' +foreach ($volume in ($volumes | Select-Object -First 40)) { + $status = if ($volume.Used -ge 90) { 'WARNUNG' } else { 'OK' } + Write-Output ('{0} {1} {2}/{3} Byte frei ({4:N1}% belegt)' -f $status, $volume.Volume, $volume.Free, $volume.Capacity, $volume.Used) +} +if ($volumes.Count -gt 40) { Write-Output ('Weitere Volumes: ' + ($volumes.Count - 40)) } +$windows_storage$), + ('Linux · Discovery-Verbindung prüfen', 'posix_sh', 'agent_service', $linux_gateway$#!/bin/sh +exec python3 -I - <<'PYTHON' +import json +from pathlib import Path +import socket +import ssl +import sys +from urllib.parse import urlsplit + +root = Path("/opt/rust-discovery-client") +try: + url = urlsplit(json.loads((root / "config.json").read_text())["gateway"]) + host, port = url.hostname, url.port or 443 + if url.scheme != "https" or not host or url.username is not None: + raise ValueError("invalid gateway origin") + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + context.load_verify_locations(cafile=root / "gateway-ca.pem") +except (OSError, ValueError, KeyError, TypeError): + sys.exit("Gateway-Konfiguration oder CA-Datei fehlt oder ist nicht lesbar.") + +print(f"Konfiguriertes Gateway: {host}:{port}", flush=True) +try: + family, kind, protocol, _, address = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)[0] +except OSError: + sys.exit("DNS: fehlgeschlagen.") +print(f"DNS: OK ({address[0]})", flush=True) +with socket.socket(family, kind, protocol) as client: + client.settimeout(8) + try: + client.connect(address) + except OSError: + sys.exit("TCP: fehlgeschlagen.") + print("TCP: OK", flush=True) + try: + with context.wrap_socket(client, server_hostname=host) as tls: + print(f"TLS: Servername und Zertifikatskette geprüft ({tls.version()})") + except ssl.SSLCertVerificationError as error: + sys.exit(f"TLS: Zertifikatsprüfung fehlgeschlagen ({error.verify_message}).") + except OSError: + sys.exit("TLS: Handshake fehlgeschlagen.") +PYTHON +$linux_gateway$), + ('Windows · Discovery-Verbindung prüfen', 'powershell', 'agent_service', $windows_gateway$$ErrorActionPreference = 'Stop' +$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery' +$config = Get-Content -LiteralPath (Join-Path $data 'config.json') -Raw | ConvertFrom-Json +$server = $config.server_name +if ($server -notmatch '^[a-zA-Z0-9][a-zA-Z0-9.-]{0,252}$' -or + $config.connect_address -notmatch '^(\[[0-9a-fA-F:]+\]|[0-9.]+):([0-9]{1,5})$') { + throw 'Ungueltiger Gatewayname oder TCP-Endpunkt in der Agentkonfiguration.' +} +$address = [Net.IPAddress]::Parse($Matches[1].Trim('[', ']')) +$port = [int]$Matches[2] +if ($port -notin (1..65535)) { throw 'Ungueltiger Gatewayport.' } +Write-Output ('Konfiguriertes Gateway: {0}:{1}; TCP-Ziel: {2}' -f $server, $port, $address) +$dnsOk = $true +try { + $addresses = @([Net.Dns]::GetHostAddresses($server)) + if ($addresses.Count -eq 0) { throw 'Keine Adressen.' } + Write-Output ('DNS: OK ({0}); konfiguriertes TCP-Ziel im DNS: {1}' -f (($addresses | Select-Object -First 8) -join ', '), ($addresses -contains $address)) +} catch { + $dnsOk = $false + Write-Output 'DNS: fehlgeschlagen.' +} +$anchors = [Security.Cryptography.X509Certificates.X509Certificate2Collection]::new() +$pem = Get-Content -LiteralPath $config.ca_file -Raw +foreach ($block in [regex]::Matches($pem, '-----BEGIN CERTIFICATE-----\s*(?[A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')) { + [void]$anchors.Add([Security.Cryptography.X509Certificates.X509Certificate2]::new( + [Convert]::FromBase64String($block.Groups['body'].Value))) +} +if ($anchors.Count -eq 0) { throw 'Gateway-CA-Datei enthaelt kein Zertifikat.' } + +$client = [Net.Sockets.TcpClient]::new($address.AddressFamily) +$tls = $null +try { + $connection = $client.ConnectAsync($address, $port) + if (-not $connection.Wait(8000)) { throw 'TCP-Zeitlimit' } + Write-Output 'TCP: OK' +} catch { + $client.Dispose() + throw 'TCP: fehlgeschlagen.' +} +try { + $client.ReceiveTimeout = 8000 + $client.SendTimeout = 8000 + $validate = [Net.Security.RemoteCertificateValidationCallback] { + param($sender, $certificate, $osChain, $errors) + # SslStream checks the name. The agent's configured CA anchors the chain. + if ($null -eq $certificate -or + ($errors -band (-bnot [Net.Security.SslPolicyErrors]::RemoteCertificateChainErrors))) { return $false } + $chain = [Security.Cryptography.X509Certificates.X509Chain]::new() + $leaf = [Security.Cryptography.X509Certificates.X509Certificate2]::new($certificate) + try { + $policy = $chain.ChainPolicy + $policy.ExtraStore.AddRange($anchors) + foreach ($element in $osChain.ChainElements) { [void]$policy.ExtraStore.Add($element.Certificate) } + $policy.VerificationFlags = [Security.Cryptography.X509Certificates.X509VerificationFlags]::AllowUnknownCertificateAuthority + $policy.RevocationMode = [Security.Cryptography.X509Certificates.X509RevocationMode]::NoCheck + $policy.UrlRetrievalTimeout = [TimeSpan]::FromSeconds(2) + [void]$policy.ApplicationPolicy.Add([Security.Cryptography.Oid]::new('1.3.6.1.5.5.7.3.1')) + if (-not $chain.Build($leaf)) { return $false } + $root = $chain.ChainElements[$chain.ChainElements.Count - 1].Certificate + foreach ($anchor in $anchors) { + if ($root.Equals($anchor)) { return $true } + } + return $false + } finally { + $leaf.Dispose() + $chain.Dispose() + } + } + $tls = [Net.Security.SslStream]::new($client.GetStream(), $false, $validate) + $tls.AuthenticateAsClient($server, [Security.Cryptography.X509Certificates.X509CertificateCollection]::new(), + [Security.Authentication.SslProtocols]::None, $false) + Write-Output ('TLS: Servername und Zertifikatskette geprueft (' + $tls.SslProtocol + ').') +} finally { + if ($null -ne $tls) { $tls.Dispose() } + $client.Dispose() + foreach ($anchor in $anchors) { $anchor.Dispose() } +} +if (-not $dnsOk) { exit 1 } +$windows_gateway$), + ('Linux · Neustartbedarf prüfen', 'posix_sh', 'agent_service', $linux_boot$#!/bin/sh +set -eu +export LC_ALL=C +boot=$(awk '$1 == "btime" { print $2 }' /proc/stat) +test -n "$boot" +printf 'Letzte Bootzeit (UTC): %s\n' "$(date -u -d "@$boot" +%FT%TZ)" +if [ -e /run/reboot-required ]; then + printf 'Neustart ausstehend: ja (/run/reboot-required)\n' +elif [ -d /run ] && [ -x /run ]; then + printf 'Neustartbedarf: unbekannt (kein Marker in /run; abhängig von Distribution und Paketen)\n' +else + printf 'Neustartbedarf: unbekannt (/run nicht zugänglich)\n' +fi +$linux_boot$), + ('Windows · Neustartbedarf prüfen', 'powershell', 'agent_service', $windows_boot$$ErrorActionPreference = 'Stop' +$event = Get-WinEvent -FilterHashtable @{ LogName='System'; ProviderName='Microsoft-Windows-Kernel-General'; Id=12 } -MaxEvents 1 +$start = ([xml]$event.ToXml()).Event.EventData.Data | Where-Object { $_.Name -ceq 'StartTime' } +$utc = [Xml.XmlConvert]::ToDateTimeOffset($start.InnerText).UtcDateTime.ToString('o') +Write-Output ('Letzte Bootzeit (UTC, Windows-Systemereignis): ' + $utc) +$sources = @( + @{ Name = 'Windows Update'; Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired' } + @{ Name = 'Komponentenwartung (CBS)'; Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending' } +) +$present = $false +$unknown = $false +foreach ($source in $sources) { + try { + $marker = Test-Path -LiteralPath $source.Key + $present = $present -or $marker + $state = if ($marker) { 'vorhanden' } else { 'fehlt' } + Write-Output ($source.Name + ': ' + $state) + } catch { + $unknown = $true + Write-Output ($source.Name + ': nicht lesbar') + } +} +if ($present) { Write-Output 'Neustart ausstehend: ja' } +elseif ($unknown) { Write-Output 'Neustartbedarf: unbekannt' } +else { Write-Output 'Neustartbedarf: keiner laut den beiden geprueften Markern' } +$windows_boot$), + ('Linux · Letzte Agent- und Updatefehler', 'posix_sh', 'agent_service', $linux_logs$#!/bin/sh +exec python3 -I - <<'PYTHON' +from datetime import datetime, timezone +import json +import re +import subprocess +import sys + +try: + result = subprocess.run( + ["journalctl", "--since=24 hours ago", "--no-pager", "--lines=400", "--output=json", + "--output-fields=PRIORITY,MESSAGE,_SYSTEMD_UNIT", + "-u", "rmm-discovery-agent.service", "-u", "rmm-discovery-update.service"], + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=15, + ) +except (OSError, subprocess.TimeoutExpired): + sys.exit("Agentjournal konnte nicht gelesen werden.") +if result.returncode != 0: + sys.exit("Agentjournal nicht lesbar (Dienstkonto oder Journal nicht verfügbar).") +partial = bool(result.stderr.strip()) +if partial: + print("Agentjournal möglicherweise nur teilweise lesbar (Journalzugriff prüfen).") + +print("Agent und Updater: Fehler und Warnungen aus den letzten 400 Einträgen innerhalb von 24 Stunden") +messages = [] +for line in result.stdout.splitlines(): + event = json.loads(line) + message = event.get("MESSAGE") + if isinstance(message, str) and ( + event.get("PRIORITY") in {"0", "1", "2", "3", "4"} + or re.search(r"\b(fail(?:ed|ure)?|err(?:or)?|warn(?:ing)?|timed?\s*out|denied|panic)\b", message, re.I) + ): + when = datetime.fromtimestamp(int(event["__REALTIME_TIMESTAMP"]) / 1e6, timezone.utc) + messages.append(f"{when.isoformat(timespec='seconds')} {' '.join(message.split())[:300]}") +for message in messages[-20:]: + print(message) +if not messages and not partial: + print("Keine passenden Einträge gefunden.") +PYTHON +$linux_logs$), + ('Windows · Letzte Agent- und Updatefehler', 'powershell', 'agent_service', $windows_logs$$ErrorActionPreference = 'Stop' +function Read-Events($filter, $limit) { + try { + Get-WinEvent -FilterHashtable $filter -MaxEvents $limit + } catch { + if ($_.FullyQualifiedErrorId -notlike 'NoMatchingEventsFound,*') { throw } + } +} +$since = (Get-Date).AddHours(-24) +$names = @('RmmDiscoveryWindows', 'RmmDiscoveryReleasePull') +$names += @(Get-Service -Name $names -ErrorAction SilentlyContinue | Select-Object -ExpandProperty DisplayName) +$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery' +$releaseStatus = Join-Path $data 'release-state\release-status.json' +try { + if (-not (Test-Path -LiteralPath $releaseStatus -PathType Leaf)) { + $releaseStatus = Join-Path $data 'release-status.json' + } + $last = Get-Content -LiteralPath $releaseStatus -Raw | ConvertFrom-Json + if ($last.status -notin 'ok', 'error') { throw 'Unbekannter Updaterstatus.' } + $checked = [DateTimeOffset]::Parse($last.observed_at).UtcDateTime + Write-Output ('Agent-Updater: letzter protokollierter Lauf {0:o}, Status {1}' -f $checked, $last.status) +} catch { + Write-Output 'Agent-Updater: letzter Lauf unbekannt (Statusdatei fehlt oder ist nicht lesbar).' +} +$failed = $false +$events = @() +try { + $scm = @{ LogName='System'; ProviderName='Service Control Manager'; StartTime=$since; Id=7000,7001,7009,7011,7023,7024,7031,7034 } + $events += @(Read-Events $scm 250 | Where-Object { + $event = $_ + $names | Where-Object { $_ -in $event.Properties.Value } + }) +} catch { + Write-Warning 'Service-Control-Manager-Ereignisse nicht lesbar.' + $failed = $true +} +try { + $updates = @{ LogName='Microsoft-Windows-WindowsUpdateClient/Operational'; ProviderName='Microsoft-Windows-WindowsUpdateClient'; StartTime=$since; Level=2,3 } + $events += @(Read-Events $updates 20) +} catch { + Write-Warning 'Windows-Update-Ereignisse nicht lesbar.' + $failed = $true +} +Write-Output 'Agentdienste und Windows Update: letzte 24 Stunden, hoechstens 20 Ereignisse' +foreach ($event in ($events | Sort-Object TimeCreated -Descending | Select-Object -First 20)) { + $line = ([string]$event.Message -replace '\s+', ' ').Trim() + if ($line.Length -gt 300) { $line = $line.Substring(0, 300) } + Write-Output ('{0:o} {1} #{2} {3}' -f $event.TimeCreated.ToUniversalTime(), $event.ProviderName, $event.Id, $line) +} +if ($events.Count -eq 0 -and -not $failed) { Write-Output 'Keine passenden Ereignisse gefunden.' } +if ($failed) { exit 1 } +$windows_logs$), + ('Linux · Betriebssystem-Updatebedarf anzeigen', 'posix_sh', 'agent_service', $linux_updates$#!/bin/sh +set -eu +export LC_ALL=C +if ! grep -Eq '^ID=(debian|ubuntu|"debian"|"ubuntu")$' /etc/os-release || + ! command -v apt >/dev/null; then + printf 'Diese Vorlage benötigt Debian oder Ubuntu mit APT.\n' >&2 + exit 1 +fi +cutoff=$(date +%s) +count=0 +oldest= +for index in /var/lib/apt/lists/*_Packages /var/lib/apt/lists/*_Packages.*; do + [ -f "$index" ] || continue + modified=$(stat -c %Y -- "$index") + if [ -z "$oldest" ] || [ "$modified" -lt "$oldest" ]; then oldest=$modified; fi + count=$((count + 1)) +done +if [ "$count" -eq 0 ]; then + printf 'Keine lokalen APT-Paketlisten gefunden. Updatebedarf unbekannt.\n' >&2 + exit 1 +fi +printf 'APT-Paketlisten: %s; ältester Zeitstempel (UTC): %s; Alter: %s Tage\n' \ + "$count" "$(date -u -d "@$oldest" +%FT%TZ)" "$(((cutoff - oldest) / 86400))" +list=$(apt list --upgradable 2>/dev/null) || { + printf 'APT-Paketlisten konnten nicht ausgewertet werden.\n' >&2 + exit 1 +} +printf '%s\n' "$list" | awk ' + /^[^[:space:]\/]+\// { if (++found <= 50) print } + END { print "Aktualisierbare installierte Pakete laut lokalem Stand: " (found + 0) } +' +$linux_updates$), + ('Windows · Betriebssystem-Updatebedarf anzeigen', 'powershell', 'system', $windows_updates$$ErrorActionPreference = 'Stop' +$session = New-Object -ComObject Microsoft.Update.Session +$searcher = $session.CreateUpdateSearcher() +$searcher.ServerSelection = 0 +$searcher.Online = $true +$searcher.CanAutomaticallyUpgradeService = $false +Write-Output 'Suche nach fehlenden Softwareupdates ueber die konfigurierte Windows-Updatequelle.' +$result = $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'") +if ($result.ResultCode -ne 2) { + throw ('Windows-Update-Suche nicht vollstaendig erfolgreich (WUA-Ergebnis ' + $result.ResultCode + ').') +} +Write-Output ('Verfuegbare Softwareupdates: ' + $result.Updates.Count) +for ($i = 0; $i -lt [Math]::Min($result.Updates.Count, 50); $i++) { + $update = $result.Updates.Item($i) + $title = $update.Title -replace '\s+', ' ' + if ($title.Length -gt 300) { $title = $title.Substring(0, 300) } + Write-Output $title +} +$windows_updates$) + ) AS scripts(name, interpreter, execution_identity, body) + ON CONFLICT (tenant_id, name, version) DO NOTHING; + PERFORM set_config('app.tenant_id', previous_tenant, true); +END +$seed$; +REVOKE ALL ON FUNCTION seed_standard_diagnostic_scripts(uuid) FROM PUBLIC; + +CREATE OR REPLACE FUNCTION seed_tenant_script_library() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER +SET search_path = pg_catalog, public AS $$ +DECLARE previous_tenant text := coalesce(current_setting('app.tenant_id', true), ''); +BEGIN + PERFORM set_config('app.tenant_id', NEW.tenant_id::text, true); + PERFORM public.seed_windows_update_script(NEW.tenant_id); + PERFORM public.seed_standard_diagnostic_scripts(NEW.tenant_id); + PERFORM set_config('app.tenant_id', previous_tenant, true); + RETURN NEW; +END +$$; +REVOKE ALL ON FUNCTION seed_tenant_script_library() FROM PUBLIC; + +DO $backfill$ +BEGIN + LOCK TABLE tenants IN SHARE ROW EXCLUSIVE MODE; + PERFORM public.seed_standard_diagnostic_scripts(tenant_id) FROM tenants; +END +$backfill$; diff --git a/web/src/main.tsx b/web/src/main.tsx index e10bbc4..3ea7091 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -705,7 +705,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) { {route.page === 'auftraege' && ( route.tab === 'neu' ? <> ← Zu den Aufträgen - +
Weitere Wartungsaktionen

Inventur, Dienstverwaltung und weitere Wartungsaufträge planen.

Wartungsauftrag planen diff --git a/web/src/order-composer.tsx b/web/src/order-composer.tsx index 968e5d4..b15333a 100644 --- a/web/src/order-composer.tsx +++ b/web/src/order-composer.tsx @@ -37,6 +37,7 @@ type Props = { auth: Session; initialAssetIds: string[]; onSubmitted: (operationId: string) => void; + onDraft: (planId: string) => void; }; type Target = { id: string; @@ -119,17 +120,22 @@ function issueMessage(err: unknown) { return errorText(err); } -export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, customerName }: Props) { +export function OrderComposer({ tenantId, auth, initialAssetIds, onSubmitted, onDraft, customerName }: Props) { const path = (suffix: string) => tenantPath(tenantId, suffix); const key = 'rmm:order-plan:' + JSON.stringify([auth.principal.id, tenantId]); - const [ticket, setTicket] = useState(() => resumeTicket(key)); + const [savedTicket, setTicket] = useState(() => resumeTicket(key)); const [step, setStep] = useState<1 | 2>(1); const [selected, setSelected] = useState(() => [...new Set(initialAssetIds)]); const [known, setKnown] = useState>({}); const [query, setQuery] = useState(''); const [cursor, setCursor] = useState(null); const [prior, setPrior] = useState<(string | null)[]>([]); - const [mode, setMode] = useState<'library' | 'once'>('library'); + const canCreate = ['inventory:read', 'operations:read', 'operations:plan', 'operations:submit'] + .every((permission) => allowed(auth, permission)); + const canPlanScript = canCreate && allowed(auth, 'scripts:execute'); + const canPlanReboot = canCreate && (allowed(auth, 'root:execute') || allowed(auth, 'system:execute')); + const ticket = canPlanScript ? savedTicket : null; + const [mode, setMode] = useState<'library' | 'once' | 'reboot'>(() => canPlanScript ? 'library' : 'reboot'); const [revisionId, choose] = useState(''); const [linux, setLinux] = useState