Compare commits

..
Author SHA1 Message Date
kevin_janssen 65d84a19c0 Record the production VM host display verification
Rust development slice / linux (push) Failing after 7s
2026-11-18 22:44:20 +01:00
kevin_janssen cad188aeb7 Use complete certificate evidence in the hypervisor database fixture
Rust development slice / linux (push) Failing after 7s
2026-11-18 22:42:14 +01:00
kevin_janssen bcd3bd86ad Show known hypervisors and the Hetzner placeholder for virtual machines 2026-11-18 22:39:29 +01:00
kevin_janssen 08177d8843 Merge Windows helper idle CPU fix and native verification
Rust development slice / linux (push) Failing after 8s
2026-11-18 22:20:14 +01:00
kevin_janssen 2378a54bd4 Record production customer transfer availability
Rust development slice / linux (push) Failing after 7s
2026-11-18 21:47:27 +01:00
kevin_janssen 9e957e6d8d Slow successful Windows helper time refreshes
Rust development slice / linux (push) Failing after 8s
(cherry picked from commit a4bcebf440)
2026-11-18 21:40:10 +01:00
kevin_janssen 5253a9f596 Support interactive customer transfers for enrolled devices
Rust development slice / linux (push) Failing after 8s
2026-11-18 21:35:28 +01:00
kevin_janssen dd59052e7c Record native Windows idle performance and SYSTEM acceptance
Rust development slice / linux (push) Failing after 8s
2026-11-18 21:31:48 +01:00
kevin_janssen a4bcebf440 Slow successful Windows helper time refreshes 2026-11-18 21:19:14 +01:00
kevin_janssen db6325131a Record production device inventory verification
Rust development slice / linux (push) Failing after 8s
2026-11-18 20:30:24 +01:00
kevin_janssen 1f60183b7e Fit larger Linux package inventories within bounded snapshots
Rust development slice / linux (push) Failing after 8s
2026-11-18 20:20:10 +01:00
kevin_janssen 55d159cab1 Retry Linux inventory when durable traffic delays collection
Rust development slice / linux (push) Failing after 8s
2026-11-18 20:12:05 +01:00
kevin_janssen aea2d5b379 Expand the passive inventory shown in device details
Rust development slice / linux (push) Failing after 9s
2026-11-18 20:02:41 +01:00
kevin_janssen 38f43f887a Record the native OTRS closure and dashboard verification
Rust development slice / linux (push) Failing after 8s
2026-11-18 19:08:27 +01:00
kevin_janssen 915e126f24 Reconcile a human closure when the helper has no result
Rust development slice / linux (push) Failing after 9s
2026-11-18 19:03:02 +01:00
kevin_janssen abad2022e2 Record the live RAM and CPU dashboard checks
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:54:40 +01:00
kevin_janssen 6ed57c4d0b Show the same capacity bar for RAM and disk space
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:47:46 +01:00
kevin_janssen 7006ce7420 Keep the last valid CPU reading during RAM-only heartbeats
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:46:04 +01:00
kevin_janssen b3fe35b86b Show available RAM and measured CPU usage for devices
Rust development slice / linux (push) Failing after 8s
2026-11-18 18:37:18 +01:00
kevin_janssen fb2376443c Document OTRS ARM64 root-script helper activation
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:21:51 +01:00
kevin_janssen f2a2d44d84 Require pushing completed changes to Gitea
Rust development slice / linux (push) Failing after 7s
2026-11-18 18:14:50 +01:00
kevin_janssen 7215ea9733 Merge remote-tracking branch 'origin/main' into codex/linux-arm64-installer 2026-11-18 18:14:35 +01:00
kevin_janssen b5907d681d Record successful OTRS enrollment and corrected HTTPS installer 2026-11-18 18:13:16 +01:00
kevin_janssen 4b3d0136e9 Wait for the device certificate before probing Linux enrollment 2026-11-18 18:09:52 +01:00
kevin_janssen bfdc3da8af Record native ARM64 HTTPS release and installer verification 2026-11-18 18:07:31 +01:00
kevin_janssen 6d15f1b3f5 Use the shared target triple for the release catalog 2026-11-18 17:59:34 +01:00
kevin_janssen 8b5365f4bc Verify Linux installer architecture selection and display available targets 2026-11-18 17:59:19 +01:00
kevin_janssen 247646a2ba Build and serve signed Linux ARM64 agent releases 2026-11-18 17:58:12 +01:00
kevin_janssen 11a67ca9a4 Record the production machine type rollout on both guests
Rust development slice / linux (push) Failing after 12s
2026-11-18 17:52:09 +01:00
kevin_janssen f1538143cf Check the machine type after the labelled hostname column
Rust development slice / linux (push) Failing after 13s
2026-11-18 17:41:22 +01:00
kevin_janssen c599baa494 Show the detected machine type in device inventory 2026-11-18 17:39:43 +01:00
kevin_janssen 6963ad332c Document the accepted MVP and retire superseded development plans
Rust development slice / linux (push) Failing after 14s
2026-11-18 17:21:12 +01:00
kevin_janssen f37b6dc4f7 Record native Linux and Windows MCP script and reboot results
Rust development slice / linux (push) Failing after 15s
2026-11-18 17:01:00 +01:00
kevin_janssen 92e2050935 Record deployed MCP planning and pending Linux acceptance
Rust development slice / linux (push) Failing after 13s
2026-11-18 16:26:43 +01:00
kevin_janssen c4e064773b Authorize scoped MCP script requests on opted-in managed devices
Rust development slice / linux (push) Failing after 16s
2026-11-18 16:21:12 +01:00
kevin_janssen 5bf844d850 Record native Windows helper recovery and original job result 2026-11-18 14:30:45 +01:00
kevin_janssen e5006b3ecb Recover Windows helper sync after acknowledged result delivery 2026-11-18 14:25:42 +01:00
kevin_janssen 1d58f2e704 Keep installed admin helpers usable after release expiry
Rust development slice / linux (push) Failing after 13s
2026-11-18 13:07:19 +01:00
kevin_janssen bb4e7cbad7 Record public enrollment guide deployment and readback
Rust development slice / linux (push) Failing after 16s
2026-11-18 13:05:03 +01:00
kevin_janssen acbff0060d Explain client enrollment and MCP curl usage in the live WebUI
Rust development slice / linux (push) Failing after 14s
2026-11-18 13:03:37 +01:00
kevin_janssen 7dccb204ec Record both native reboot and follow-up runs through the script channel
Rust development slice / linux (push) Failing after 13s
2026-11-18 12:47:41 +01:00
kevin_janssen fa71f44c36 Provide the native computer name to Windows script processes 2026-11-18 12:38:03 +01:00
kevin_janssen 5889964ea1 Check Windows reboot scheduling through an explicit process result 2026-11-18 12:28:52 +01:00
kevin_janssen 55fad07327 Apply the script-only capability and start contract to every Windows profile 2026-11-18 12:17:52 +01:00
kevin_janssen 4afa6e4a12 Build the Windows updater policy capability probe 2026-11-18 12:12:36 +01:00
kevin_janssen fb07e4b548 Close retired Windows offers before start and verify policy-preserving updater support 2026-11-18 12:11:15 +01:00
kevin_janssen 0f70d8d8f5 Reconcile byte-identical historical offers without allowing another execution 2026-11-18 12:10:27 +01:00
kevin_janssen cd80bfc704 Plan device actions exclusively as approved scripts and provide reboot library revisions 2026-11-18 12:04:58 +01:00
kevin_janssen adc04f0148 Use script-only execution on Linux and preserve the enrolled helper through updates 2026-11-18 12:01:02 +01:00
kevin_janssen c692316abe Bind Windows script contexts to the installed signed helper 2026-11-18 11:58:55 +01:00
kevin_janssen ab20cb0778 Record whole-MVP identity checks and the unqualified typed reboot paths 2026-11-18 11:34:37 +01:00
kevin_janssen 53c713aa3a Record official Windows release, native self-update and retired pairing removal 2026-11-18 11:20:24 +01:00
kevin_janssen 9c7ccbb59b Enable explicitly configured private artifact storage for authenticated production releases 2026-11-18 11:08:53 +01:00
kevin_janssen 0b07baf7be Keep legacy Windows starter worker pins outside official GNU enrollments 2026-11-18 11:03:55 +01:00
kevin_janssen 07154833b3 Remove one retired device pairing and its owned history from the device detail 2026-11-18 11:03:55 +01:00
kevin_janssen 374b7e42d6 Use verified SSH profiles from the primary checkout in linked worktrees 2026-11-18 10:54:35 +01:00
kevin_janssen 663e846415 Ship Windows x64 through a separately signed official GNU release channel 2026-11-18 10:53:16 +01:00
kevin_janssen 7ddd579888 Record live device recovery, role checks and public script results 2026-11-18 10:33:32 +01:00
kevin_janssen b8e4b32a33 Wait for the Linux service launcher to execute its verified binary 2026-11-18 10:27:59 +01:00
kevin_janssen 17f2e6dc91 Roll existing Linux helper pins forward with the verified release pair 2026-11-18 10:23:43 +01:00
kevin_janssen 6d4f53dcae Display Windows CRLF as a line break in stored script output 2026-11-18 10:22:38 +01:00
kevin_janssen a0b3aa46f5 Keep participant checks consistent across submission and dispatch 2026-11-18 10:12:31 +01:00
kevin_janssen 72d95dee11 Keep Windows intent and diagnostic databases read-only with rusqlite 0.41 2026-11-18 10:11:02 +01:00
kevin_janssen 0f15f91f65 Recheck the submitting principal and protect stored log output 2026-11-18 10:10:06 +01:00
kevin_janssen db2f5b407d Ship the corrected bundled SQLite in device components and pinned builds 2026-11-18 10:08:01 +01:00
kevin_janssen 3e6ce7f07c Resume signed Windows reconciliation after a proven missing helper acknowledgement 2026-11-18 10:01:57 +01:00
kevin_janssen 7cec566dfe Record the release readiness checks and the Windows sync blocker 2026-11-18 09:40:48 +01:00
kevin_janssen 9e913b7a51 Record script library filtering and customer navigation acceptance 2026-11-18 09:29:30 +01:00
kevin_janssen 97ef5783c1 Filter the script library and show customer context across pages 2026-11-18 09:28:11 +01:00
kevin_janssen f8e5865412 Record public acceptance of order filters and decision history 2026-11-18 09:18:08 +01:00
kevin_janssen 61688bcd4b Verify the order filter form with accessible labels 2026-11-18 09:17:01 +01:00
kevin_janssen 14a271f61a Make order search, device results and decisions visible in the WebUI 2026-11-18 09:14:42 +01:00
kevin_janssen 5b6e9c9cdb Validate order search and audit decisions against PostgreSQL 2026-11-18 09:12:47 +01:00
kevin_janssen c0754f1d0d Filter orders before pagination and expose recorded decisions and result links 2026-11-18 09:07:28 +01:00
kevin_janssen 973e131c86 Integrate the currently deployed server functionality with the reviewed WebUI 2026-11-18 09:05:06 +01:00
kevin_janssen ea87d8141c Enable per-order privileged scripts on managed devices 2026-11-18 00:02:17 +01:00
kevin_janssen 2712c4f80e Record the deployed WebUI review changes and live readback 2026-11-17 23:54:51 +01:00
kevin_janssen 8e770c6378 Mark release table column headers explicitly 2026-11-17 23:53:59 +01:00
kevin_janssen f6e658ce35 Make execution controls and maintenance workflows easier to use 2026-11-17 23:52:03 +01:00
kevin_janssen a397dd7ae4 Expose the current execution stop to authorized web sessions 2026-11-17 23:46:06 +01:00
kevin_janssen 984c730f5d Add standard diagnostics and typed restart planning 2026-11-17 23:37:14 +01:00
355 changed files with 12075 additions and 37319 deletions
+17 -26
View File
@@ -1,35 +1,26 @@
# Arbeiten an Rust Discovery
## Einstieg für jeden Auftrag
Der abgenommene MVP liegt auf dem Branch `main`. Der [Produktvertrag](Rust_RMM_Implementierungsspezifikation.md) beschreibt das Verhalten, die [MVP-Abnahme](docs/mvp-completion-plan.md) die tatsächlich geprüften Geräte und Ergebnisse. Den nächsten Arbeitsumfang bestimmt der aktuelle Nutzerauftrag.
1. Lies das [Produktziel, den geprüften Stand und den nächsten Schritt](docs/mvp-completion-plan.md). **Nur dort** steht die aktive Arbeitsreihenfolge. Die [Übergabe](docs/handover.md) nennt den passenden Betriebszugang. Eine datierte Abnahme oder ein alter Reparaturplan ist ein Beleg für seinen damaligen Stand.
2. Benenne das Nutzerergebnis des gewählten Schritts, den schon vorhandenen Beleg und die fehlende Beobachtung. Lies vor Änderungen den betroffenen Code und Vertrag. Bei Produktentscheidungen gilt [Kapitel 0 der Spezifikation](Rust_RMM_Implementierungsspezifikation.md) mit dem jüngsten einschlägigen Nutzerentscheid. [Entscheidungsbuch](docs/project-decisions.md) und [Entwicklungsweg](docs/development.md) liefern den Hintergrund.
3. Ein Integrator koordiniert Zielgeräte, gemeinsam genutzte Dateien, WebUI und Gitindex. Teilaufträge bekommen einen Dateibereich und ein prüfbares Ergebnis. Vorhandenen WIP mit `git status --short` abgrenzen, funktionierende Teilstrecken wiederverwenden und nur aufgabenbezogene Änderungen aufnehmen.
4. Wenn eine frühere Grenze das Ziel behindert, kläre ihren Zweck und wähle die kleinste begründete Änderung. Technische Vereinfachungen dürfen direkt umgesetzt werden. Eine geänderte Produktentscheidung in Kapitel 0 und im Entscheidungsbuch festhalten. Eine unbekannte Wirkung eines früheren Jobs bleibt dabei unbekannt.
5. Nach einem Schritt den Status **in derselben Planzeile** aktualisieren. Quelle, Artefakt, echter Zielkontakt und fachliche Abnahme getrennt belegen. Bei einem Hindernis die konkrete fehlende Beobachtung festhalten und am nächsten unabhängigen Liefergegenstand weiterarbeiten.
## Einen Auftrag übernehmen
## Was wir liefern
1. Mit `git status --short --branch` den Arbeitsbaum und vorhandene Änderungen prüfen. Für laufende Fremdarbeit einen separaten Branch oder Worktree verwenden.
2. In der [Übergabe](docs/handover.md) den betroffenen Einstiegspunkt finden. Vor Änderungen den tatsächlichen Aufrufer, die Berechtigungsprüfung und die vorhandenen Tests lesen. Ein datierter Beleg in `docs/evidence/` dokumentiert das Ereignis zu seinem Messzeitpunkt.
3. Den normalen Bedienweg und den konkreten Fehlerfall prüfen. Bei einem Linux- oder Windows-spezifischen Verhalten den betreffenden Gast verwenden. Ein Build belegt die Erzeugung des Artefakts. Das Ergebnis des Zielgeräts belegt seine Wirkung.
4. Verändert sich das Produktverhalten, die zuständige Anleitung und den Produktvertrag abgleichen. Eine neue Abnahme im [Prüfstand](docs/mvp-completion-plan.md) mit Quelle, Ziel und beobachtetem Ergebnis nachtragen.
5. Nach jeder abgeschlossenen Änderung die zugehörigen Dateien committen und auf den passenden Branch in Gitea pushen. Das gilt auch für reine Dokuänderungen. Den gepushten Commit in Gitea prüfen. [Entwicklungsablauf](docs/development.md#änderungen-in-gitea-sichern)
Ein Server mit WebUI und MCP verwaltet Linux- und Windows-Clients. Die Clients melden Heartbeats und Inventar, holen optionale Skriptaufträge ab und geben Ergebnisse zurück. Eine benannte, versionierte Skriptbibliothek bedient beide Oberflächen. Windows-Updates sind ein PowerShell-Katalogeintrag. Ein frischer Client lässt sich über ein HTTPS-Installationsskript aufnehmen und aktualisiert seinen eigenen Agenten periodisch aus dem signierten Releasebestand des Servers. Die Abnahmekriterien stehen im Plan.
## Regeln für Änderungen
Für Geräte und Kunden gilt Kapitel 0.7. Änderungen an Kundengrenzen mit beschränktem und globalem Token prüfen, einschließlich Listen, direkter Geräte-IDs und Widerruf. Die Trennung von Bestand und Historie beruht auf der bestätigten Geräteidentität. Bei einem Kundenwechsel neu enrollen und die bisherige Historie beim ursprünglichen Kunden belassen.
- Jede neu geplante Geräteaktion nutzt ein Skript. Ein Neustart und ein Betriebssystemupdate durchlaufen denselben Weg wie ein eigenes Shell- oder PowerShell-Skript.
- Jeder eingereichte Skriptplan wartet auf Genehmigung. Eine berechtigte Person bestätigt in der WebUI Ziel, genaue Skriptbytes, Rechte, Zeitfenster und feste Versuche. Diese Entscheidung gehört zur Person. Für produktive Aufträge sind Freigaben durch die KI, einen MCP-Token oder direkte Datenbankzugriffe ausgeschlossen. Separat gekennzeichnete Simulationen gehören ausschließlich zum internen Entwicklungsprofil.
- Beim Zustellen und Wiederverbinden die Signatur-, Zeit-, Geräte- und Versuchsbindung erhalten. Einen bereits gestarteten oder ungeklärten Versuch anhand seines Journals und der Serverdaten abgleichen. Ein neuer Versuch braucht einen eigenen genehmigten Plan. Einen Neustart mit Bootwechsel, authentisiertem Kontakt derselben Installation und erfolgreichem Folgeauftrag prüfen.
- Die Kundenbindung gilt auch für direkte IDs und gespeicherte Ergebnisse. Änderungen an Tokenrechten mit berechtigtem und fremdem Kunden sowie nach Widerruf prüfen. Für einen Kundenwechsel das Gerät neu aufnehmen. Die bisherige Historie gehört zum bisherigen Kunden.
- Ein Administrator-Skript braucht neben den Serverrechten den für diese Installation eingerichteten Helper. Bei `SCRIPT_HELPER_SCOPE_DENIED` zuerst Kunden- und Tokenrechte sowie die zentrale Geräteregel prüfen. [MCP-Zugang](docs/public-access.md)
- Beim Binärwechsel Geräteidentität, Zertifikate, Journale und Dateirechte erhalten. Bei Änderungen am Installer oder Selbstupdate den HTTPS-Installer beziehungsweise den regulären Updateabruf prüfen.
Für Skriptaufträge gilt Kapitel 0.8. Die Bibliothek veröffentlicht Skriptversionen. Gerätezuweisung und Ergebniskontrolle gehören zu „Aufträge“, die interaktive Entscheidung zu „Genehmigungen“. Änderungen an einem dieser Wege am Übergang zum nächsten prüfen.
## In der Entwicklungsumgebung arbeiten
## Betrieb und Freigabe
Das Notebook ist der Entwicklungsrechner. Server und beide Testgäste sind getrennte Ziele. Für Builds, Transfer und Aktivierung die [Projektwerkzeuge](docs/development.md) verwenden. Vorhandene Artefakte dürfen für die Entwicklung über gepinntes SSH/SFTP bereitgestellt werden. Zielneustarts, echte Betriebssystemupdates und Löschungen brauchen einen konkreten Auftrag.
- Der dedizierte Server ist `discovery.ease-technologies.de`. Testclients sind die Cloud-Linux-VM und der Windows-11-Gast. Das Notebook dient ausschließlich der Entwicklung. Plattformspezifische Arbeit auf beiden Gästen darf parallel laufen. Plattformfunktionen jeweils nativ nachweisen.
- Der produktive Geräteverkehr geht vom Client aus. SSH/SFTP ist im Entwicklungsbetrieb ausdrücklich für die direkte Bereitstellung vorhandener Artefakte zulässig. Der [Entwicklungsweg](docs/development.md) beschreibt Build, Transfer und Aktivierung. Zur Produktabnahme von Installer und Selbstupdate den jeweiligen Produktweg benutzen.
- Jeder **Skript- oder Wartungsjob** aus UI, MCP oder Automatik wird zunächst als `pending_approval` gespeichert. Erst eine berechtigte Person genehmigt den unveränderlichen Plan mit Ziel, Skriptbytes, Rechten, Grenzen und festen Versuchen in der WebUI. Vorher bleiben ausführbare Jobs, Outbox, Angebote und Startgrants leer. Policies begrenzen. Direkte API-/DB-Freigaben durch KI oder Automatik sind ausgeschlossen.
- Ausschließlich im expliziten dev/test-Profil darf ein sichtbar **simulierter Testprincipal** die tatsächliche WebUI per Browser bedienen. Audit bindet `approval_origin`, `testsimulation`, Principal und Plan. In Produktion gilt die menschliche Freigabe. Redelivery darf keine zweite Ausführung auslösen. Neue Versuche und Folgejobs brauchen eine eigene feste Freigabe.
- Passive Standardtelemetrie und gespeicherte Lesezugriffe laufen ohne Job. Version 1.33 spezifiziert zusätzlich die automatische Installation **veröffentlichter signierter Agent-Releases**. Der Releasepfad akzeptiert ausschließlich die festgelegten Agentkomponenten. Eine Live-Diagnose oder ein OS-Update ist ein Wartungsjob.
- WebUI und MCP sind öffentlich über HTTPS mit lokalem Passwort/TOTP beziehungsweise scoped Bearer-Tokens erreichbar. Der [öffentliche Zugang](docs/public-access.md) ist der maßgebliche Aufbau seit Spezifikation 1.35. Der separate dev/test-Zugang bleibt intern über den SSH-Tunnel erreichbar. Dockerports an Loopback binden, PostgreSQL intern betreiben. Für die öffentlichen Geräte- und Bootstrapwege TLS-Kette und SAN/SNI prüfen, für registrierte Geräte mTLS und Mandantenbindung durchsetzen. Der öffentliche Installer braucht einen auf dem frischen Gerät bereits vertrauenswürdigen TLS-Anker.
- `credentials/` bleibt ignoriert und privat (0700, Dateien 0600). Die [Zugangsanleitung](docs/operations-access.md) nennt Parser und bestätigte Hostpins. Profile ausschließlich als Daten verarbeiten, kein `source` oder `eval`. Schlüssel, Token und private Diagnoseausgaben gehören weder ins Repository noch in Agentkontexte.
- Bei einem normalen Binärwechsel Identität, PKI, Konfiguration, Journale und Dateirechte erhalten. Im aktuellen Entwicklungssystem dürfen ausdrücklich freigegebene Altanträge und blockierende Testprojektionen gezielt entfernt werden. Nach einer Bereinigung das Fehlen des Auftrags und den frischen Geräteabgleich prüfen. Zielreboots, OS-Updates und destruktive Tests brauchen einen konkreten Auftrag. Vom Status `unknown` führt nur der belegte Abgleich oder der dokumentierte WebUI-Abschluss weiter. Niemals blind wiederholen.
## Nachweise und Umfang
Teste die betroffene Funktion und den konkreten Fehlerpfad. Verwende vorhandene native Belege weiter. Kennzeichne geplante, noch nicht ausgeführte Befehle sowie fehlende Zugänge oder Werkzeuge. Historische APT-/MSI-/Rebootabnahmen, Terminal, RustDesk, PVE/PBS, Cluster und Backups sind keine Voraussetzungen für den aktuellen Lieferplan.
Für ein benötigtes Windows-Update-Wartungsfenster den [dokumentierten Operator](docs/windows-update-dev-window.md) wiederverwenden. Der temporäre SYSTEM-Helper bindet das aktuelle signierte Agentpaar und die Geräteidentität. Nach terminalem Ergebnis das Fenster schließen und den normalen Agent-/Updatebetrieb nachlesen. Eine echte OS-Installation gilt erst mit ihrem eigenen Zielergebnis als nachgewiesen.
`credentials/` bleibt privat und von Git ausgeschlossen. Profile als Daten über die vorhandenen Parser lesen, Zugangswerte weder ausgeben noch ins Repository übernehmen. Zugangsdatenverzeichnis, Dateirechte und Hostprüfung sind in den [Betriebszugängen](docs/operations-access.md) beschrieben.
Generated
+48 -128
View File
@@ -37,18 +37,6 @@ dependencies = [
"subtle",
]
[[package]]
name = "ahash"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
dependencies = [
"cfg-if",
"once_cell",
"version_check",
"zerocopy",
]
[[package]]
name = "allocator-api2"
version = "0.2.21"
@@ -234,9 +222,6 @@ name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
dependencies = [
"serde_core",
]
[[package]]
name = "block-buffer"
@@ -721,17 +706,6 @@ version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "flume"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095"
dependencies = [
"futures-core",
"futures-sink",
"spin",
]
[[package]]
name = "fnv"
version = "1.0.7"
@@ -744,6 +718,12 @@ version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "foreign-types"
version = "0.3.2"
@@ -967,15 +947,6 @@ dependencies = [
"tracing",
]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
@@ -984,7 +955,7 @@ checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"allocator-api2",
"equivalent",
"foldhash",
"foldhash 0.1.5",
]
[[package]]
@@ -992,14 +963,8 @@ name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [
"hashbrown 0.14.5",
"foldhash 0.2.0",
]
[[package]]
@@ -1011,6 +976,15 @@ dependencies = [
"hashbrown 0.15.5",
]
[[package]]
name = "hashlink"
version = "0.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
dependencies = [
"hashbrown 0.17.1",
]
[[package]]
name = "heck"
version = "0.5.0"
@@ -1418,9 +1392,9 @@ dependencies = [
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3"
dependencies = [
"cc",
"pkg-config",
@@ -2215,6 +2189,7 @@ dependencies = [
"hex",
"openssl",
"prost",
"reqwest",
"rmm-domain",
"rmm-protocol",
"rmm-updater-handoff",
@@ -2239,7 +2214,7 @@ dependencies = [
[[package]]
name = "rmm-agent-windows"
version = "0.1.0"
version = "0.1.16"
dependencies = [
"anyhow",
"base64 0.22.1",
@@ -2315,7 +2290,9 @@ name = "rmm-persistence"
version = "0.1.0"
dependencies = [
"anyhow",
"sqlx",
"sqlx-core",
"sqlx-macros",
"sqlx-postgres",
"uuid",
]
@@ -2538,17 +2515,27 @@ dependencies = [
]
[[package]]
name = "rusqlite"
version = "0.32.1"
name = "rsqlite-vfs"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7"
dependencies = [
"thiserror",
]
[[package]]
name = "rusqlite"
version = "0.41.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink 0.9.1",
"hashlink 0.12.2",
"libsqlite3-sys",
"smallvec",
"sqlite-wasm-rs",
]
[[package]]
@@ -2871,9 +2858,6 @@ name = "spin"
version = "0.9.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"
dependencies = [
"lock_api",
]
[[package]]
name = "spki"
@@ -2885,6 +2869,16 @@ dependencies = [
"der",
]
[[package]]
name = "sqlite-wasm-rs"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867"
dependencies = [
"cc",
"rsqlite-vfs",
]
[[package]]
name = "sqlx"
version = "0.8.6"
@@ -2893,9 +2887,7 @@ checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
dependencies = [
"sqlx-core",
"sqlx-macros",
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
]
[[package]]
@@ -2966,58 +2958,12 @@ dependencies = [
"serde_json",
"sha2 0.10.9",
"sqlx-core",
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
"syn 2.0.119",
"tokio",
"url",
]
[[package]]
name = "sqlx-mysql"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"
dependencies = [
"atoi",
"base64 0.22.1",
"bitflags",
"byteorder",
"bytes",
"chrono",
"crc",
"digest 0.10.7",
"dotenvy",
"either",
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"generic-array",
"hex",
"hkdf",
"hmac",
"itoa",
"log",
"md-5",
"memchr",
"once_cell",
"percent-encoding",
"rand 0.8.8",
"rsa",
"serde",
"sha1",
"sha2 0.10.9",
"smallvec",
"sqlx-core",
"stringprep",
"thiserror",
"tracing",
"uuid",
"whoami",
]
[[package]]
name = "sqlx-postgres"
version = "0.8.6"
@@ -3057,32 +3003,6 @@ dependencies = [
"whoami",
]
[[package]]
name = "sqlx-sqlite"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea"
dependencies = [
"atoi",
"chrono",
"flume",
"futures-channel",
"futures-core",
"futures-executor",
"futures-intrusive",
"futures-util",
"libsqlite3-sys",
"log",
"percent-encoding",
"serde",
"serde_urlencoded",
"sqlx-core",
"thiserror",
"tracing",
"url",
"uuid",
]
[[package]]
name = "sse-stream"
version = "0.2.6"
+2 -1
View File
@@ -18,13 +18,14 @@ openssl = "0.10.75"
prost = "0.14.1"
rand = "0.9.2"
reqwest = { version = "0.12.24", default-features = false, features = ["rustls-tls", "json"] }
rusqlite = { version = "0.41.1", features = ["bundled", "fallible_uint"] }
rustls = { version = "0.23.35", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2.2.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.145"
sha2 = "0.10.9"
schemars = { version = "1", features = ["chrono04", "uuid1"] }
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres", "uuid", "chrono", "json", "migrate", "macros"] }
sqlx = { version = "0.8.6", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
tokio = { version = "1.48.0", features = ["full"] }
tokio-rustls = { version = "0.26.4", default-features = false, features = ["ring", "tls12"] }
tokio-tungstenite = { version = "0.28.0", features = ["rustls-tls-webpki-roots"] }
+16 -14
View File
@@ -1,22 +1,24 @@
# Rust Discovery
Rust Discovery verwaltet Linux- und Windows-Geräte über einen dedizierten Server mit WebUI und MCP. Die Clients melden sich ausgehend per HTTPS, liefern Inventar und Heartbeats, holen genehmigte Skripte ab und melden ihre Ergebnisse zurück. Wiederkehrende Aufgaben lassen sich als versionierte Skripte hinterlegen. Neue Geräte werden über einen HTTPS-Installer aufgenommen und beziehen signierte Agentupdates vom Server.
Rust Discovery ist eine Remote-Monitoring- und Management-Plattform für Linux- und Windows-Geräte. Der Server verwaltet Kunden, Geräte, Skripte und Aufträge. Die Agenten melden sich von den Geräten aus, liefern Inventar und Heartbeats, holen genehmigte Skripte ab und melden die Ausgabe zurück.
**[Aktueller Stand und Schritt-für-Schritt-Plan](docs/mvp-completion-plan.md)** · [Entwicklungsbefehle](docs/development.md) · [Übergabe und Zugänge](docs/handover.md)
**Der MVP ist abgenommen.** Auf Ubuntu und Windows 11 wurden ein eigenes Administrator-Skript, eine Skriptversion aus der Bibliothek, ein echter Neustart und ein weiterer Auftrag nach der Wiederanmeldung geprüft. Die Abnahme enthält die Ausgaben und den installierten Stand beider Geräte. [MVP-Abnahme](docs/mvp-completion-plan.md)
## Stand am 17. November 2026
## Von der Geräteauswahl zum Ergebnis
Die beiden über den öffentlichen Installer aufgenommenen Geräte haben ein Bibliotheksskript mit Exitcode 0 zurückgemeldet. WebUI und MCP zeigen das Ergebnis desselben Versuchs. Der Linux-Timer und der Windows-Updaterdienst haben auf den Testgästen selbstständig veröffentlichte Versionen übernommen. Die integrierte Windows-Update-Vorlage erfordert gesondert eingerichtete Wartungsrechte. [Aktueller Prüfstand](docs/mvp-completion-plan.md)
1. In der WebUI den Kunden und unter **Geräte** die Zielmaschine auswählen.
2. Unter **Aufträge** ein eigenes Skript eingeben oder eine feste Version aus **Skripte** auswählen. Ausführungskonto und Zeitfenster prüfen und den Auftrag einreichen.
3. Unter **Genehmigungen** prüft eine berechtigte Person den Skriptinhalt und die Ziele und entscheidet über die Ausführung.
4. Unter **Aufträge** den Auftrag öffnen und pro Gerät Ergebnis, Ausgabe und Exitcode lesen. Über das Gerätedetail sind seine letzten Aufträge ebenfalls erreichbar.
## Einstieg in den Code
MCP kann Skriptversionen veröffentlichen, eigene Skripte und Bibliotheksversionen für berechtigte Kunden einreichen sowie Ergebnisse lesen. Die persönliche Genehmigung erfolgt in der WebUI. [WebUI öffnen](https://discovery.ease-technologies.de:8443/) · [Zugang und MCP-Rechte](docs/public-access.md)
| Aufgabe | Einstieg |
## Einstieg ins Projekt
| Ich möchte … | Einstieg |
| --- | --- |
| Verwaltungs-API, UI und MCP | [Server-Routen](crates/server/src/main.rs), [MCP-Werkzeuge](crates/server/src/mcp.rs), [WebUI](web/src/main.tsx) |
| Gerätekommunikation und Jobs | [HTTPS-Poll](crates/server/src/agent_http.rs), [Jobzustellung](crates/server/src/job_gateway.rs), [gemeinsamer Agentkern](crates/agent-core/src/lib.rs) |
| Linux- und Windows-Dienst | [Linux-Agent](crates/agent/src/main.rs), [Windows-Laufzeit](crates/agent-windows/src/runtime.rs) |
| Releases und Selbstupdate | [Releasekatalog und Downloads](crates/server/src/agent_updates.rs), [Manifestprüfung](crates/updater/src/manifest.rs) |
Der Server läuft auf `discovery.ease-technologies.de`. Die [öffentliche WebUI](https://discovery.ease-technologies.de:8443/) verwendet Passwort und TOTP. Der [MCP-Endpunkt](https://discovery.ease-technologies.de:8443/mcp) verwendet eigene Bearer-Tokens. [Einrichtung und Betrieb](docs/public-access.md) Die Cloud-Linux-VM und der Windows-11-Gast dienen als Testgeräte. Das Notebook ist der Entwicklungsrechner.
[Agenthinweise](AGENTS.md) · [Spezifikation](Rust_RMM_Implementierungsspezifikation.md) · [Entscheidungen](docs/project-decisions.md) · [Historische Linux-Abnahme](docs/mvp-final-audit.md) · [Windows-Nachweise](docs/windows-gates.md)
| einen Entwicklungsauftrag übernehmen | [Agenthinweise](AGENTS.md) und [Übergabe](docs/handover.md) |
| den Funktionsumfang und die Grenzen des MVP verstehen | [Produktvertrag](Rust_RMM_Implementierungsspezifikation.md) |
| ein Gerät aufnehmen oder einen Agenten aktualisieren | [Linux](deploy/linux/README.md) oder [Windows](deploy/windows/README.md) |
| eine Änderung bauen, testen oder bereitstellen | [Entwicklung und Deployment](docs/development.md) |
| einen Betriebsvorgang auf dem Testsystem prüfen | [Betriebszugänge](docs/operations-access.md) und [Abnahmebelege](docs/mvp-completion-plan.md) |
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -19,7 +19,8 @@ uuid.workspace = true
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
rmm-updater-handoff = { path = "../updater-handoff" }
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
reqwest.workspace = true
ed25519-dalek = "=2.2.0"
[dev-dependencies]
@@ -62,7 +62,7 @@ impl Snapshot {
let db = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)?;
db.execute_batch("PRAGMA query_only=ON; PRAGMA trusted_schema=OFF; BEGIN;")?;
ensure!(
db.is_readonly(rusqlite::DatabaseName::Main)?,
db.is_readonly(rusqlite::MAIN_DB)?,
"read-only database required"
);
Ok(Self { db, _held: handles })
+391
View File
@@ -0,0 +1,391 @@
//! A handoff changes the installation, not the old journal or its trust.
use anyhow::{Context, Result, ensure};
use ed25519_dalek::{Signature, VerifyingKey};
use reqwest::Client;
use rmm_domain::customer_transfer::{CertificateRequest, CertificateResponse, Offer};
use rmm_protocol::EnrollmentResponse;
use serde::{Deserialize, de::DeserializeOwned};
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
path::{Path, PathBuf},
time::Duration,
};
use uuid::Uuid;
const PREFIX: &str = "customer-move-";
const INTENT: &str = "customer-move-intent.json";
const MAX_RECORD: usize = 32768;
pub fn idle(journal: &rusqlite::Connection, ledger: &rusqlite::Connection) -> Result<bool> {
let busy: bool = journal.query_row(
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN (
'accepted','requesting','running','verifying','unknown','awaiting_reboot'))",
[],
|row| row.get(0),
)?;
let consumed: bool = ledger.query_row(
"SELECT EXISTS(SELECT 1 FROM consumed WHERE result IS NULL)",
[],
|row| row.get(0),
)?;
// The new customer executes under the same service account. Retire
// local history only after the old installation has delivered its work.
if busy || consumed {
return Ok(false);
}
Ok(crate::jobs::events(journal)?.iter().all(|event| {
matches!(
event.payload,
Some(rmm_protocol::Payload::InventorySnapshot(_))
)
}))
}
fn read(path: &Path) -> Result<Vec<u8>> {
let info = fs::symlink_metadata(path)?;
ensure!(
info.is_file() && !info.file_type().is_symlink() && info.len() <= MAX_RECORD as u64,
"TRANSFER_RECORD"
);
let mut data = Vec::new();
File::open(path)?
.take(MAX_RECORD as u64 + 1)
.read_to_end(&mut data)?;
ensure!(data.len() <= MAX_RECORD, "TRANSFER_RECORD");
Ok(data)
}
fn sync_dir(path: &Path) -> Result<()> {
#[cfg(unix)]
File::open(path)?.sync_all()?;
#[cfg(not(unix))]
let _ = path;
Ok(())
}
fn publish(path: &Path, bytes: &[u8]) -> Result<()> {
if path.try_exists()? {
ensure!(read(path)? == bytes, "TRANSFER_RECORD_CONFLICT");
return Ok(());
}
let dir = path.parent().context("TRANSFER_RECORD_PARENT")?;
let temporary = dir.join(format!("{PREFIX}tmp-{}", Uuid::new_v4()));
let result = (|| {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options.open(&temporary)?;
file.write_all(bytes)?;
file.sync_all()?;
drop(file);
fs::rename(&temporary, path)?;
sync_dir(dir)
})();
if result.is_err() {
let _ = fs::remove_file(temporary);
}
result
}
fn file(dir: &Path, id: Uuid, role: &str) -> PathBuf {
dir.join(format!("{PREFIX}{id}-{role}"))
}
fn verify(response: &CertificateResponse, signer: &str) -> Result<()> {
let binding = &response.receipt.binding;
let signature = Signature::from_slice(&hex::decode(&response.receipt.signature_hex)?)?;
let public: [u8; 32] = hex::decode(signer)?
.try_into()
.map_err(|_| anyhow::anyhow!("TRANSFER_SIGNER"))?;
VerifyingKey::from_bytes(&public)?.verify_strict(&binding.signing_bytes()?, &signature)?;
ensure!(
binding.offer.source_tenant_id != binding.offer.target_tenant_id
&& binding.agent_id != binding.offer.source_agent_id
&& !binding.agent_id.is_nil()
&& !binding.asset_id.is_nil()
&& binding.certificate_sha256
== rmm_domain::jobs::hash(response.certificate_pem.as_bytes()),
"TRANSFER_BINDING"
);
Ok(())
}
async fn json<T: DeserializeOwned>(mut response: reqwest::Response) -> Result<T> {
ensure!(response.status().is_success(), "TRANSFER_HTTP");
let mut bytes = Vec::new();
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= MAX_RECORD,
"TRANSFER_RESPONSE_SIZE"
);
bytes.extend_from_slice(&chunk);
}
Ok(serde_json::from_slice(&bytes)?)
}
pub async fn stage(
client: &Client,
origin: &str,
dir: &Path,
current: &crate::auth::Binding,
key_and_csr: impl FnOnce(Option<&[u8]>) -> Result<(Vec<u8>, String)>,
) -> Result<bool> {
#[derive(Deserialize)]
struct Response {
offer: Option<Offer>,
}
let route = format!("{origin}/agent/v1/customer-transfer");
let response = client
.get(&route)
.timeout(Duration::from_secs(4))
.send()
.await?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(false); // agent updates can precede the server upgrade
}
let Some(offer) = json::<Response>(response).await?.offer else {
return Ok(false);
};
ensure!(
offer.source_agent_id == current.agent_id
&& offer.source_tenant_id == current.tenant_id
&& offer.target_tenant_id != current.tenant_id
&& !offer.transfer_id.is_nil(),
"TRANSFER_SOURCE"
);
let id = offer.transfer_id;
let key_path = file(dir, id, "key.pem");
let previous = key_path
.try_exists()?
.then(|| read(&key_path))
.transpose()?;
let (key, csr_pem) = key_and_csr(previous.as_deref())?;
publish(&key_path, &key)?;
let response = json::<CertificateResponse>(
client
.post(format!("{route}/{id}/certificate"))
.timeout(Duration::from_secs(10))
.json(&CertificateRequest { csr_pem })
.send()
.await?,
)
.await?;
verify(&response, &current.public_key_hex)?;
ensure!(
response.receipt.binding.offer == offer,
"TRANSFER_OFFER_CHANGED"
);
publish(
&file(dir, id, "response.json"),
&serde_json::to_vec(&response)?,
)?;
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
Ok(true)
}
fn archive(dir: &Path, id: Uuid) -> Result<()> {
for item in fs::read_dir(dir)? {
let item = item?;
let name = item.file_name();
if name.to_string_lossy().starts_with(PREFIX)
|| ["agent.lock", "job-signing-key.json"]
.iter()
.any(|kept| name == *kept)
{
continue;
}
if name == "jobs" && item.file_type()?.is_dir() {
// Keep the installer-owned directory and its Windows ACL.
archive(&item.path(), id)?;
continue;
}
let mut backup = std::ffi::OsString::from(format!("{PREFIX}{id}-prior-"));
backup.push(name);
let target = dir.join(backup);
ensure!(!target.try_exists()?, "TRANSFER_ARCHIVE_EXISTS");
fs::rename(item.path(), target)?;
}
sync_dir(dir)
}
fn retire_prior_state(dir: &Path, id: Uuid) -> Result<()> {
let prefix = format!("{PREFIX}{id}-prior-");
for item in fs::read_dir(dir)? {
let item = item?;
let name = item.file_name();
if name == "jobs" && item.file_type()?.is_dir() {
retire_prior_state(&item.path(), id)?;
} else if name.to_string_lossy().starts_with(&prefix) {
if item.file_type()?.is_dir() {
fs::remove_dir_all(item.path())?;
} else {
fs::remove_file(item.path())?;
}
}
}
sync_dir(dir)
}
pub fn pending(dir: &Path) -> Result<bool> {
Ok(dir.join(INTENT).try_exists()?)
}
pub fn activate(dir: &Path, signer: &str) -> Result<()> {
let intent = dir.join(INTENT);
if !intent.try_exists()? {
return Ok(());
}
let id: Uuid = serde_json::from_slice(&read(&intent)?)?;
let response_file = file(dir, id, "response.json");
let data = read(&response_file)?;
let response: CertificateResponse = serde_json::from_slice(&data)?;
let binding = &response.receipt.binding;
verify(&response, signer)?;
ensure!(binding.offer.transfer_id == id, "TRANSFER_INTENT");
let relocated = file(dir, id, "relocated");
if !relocated.try_exists()? {
let current: EnrollmentResponse =
serde_json::from_slice(&read(&dir.join("identity.json")).or_else(|error| {
let backup = file(dir, id, "prior-identity.json");
if backup.exists() {
read(&backup)
} else {
Err(error)
}
})?)?;
ensure!(
current.agent_id == binding.offer.source_agent_id.to_string(),
"TRANSFER_SOURCE"
);
archive(dir, id)?;
publish(&relocated, b"ok")?;
}
let key_file = file(dir, id, "key.pem");
let identity = EnrollmentResponse {
agent_id: binding.agent_id.to_string(),
asset_id: binding.asset_id.to_string(),
certificate_pem: response.certificate_pem,
};
publish(&dir.join("device.key"), &read(&key_file)?)?;
publish(&dir.join("device.pem"), identity.certificate_pem.as_bytes())?;
publish(&dir.join("identity.json"), &serde_json::to_vec(&identity)?)?;
publish(&file(dir, binding.agent_id, "active.json"), &data)?;
// Do not expose old-tenant credentials or job outputs to scripts running
// under this same local service account in the new tenant.
retire_prior_state(dir, id)?;
fs::remove_file(intent)?;
sync_dir(dir)?;
// The live private key is durable. This copy only existed for upload retry.
let _ = fs::remove_file(key_file);
let _ = fs::remove_file(response_file);
let _ = fs::remove_file(relocated);
Ok(())
}
pub fn assigned_tenant(
dir: &Path,
identity: &EnrollmentResponse,
signer: &str,
) -> Result<Option<Uuid>> {
let path = file(dir, Uuid::parse_str(&identity.agent_id)?, "active.json");
if !path.try_exists()? {
return Ok(None);
}
let response: CertificateResponse = serde_json::from_slice(&read(&path)?)?;
verify(&response, signer)?;
let binding = response.receipt.binding;
ensure!(
response.certificate_pem == identity.certificate_pem
&& binding.agent_id.to_string() == identity.agent_id
&& binding.asset_id.to_string() == identity.asset_id,
"TRANSFER_ACTIVE_IDENTITY"
);
Ok(Some(binding.offer.target_tenant_id))
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::{Signer, SigningKey};
use rmm_domain::customer_transfer::{Binding, Receipt};
#[test]
fn authenticated_handoff_recovers_partial_archive_and_isolates_local_state() -> Result<()> {
let dir = std::env::temp_dir().join(format!("rmm-transfer-{}", Uuid::new_v4()));
fs::create_dir(&dir)?;
let result = (|| {
let id = Uuid::new_v4();
let source = Uuid::new_v4();
let target = Uuid::new_v4();
let previous = EnrollmentResponse {
agent_id: source.to_string(),
asset_id: Uuid::new_v4().to_string(),
certificate_pem: "old certificate fixture".into(),
};
publish(&dir.join("identity.json"), &serde_json::to_vec(&previous)?)?;
publish(&dir.join("device.key"), b"old key")?;
publish(&dir.join("journal.sqlite"), b"old journal")?;
let signer = SigningKey::from_bytes(&[7; 32]);
let public = hex::encode(signer.verifying_key().as_bytes());
let certificate_pem = "new certificate fixture".to_string();
let binding = Binding {
offer: Offer {
transfer_id: id,
source_agent_id: source,
source_tenant_id: Uuid::new_v4(),
target_tenant_id: Uuid::new_v4(),
},
asset_id: Uuid::new_v4(),
agent_id: target,
certificate_sha256: rmm_domain::jobs::hash(certificate_pem.as_bytes()),
};
let tenant = binding.offer.target_tenant_id;
let mut response = CertificateResponse {
certificate_pem,
receipt: Receipt {
signature_hex: hex::encode(signer.sign(&binding.signing_bytes()?).to_bytes()),
binding,
},
};
publish(&file(&dir, id, "key.pem"), b"new key")?;
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
response.receipt.binding.offer.target_tenant_id = Uuid::new_v4();
fs::write(
file(&dir, id, "response.json"),
serde_json::to_vec(&response)?,
)?;
assert!(activate(&dir, &public).is_err());
assert_eq!(fs::read(dir.join("device.key"))?, b"old key");
response.receipt.binding.offer.target_tenant_id = tenant;
fs::write(
file(&dir, id, "response.json"),
serde_json::to_vec(&response)?,
)?;
// Simulate a stop immediately after relocating the first original file.
fs::rename(
dir.join("identity.json"),
file(&dir, id, "prior-identity.json"),
)?;
activate(&dir, &public)?;
activate(&dir, &public)?;
assert!(!pending(&dir)?);
assert!(!file(&dir, id, "prior-identity.json").exists());
assert!(!file(&dir, id, "prior-device.key").exists());
assert!(!file(&dir, id, "prior-journal.sqlite").exists());
assert_eq!(fs::read(dir.join("device.key"))?, b"new key");
let active: EnrollmentResponse =
serde_json::from_slice(&read(&dir.join("identity.json"))?)?;
assert_eq!(active.agent_id, target.to_string());
assert_eq!(assigned_tenant(&dir, &active, &public)?, Some(tenant));
Ok(())
})();
fs::remove_dir_all(dir)?;
result
}
}
+39 -15
View File
@@ -782,10 +782,10 @@ impl<V: Ed25519Verifier> HelperSync<V> {
let d = decisions
.get(&id)
.context("ROOT_ATTEMPT_OMITTED_FROM_DECISION")?;
validate_summary(row, local)?;
validate_decision(row, local, d)?;
let unreported = validate_summary(row, local)?;
validate_decision(row, local, d, unreported)?;
if d.unlock {
let bytes = unlock_outcome(row, d, current_boot)?;
let bytes = unlock_outcome(row, d, current_boot, unreported.then_some(local))?;
if d.outcome_state == "closed_unknown" {
crate::ledger::retain_closure_original(
&tx,
@@ -1636,22 +1636,33 @@ fn definitive(row: &LocalAttempt) -> bool {
"succeeded" | "failed" | "cancelled" | "expired" | "closed_unknown"
) && !row.outcome_bytes.is_empty()
}
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<()> {
fn validate_summary(row: &LocalAttempt, a: &AttemptView) -> Result<bool> {
let unreported = row.state == "unknown"
&& row.outcome_sha256.is_empty()
&& row.outcome_bytes.is_empty()
&& row.update_handoff_bytes.is_empty()
&& crate::reconcile::uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
ensure!(
a.job_payload_hash == row.job_payload_hash
&& a.grant_id == row.grant_id.to_string()
&& a.consumption == "consumed"
&& a.state == row.state
&& a.revision >= row.revision
&& a.original_boot_id == row.original_boot_id.to_string()
&& a.outcome_sha256 == row.outcome_sha256
&& a.update_handoff_bytes == row.update_handoff_bytes
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes),
&& (unreported
|| (a.state == row.state
&& a.outcome_sha256 == row.outcome_sha256
&& (a.outcome_bytes.is_empty() || a.outcome_bytes == row.outcome_bytes))),
"ROOT_SNAPSHOT_REQUEST_MISMATCH"
);
Ok(())
Ok(unreported)
}
fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -> Result<()> {
fn validate_decision(
row: &LocalAttempt,
a: &AttemptView,
d: &AttemptDecision,
unreported: bool,
) -> Result<()> {
if !row.update_handoff_bytes.is_empty() {
let proof =
rmm_domain::agent_update::UpdateInflightProof::from_bytes(&row.update_handoff_bytes)
@@ -1686,7 +1697,7 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
&& d.original_boot_id == Some(row.original_boot_id)
&& (d.revision >= a.revision || (!d.unlock && d.outcome_state == "unknown"))
&& d.previous_outcome_sha256.as_deref()
== (!row.outcome_sha256.is_empty()).then_some(row.outcome_sha256.as_str()),
== (!a.outcome_sha256.is_empty()).then_some(a.outcome_sha256.as_str()),
"ROOT_SIGNED_ATTEMPT_BINDING"
);
ensure!(
@@ -1697,11 +1708,26 @@ fn validate_decision(row: &LocalAttempt, a: &AttemptView, d: &AttemptDecision) -
),
"UNKNOWN_CANNOT_UNLOCK"
);
ensure!(
!unreported
|| (!d.unlock && d.outcome_state == "unknown")
|| (d.unlock
&& d.outcome_state == "closed_unknown"
&& d.reason == "OPERATOR_CLOSED_UNKNOWN"),
"ROOT_UNREPORTED_OUTCOME_CLOSURE_REQUIRED"
);
Ok(())
}
fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -> Result<Vec<u8>> {
fn unlock_outcome(
row: &LocalAttempt,
d: &AttemptDecision,
current_boot: Uuid,
unreported: Option<&AttemptView>,
) -> Result<Vec<u8>> {
let bytes = if d.outcome_bytes.is_empty() {
row.outcome_bytes.clone()
unreported
.map_or(&row.outcome_bytes, |a| &a.outcome_bytes)
.clone()
} else {
d.outcome_bytes.clone()
};
@@ -1712,9 +1738,7 @@ fn unlock_outcome(row: &LocalAttempt, d: &AttemptDecision, current_boot: Uuid) -
&& o.state == d.outcome_state,
"ROOT_CANONICAL_UNLOCK_OUTCOME"
);
if bytes != row.outcome_bytes
&& crate::reconcile::operator_closure(&d.reason, &row.state, &o)
{
if bytes != row.outcome_bytes && crate::reconcile::operator_closure(&d.reason, &row.state, &o) {
return Ok(bytes);
}
if bytes != row.outcome_bytes {
+3 -1
View File
@@ -24,7 +24,6 @@ pub fn accept(
&& hex_hash(&offer.plan_hash),
"OFFER_BINDING"
);
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let bytes = offer.encode_to_vec();
let existing: Option<Vec<u8>> = db
.query_row(
@@ -37,6 +36,9 @@ pub fn accept(
ensure!(old == bytes, "OFFER_CONFLICT");
return Ok(false);
}
// An identical journal receipt is evidence of a previous delivery. Current
// executable capabilities apply to newly accepted offers.
ensure!(supported(&job), "UNSUPPORTED_CAPABILITY");
let count: i64 = db.query_row("SELECT count(*) FROM job_attempts", [], |r| r.get(0))?;
ensure!(count < 10000, "JOURNAL_CAPACITY_NEW_EFFECTS_BLOCKED");
db.execute(
+1
View File
@@ -3,6 +3,7 @@
//! Callers must authenticate their transport, protect/lock their own journals and
//! supply a qualified clock. A successful signature is never UI approval itself.
pub mod auth;
pub mod customer_transfer;
pub mod crypto;
pub mod helper_reconcile;
pub mod jobs;
+198 -15
View File
@@ -365,7 +365,6 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& original.helper_previous_decision_id == h.to_string()
&& original.previous_request_id.is_empty()
&& original.journal_complete
&& original.durable_message_ids.is_empty()
&& decision.issued_at <= now
&& decision.connection_generation <= channel.connection_generation
&& previous.connection_generation <= decision.connection_generation
@@ -379,6 +378,7 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&& helper.checkpoint >= decision.helper_checkpoint,
"CLOSED_CONTROL_EXACT_PARTIAL_EDGE"
);
verify_closed_result_messages(db, &original, &decision)?;
let current = attempts(db, ledger, &self.binding)?;
ensure!(
current.len() == original.attempts.len()
@@ -399,7 +399,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
);
for row in &current {
ensure!(
terminal(&row.state) && row.update_handoff_bytes.is_empty(),
matches!(row.state.as_str(), "succeeded" | "failed" | "cancelled" | "expired")
&& row.update_handoff_bytes.is_empty(),
"CLOSED_CONTROL_DEFINITIVE_ONLY"
);
let old = original
@@ -1018,9 +1019,9 @@ impl<V: Ed25519Verifier> ClientSync<V> {
} else {
for d in decision.attempts.iter().filter(|d| d.unlock) {
let grant = d.grant_id.context("UNLOCK_GRANT_MISSING")?;
let (agent,generation,job,attempt,previous):(String,u64,String,String,Option<Vec<u8>>)=tx.query_row(
"SELECT agent,generation,job,attempt,COALESCE((SELECT outcome FROM execution_evidence WHERE execution_evidence.grant_id=consumed.grant_id),result) FROM consumed WHERE grant_id=?1",
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?)))?;
let (agent,generation,job,attempt,previous,start):(String,u64,String,String,Option<Vec<u8>>,Option<Vec<u8>>)=tx.query_row(
"SELECT c.agent,c.generation,c.job,c.attempt,COALESCE(e.outcome,c.result),e.start FROM consumed c LEFT JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
[grant.to_string()],|r|Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?)))?;
ensure!(
agent == self.binding.agent_id.to_string()
&& generation == self.binding.enrollment_generation
@@ -1033,13 +1034,61 @@ impl<V: Ed25519Verifier> ClientSync<V> {
Some(&self.binding),
grant,
)?;
let previous = resolved
.or(previous)
.context("LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING")?;
let original = previous.clone();
let prior = canonical_outcome_bytes(&serde_json::from_slice::<ReconciledOutcome>(
&previous,
)?)?;
let previous = resolved.or(previous);
let summary = gate
.request
.attempts
.iter()
.find(|a| a.job_id == job && a.attempt_id == attempt)
.context("LOCAL_UNLOCK_ATTEMPT_MISSING")?;
let closure = d.reason == "OPERATOR_CLOSED_UNKNOWN"
&& d.outcome_state == "closed_unknown"
&& summary.consumption == "consumed"
&& uncertain_agent_outcome(
&summary.state,
&summary.outcome_bytes,
&summary.outcome_sha256,
);
let prior = match &previous {
Some(bytes) => {
let canonical = canonical_outcome_bytes(&serde_json::from_slice(bytes)?)?;
if closure
&& summary.state == "closed_unknown"
&& uncertain_agent_outcome("unknown", &canonical, &hash(&canonical))
{
summary.outcome_bytes.clone()
} else {
canonical
}
}
None => {
ensure!(closure, "LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISSING");
let start: serde_json::Value = serde_json::from_slice(
&start.context("LOCAL_UNLOCK_ORIGINAL_START_MISSING")?,
)?;
let request: crate::auth::Request =
serde_json::from_value(start["request"].clone())?;
let permit: rmm_domain::jobs::ExecutionPermitPayload =
serde_json::from_slice(&request.permit_bytes)?;
let (original, permit) = self.binding.verify_with(
&request,
permit.not_before,
&self.verifier,
)?;
ensure!(
permit.grant_id == grant
&& original.job_id == d.job_id
&& original.attempt_id == d.attempt_id
&& hash(&request.job_bytes) == d.job_payload_hash
&& Some(permit.authorization_id) == d.authorization_id
&& Some(permit.plan_hash.as_str()) == d.plan_hash.as_deref()
&& start["previous_boot_id"].as_str()
== d.original_boot_id.map(|id| id.to_string()).as_deref(),
"LOCAL_UNLOCK_ORIGINAL_START_BINDING"
);
summary.outcome_bytes.clone()
}
};
ensure!(
d.previous_outcome_sha256.as_deref() == Some(hash(&prior).as_str()),
"LOCAL_UNLOCK_PREVIOUS_OUTCOME_MISMATCH"
@@ -1054,7 +1103,8 @@ impl<V: Ed25519Verifier> ClientSync<V> {
terminal(&outcome.state)
&& outcome.state == d.outcome_state
&& canonical_outcome_bytes(&outcome)? == bytes
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str()),
&& d.outcome_sha256.as_deref() == Some(hash(&bytes).as_str())
&& (previous.is_some() || operator_closure(&d.reason, "unknown", &outcome)),
"LOCAL_UNLOCK_CANONICAL_OUTCOME"
);
let preserve = crate::windows_system_nonstart::preserve_original_unlock(
@@ -1064,7 +1114,12 @@ impl<V: Ed25519Verifier> ClientSync<V> {
&bytes,
)?;
if outcome.state == "closed_unknown" {
crate::ledger::retain_closure_original(&tx, grant, &original, &bytes)?;
crate::ledger::retain_closure_original(
&tx,
grant,
previous.as_deref().unwrap_or_default(),
&bytes,
)?;
}
tx.execute(
"UPDATE consumed SET result=?2 WHERE grant_id=?1",
@@ -1170,6 +1225,81 @@ pub fn archive_events(db: &Connection) -> Result<()> {
}
Ok(())
}
/// A partial control edge can contain the result that closed an attempt, and
/// an earlier unknown report for that same grant. Only account for archived
/// messages here. Never ACK an event, change its state or replay a result.
fn verify_closed_result_messages(
db: &Connection,
request: &SyncRequest,
decision: &ReconcileDecisionPayload,
) -> Result<()> {
for id in &request.durable_message_ids {
let raw: Vec<u8> = db.query_row(
"SELECT envelope FROM reconcile_results WHERE id=?1",
[id],
|r| r.get(0),
)?;
let envelope = Envelope::decode(raw.as_slice())?;
let Some(Payload::JobResult(result)) = &envelope.payload else {
anyhow::bail!("CLOSED_CONTROL_EXPECTED_RESULT");
};
let attempt = request
.attempts
.iter()
.find(|a| {
a.job_id == result.job_id
&& a.attempt_id == result.attempt_id
&& a.grant_id == result.grant_id
})
.context("CLOSED_CONTROL_ARCHIVED_ATTEMPT")?;
let final_envelope = attempt
.result_envelope
.as_ref()
.context("CLOSED_CONTROL_FINAL_ENVELOPE")?;
let final_id = Uuid::parse_str(&attempt.result_message_id)?;
let persisted: bool = db.query_row(
"SELECT EXISTS(SELECT 1 FROM reconcile_receipts WHERE id=?1 AND decision_id=?2)",
params![attempt.result_message_id, decision.decision_id.to_string()],
|r| r.get(0),
)?;
ensure!(
persisted
&& decision.acknowledged_message_ids.contains(&final_id)
&& request
.durable_message_ids
.contains(&attempt.result_message_id)
&& final_envelope.message_id == attempt.result_message_id
&& envelope.message_id == *id
&& envelope.encode_to_vec() == raw
&& rmm_protocol::valid_envelope(
&envelope,
&decision.agent_id.to_string(),
final_envelope.connection_generation
)
&& envelope.boot_id == final_envelope.boot_id
&& matches!(
attempt.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired"
)
&& !result.grant_id.is_empty(),
"CLOSED_CONTROL_FINAL_RESULT_RECEIPT"
);
ensure!(
if *id == attempt.result_message_id {
envelope == *final_envelope
&& result.revision == attempt.revision
&& result.state == attempt.state
&& canonical_outcome_bytes(&outcome(result)?)? == attempt.outcome_bytes
} else {
result.state == "unknown"
&& result.revision < attempt.revision
&& envelope.sequence < final_envelope.sequence
},
"CLOSED_CONTROL_CONFLICTING_ARCHIVED_RESULT"
);
}
Ok(())
}
fn pending_ids(db: &Connection) -> Result<Vec<String>> {
let mut statement = db.prepare("SELECT id,payload FROM job_events ORDER BY id")?;
let rows = statement
@@ -1228,6 +1358,32 @@ pub(crate) fn operator_closure(
&& outcome.evidence["closed_by_human"] == true
&& outcome.evidence["retry"] == false
}
/// An interrupted agent can record its own uncertainty while the independently
/// consumed helper grant has no result. Neither witness establishes an effect.
pub(crate) fn uncertain_agent_outcome(state: &str, bytes: &[u8], digest: &str) -> bool {
if bytes.is_empty() || hash(bytes) != digest {
return false;
}
let Ok(outcome) = serde_json::from_slice::<ReconciledOutcome>(bytes) else {
return false;
};
canonical_outcome_bytes(&outcome).is_ok_and(|canonical| canonical == bytes)
&& outcome.state == state
&& !outcome.output_truncated
&& !outcome.reboot_required
&& (operator_closure("OPERATOR_CLOSED_UNKNOWN", "unknown", &outcome)
|| (state == "unknown"
&& matches!(
outcome.error_code.as_str(),
"AGENT_PROCESS_INTERRUPTED" | "HELPER_TRANSPORT_EFFECT_UNKNOWN"
)
&& outcome.exit_code.is_none()
&& outcome.stdout.is_empty()
&& outcome.stderr.is_empty()
&& outcome.evidence["postconditions_passed"] == false))
}
fn optional_uuid(s: &str) -> Result<Option<Uuid>> {
if s.is_empty() {
Ok(None)
@@ -1376,6 +1532,24 @@ fn attempts(db: &Connection, ledger: &Connection, binding: &Binding) -> Result<V
result_envelope = Some(envelope);
}
}
// The signed closure projection can commit before either consumption
// ledger. A fresh signed check may then finish the remaining writes.
if state == "closed_unknown"
&& consumption == "consumed"
&& (canonical.is_empty()
|| uncertain_agent_outcome("unknown", &canonical, &hash(&canonical)))
{
let closed: Vec<u8> = db.query_row(
"SELECT outcome FROM reconcile_outcomes WHERE job=?1 AND attempt=?2",
params![offer.job_id, offer.attempt_id],
|r| r.get(0),
)?;
ensure!(
uncertain_agent_outcome(&state, &closed, &hash(&closed)),
"LOCAL_CLOSURE_OUTCOME_MISMATCH"
);
canonical = closed;
}
if !canonical.is_empty() {
let o: ReconciledOutcome = serde_json::from_slice(&canonical)?;
ensure!(o.state == state, "LOCAL_OUTCOME_STATE_MISMATCH");
@@ -1670,6 +1844,15 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
"HELPER_ATTEMPT_BINDING"
);
if h.consumption != "unconsumed" {
let unreported = h.state == "unknown"
&& h.consumption == "consumed"
&& h.outcome_bytes.is_empty()
&& h.outcome_sha256.is_empty()
&& h.update_handoff_bytes.is_empty()
&& a.consumption == "consumed"
&& a.grant_id == h.grant_id
&& a.original_boot_id == h.original_boot_id
&& uncertain_agent_outcome(&a.state, &a.outcome_bytes, &a.outcome_sha256);
if !h.update_handoff_bytes.is_empty() {
ensure!(
h.state == "running" && a.state == "running" && a.outcome_bytes.is_empty(),
@@ -1680,7 +1863,7 @@ fn merge_helper(local: &mut [SyncAttempt], helper: &HelperSnapshot) -> Result<()
a.grant_id = h.grant_id.clone();
a.consumption = h.consumption.clone();
ensure!(
a.outcome_sha256 == h.outcome_sha256,
a.outcome_sha256 == h.outcome_sha256 || unreported,
"HELPER_OUTCOME_MISMATCH"
);
if a.original_boot_id.is_empty() {
+34
View File
@@ -326,6 +326,40 @@ fn consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution() {
std::fs::remove_file(path).unwrap();
}
#[test]
fn retired_reboot_redelivery_preserves_the_original_attempt_and_enrollment() {
let (binding, request, permit, _) = fixture();
let mut old = binding.job(&request.job_bytes).unwrap();
old.action = Action::Reboot {
reason: "historical reboot".into(),
reconnect_timeout_seconds: 60,
dependency_group: "test".into(),
};
old.execution_identity = "root".into();
let payload = encode(&old).unwrap();
let offer = JobOffer {
job_id: old.job_id.to_string(),
attempt_id: old.attempt_id.to_string(),
job_payload_hash: hash(&payload),
payload_bytes: payload,
plan_hash: permit.plan_hash,
authorization_id: permit.authorization_id.to_string(),
};
let db = Connection::open_in_memory().unwrap();
db.execute_batch("CREATE TABLE job_attempts(job TEXT,attempt TEXT,offer BLOB,state TEXT,PRIMARY KEY(job,attempt))").unwrap();
assert!(jobs::accept(&db, &binding, &offer, |_| false).is_err());
assert!(jobs::accept(&db, &binding, &offer, |_| true).unwrap());
db.execute("UPDATE job_attempts SET state='unknown'", []).unwrap();
assert!(!jobs::accept(&db, &binding, &offer, |_| panic!("historical delivery invoked the execution probe")).unwrap());
let mut altered = offer.clone();
altered.authorization_id = Uuid::new_v4().to_string();
assert!(jobs::accept(&db, &binding, &altered, |_| false).is_err());
let mut other = binding;
other.enrollment_generation += 1;
assert!(jobs::accept(&db, &other, &offer, |_| true).is_err());
assert_eq!(db.query_row("SELECT count(*) FROM job_attempts WHERE state='unknown'", [], |r| r.get::<_,u32>(0)).unwrap(), 1);
}
#[test]
fn portable_acceptance_requires_platform_capability_and_exact_redelivery() {
let (binding, request, permit, _) = fixture();
+298
View File
@@ -1091,6 +1091,103 @@ fn windows_unconfirmed_helper_head_cannot_replace_a_committed_decision() {
);
assert!(!reopened.can_start(&f.channel, false, &f.clock));
}
#[test]
fn missed_system_ack_after_result_delivery_requires_archived_definitive_proof() {
let mut f = Fixture::new();
f.helper_identity = HelperIdentity::System;
let mut c = f.client();
let mut helper = HelperSnapshot {
journal_id: Uuid::new_v4(),
checkpoint: 1,
previous_decision_id: None,
attempts: vec![],
};
let first = c
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
)
.unwrap();
let anchor = f.decision(&first, true);
f.apply(&mut c, &anchor).unwrap();
c.apply_consumption(&mut f.ledger, &f.clock).unwrap();
helper.previous_decision_id = Some(anchor.decision_id);
c.confirm_helper(&helper).unwrap();
helper.checkpoint += 1;
let (offer, grant, report) = f.add("unknown", true, Some(success()), script());
let mut prior = report.unwrap();
let Some(Payload::JobResult(result)) = &mut prior.payload else {
unreachable!()
};
result.state = "unknown".into();
f.db.execute(
"UPDATE job_events SET payload=?1 WHERE id=?2",
params![prior.encode_to_vec(), prior.message_id],
)
.unwrap();
let final_report =
persist_original_fixture_result(&mut f, &offer, &grant.unwrap(), completion_outcome());
let edge = c
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
)
.unwrap();
assert_eq!(edge.request.durable_message_ids.len(), 2);
let mut signed = f.decision(&edge, true);
signed
.acknowledged_message_ids
.push(Uuid::parse_str(&final_report.message_id).unwrap());
f.apply(&mut c, &signed).unwrap();
c.apply_consumption(&mut f.ledger, &f.clock).unwrap();
helper.checkpoint += 1;
f.channel.connection_generation += 1;
let mut fresh = f.client();
let prepare = |c: &mut ClientSync, f: &mut Fixture| {
c.prepare_with_closed_control_idle(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&helper),
&f.clock,
true,
)
};
assert!(prepare(&mut fresh, &mut f).is_err()); // prior report still pending
rmm_agent_core::jobs::ack(&mut f.db, &prior.message_id).unwrap();
let mut conflicting = prior.clone();
if let Some(Payload::JobResult(r)) = &mut conflicting.payload {
r.state = "failed".into();
}
f.db.execute(
"UPDATE reconcile_results SET envelope=?1 WHERE id=?2",
params![conflicting.encode_to_vec(), prior.message_id],
)
.unwrap();
assert!(prepare(&mut fresh, &mut f).is_err());
f.db.execute(
"UPDATE reconcile_results SET envelope=?1 WHERE id=?2",
params![prior.encode_to_vec(), prior.message_id],
)
.unwrap();
let next = prepare(&mut fresh, &mut f).unwrap();
assert_eq!(
next.request.previous_decision_id,
signed.decision_id.to_string()
);
assert_eq!(
next.request.helper_previous_decision_id,
anchor.decision_id.to_string()
);
assert!(!fresh.can_start(&f.channel, true, &f.clock));
}
#[test]
fn independent_helper_checkpoint_regression_is_sticky() {
let mut f = Fixture::new();
@@ -1388,6 +1485,207 @@ fn persist_original_fixture_result(
fn completion_outcome() -> rmm_agent_core::auth::Outcome {
serde_json::from_slice(&canonical_outcome_bytes(&success()).unwrap()).unwrap()
}
#[test]
fn human_closure_reconciles_agent_interruption_and_a_helper_without_result() {
use rmm_agent_core::helper_reconcile::{self, BootSource, ExecutorLedgerGuard, HelperSync};
struct TestGuard;
impl ExecutorLedgerGuard for TestGuard {
fn check(&self, db: &Connection) -> anyhow::Result<()> {
anyhow::ensure!(
db.is_autocommit(),
"fixture ledger must be outside a transaction"
);
Ok(())
}
}
struct TestBoot(Uuid);
impl BootSource for TestBoot {
fn current_boot(&self) -> anyhow::Result<Uuid> {
Ok(self.0)
}
}
fn map(snapshot: &helper_reconcile::Snapshot) -> HelperSnapshot {
HelperSnapshot {
journal_id: snapshot.journal_id,
checkpoint: snapshot.checkpoint,
previous_decision_id: snapshot.previous_decision_id,
attempts: snapshot
.attempts
.iter()
.map(|a| SyncAttempt {
job_id: a.job_id.to_string(),
attempt_id: a.attempt_id.to_string(),
job_payload_hash: a.job_payload_hash.clone(),
grant_id: a.grant_id.to_string(),
consumption: a.consumption.clone(),
state: a.state.clone(),
revision: a.revision,
original_boot_id: a.original_boot_id.to_string(),
outcome_sha256: a.outcome_sha256.clone(),
outcome_bytes: a.outcome_bytes.clone(),
..Default::default()
})
.collect(),
}
}
let closed = canonical_outcome_bytes(&ReconciledOutcome {
state: "closed_unknown".into(),
stdout: vec![],
stderr: vec![],
exit_code: None,
output_truncated: false,
reboot_required: false,
evidence: serde_json::json!({
"postconditions_passed":false,"effect":"unknown","closed_by_human":true,"retry":false
}),
error_code: "OPERATOR_CLOSED_UNKNOWN".into(),
})
.unwrap();
for interrupt_after_projection in [false, true] {
let mut f = Fixture::new();
reconcile::initialize(&f.db).unwrap();
let (offer, grant, _) = f.add(
"running",
true,
None,
Action::SetServiceState {
unit: "rmm-acceptance.service".into(),
state: "running".into(),
},
);
let grant = grant.unwrap();
let archive = persist_original_fixture_result(
&mut f,
&offer,
&grant,
rmm_agent_core::auth::Outcome::unknown("AGENT_PROCESS_INTERRUPTED"),
);
rmm_agent_core::jobs::ack(&mut f.db, &archive.message_id).unwrap();
let start: Vec<u8> = f
.ledger
.query_row("SELECT start FROM execution_evidence", [], |row| row.get(0))
.unwrap();
let start: serde_json::Value = serde_json::from_slice(&start).unwrap();
let request: Request = serde_json::from_value(start["request"].clone()).unwrap();
let boot = TestBoot(f.channel.boot_id);
let guard = TestGuard;
let mut helper_db = Connection::open_in_memory().unwrap();
rmm_agent_core::ledger::initialize_ledger(&helper_db).unwrap();
rmm_agent_core::ledger::begin_execution(
&mut helper_db,
&grant,
&request,
boot.0,
f.clock.now,
)
.unwrap();
let mut helper = HelperSync::new(f.binding.clone(), &f.clock).unwrap();
let mut client = f.client();
for round in 0..if interrupt_after_projection { 3 } else { 2 } {
let snapshot = map(&helper
.snapshot(
&mut helper_db,
&guard,
f.channel.connection_generation,
&f.clock,
&boot,
)
.unwrap());
assert_eq!(snapshot.attempts[0].state, "unknown");
assert!(snapshot.attempts[0].outcome_bytes.is_empty());
let prepared = client
.prepare(
&mut f.db,
&f.ledger,
f.channel.clone(),
Some(&snapshot),
&f.clock,
)
.unwrap();
let agent_attempt = &prepared.request.attempts[0];
assert!(!agent_attempt.outcome_bytes.is_empty());
let mut d = f.decision(&prepared, round != 0);
d.issued_at = f.clock.now;
if round != 0 {
let attempt = &mut d.attempts[0];
attempt.revision = 3;
attempt.outcome_state = "closed_unknown".into();
attempt.reason = "OPERATOR_CLOSED_UNKNOWN".into();
attempt.unlock = true;
attempt.outcome_sha256 = Some(hash(&closed));
if agent_attempt.state == "unknown" {
attempt.outcome_bytes = closed.clone();
}
}
let signed = f.sign(&d);
client.apply(&mut f.db, &signed, &f.clock).unwrap();
if interrupt_after_projection && round == 1 {
client = f.client();
continue;
}
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
let raw = prepared.request.encode_to_vec();
let response = helper_reconcile::SignedResponse {
decision_bytes: signed.decision_bytes,
signature: signed.signature,
};
let applied = helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap();
if round == 0 {
assert!(!applied.ready && applied.unlocked_grants.is_empty());
assert!(!client.can_start(&f.channel, false, &f.clock));
} else {
assert!(applied.ready);
assert_eq!(applied.unlocked_grants, vec![grant.grant_id]);
assert!(
helper
.apply(&mut helper_db, &guard, &response, &raw, &f.clock, &boot)
.unwrap()
.unlocked_grants
.is_empty()
);
client.apply_consumption(&mut f.ledger, &f.clock).unwrap();
client.confirm_helper(&map(&applied.snapshot)).unwrap();
assert!(client.can_start(&f.channel, true, &f.clock));
}
}
assert_eq!(
f.db.query_row::<String, _, _>("SELECT state FROM job_attempts", [], |rec| rec.get(0))
.unwrap(),
"closed_unknown"
);
assert_eq!(
f.db.query_row::<Vec<u8>, _, _>("SELECT envelope FROM reconcile_results", [], |rec| {
rec.get(0)
})
.unwrap(),
archive.encode_to_vec()
);
for ledger in [&f.ledger, &helper_db] {
assert_eq!(
ledger
.query_row::<Vec<u8>, _, _>("SELECT result FROM consumed", [], |rec| rec.get(0))
.unwrap(),
closed
);
assert_eq!(
ledger
.query_row::<(Vec<u8>, Vec<u8>), _, _>(
"SELECT original_outcome,closure_outcome FROM unknown_closure_originals",
[],
|rec| Ok((rec.get(0)?, rec.get(1)?))
)
.unwrap(),
(vec![], closed.clone())
);
}
}
}
#[test]
fn crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes() {
let mut f = Fixture::new();
+233 -24
View File
@@ -4,11 +4,12 @@ use crate::{
actions::{ServiceUnit, reboot_required},
process,
};
use rmm_domain::inventory_document::{CpuTimes, DeviceType, firmware_identifier};
use std::{
collections::BTreeMap,
ffi::{CStr, CString},
fs,
io::Read,
io::{BufRead, BufReader, Read},
mem::MaybeUninit,
net::{Ipv4Addr, Ipv6Addr},
path::Path,
@@ -168,6 +169,9 @@ pub struct OperatingSystem {
pub hostname: String,
pub boot_id: String,
pub uptime_seconds: f64,
pub booted_at: Option<chrono::DateTime<chrono::Utc>>,
pub installed_at: Option<chrono::DateTime<chrono::Utc>>,
pub install_date_source: Option<&'static str>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct Interface {
@@ -257,6 +261,10 @@ pub struct UpdateStatus {
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hardware {
pub readable_dmi: BTreeMap<String, String>,
pub device_type: Option<DeviceType>,
pub proxmox_ve: bool,
pub manufacturer: Option<String>,
pub bios_serial_number: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct LinuxInventory {
@@ -268,6 +276,7 @@ pub struct LinuxInventory {
pub dns: Observation<Dns>,
pub volumes: Observation<Vec<Observation<Volume>>>,
pub software: Observation<Vec<SoftwarePackage>>,
pub users: Observation<Vec<String>>,
pub updates: Observation<UpdateStatus>,
pub hardware: Observation<Hardware>,
pub smart: Observation<()>,
@@ -282,6 +291,7 @@ pub fn collect_native() -> LinuxInventory {
dns: dns(),
volumes: volumes(),
software: software(),
users: logged_in_users(),
updates: updates(),
hardware: hardware(),
smart: Observation::unavailable(
@@ -377,6 +387,22 @@ pub fn capabilities() -> BTreeMap<String, Observation<bool>> {
);
result
}
fn installed_at() -> Option<(chrono::DateTime<chrono::Utc>, &'static str)> {
for (path, source) in [
("/var/log/installer", "installer_directory"),
("/", "root_filesystem"),
] {
if let Some(time) = fs::metadata(path)
.ok()
.and_then(|data| data.created().ok())
.filter(|time| *time > SystemTime::UNIX_EPOCH && *time <= SystemTime::now())
{
return Some((time.into(), source));
}
}
None
}
pub fn operating_system() -> Observation<OperatingSystem> {
let release = read("/etc/os-release", 32 * 1024);
let kernel = read("/proc/sys/kernel/osrelease", 4096);
@@ -414,8 +440,21 @@ pub fn operating_system() -> Observation<OperatingSystem> {
.map(|(k, v)| (k.into(), v.trim_matches('"').into()))
})
.collect();
let booted_at = read("/proc/stat", 256 * 1024)
.data
.as_deref()
.and_then(|stat| {
let seconds = stat
.lines()
.find_map(|line| line.strip_prefix("btime "))?
.trim()
.parse()
.ok()?;
chrono::DateTime::from_timestamp(seconds, 0)
});
let installed = installed_at();
Observation::valid(
"linux.os:/etc/os-release,/proc",
"linux.os:/etc/os-release,/proc,filesystem-birth",
OperatingSystem {
release,
kernel: kernel.trim().into(),
@@ -423,12 +462,109 @@ pub fn operating_system() -> Observation<OperatingSystem> {
hostname: hostname.trim().into(),
boot_id,
uptime_seconds,
booted_at,
installed_at: installed.map(|(time, _)| time),
install_date_source: installed.map(|(_, source)| source),
},
)
} else {
Observation::unavailable("linux.os", Quality::Error, "OS_SOURCE_UNAVAILABLE")
}
}
fn logged_in_users() -> Observation<Vec<String>> {
const LOGINCTL: &str = "/usr/bin/loginctl";
let listed = command(
LOGINCTL,
&["--no-legend", "--no-pager", "list-sessions"],
16 * 1024,
);
let Some(rows) = &listed.data else {
return map(listed, |_| None);
};
let mut ids = rows
.lines()
.filter_map(|line| line.split_whitespace().next());
let mut args = vec![
"--no-pager",
"--all",
"--property=Name,Class,State",
"show-session",
"--",
];
args.extend(
ids.by_ref()
.take(64)
.filter(|id| id.bytes().all(|c| c.is_ascii_alphanumeric())),
);
let limited = listed.truncated || ids.next().is_some();
if args.len() == 5 {
return Observation::valid("linux.logind:loginctl", Vec::new());
}
let mut report = map(command(LOGINCTL, &args, 16 * 1024), |text| {
let users: std::collections::BTreeSet<_> = text
.split("\n\n")
.filter_map(|block| {
let fields: BTreeMap<_, _> = block
.lines()
.filter_map(|line| line.split_once('='))
.collect();
let class = *fields.get("Class")?;
let state = *fields.get("State")?;
let name = *fields.get("Name")?;
(matches!(
class,
"user" | "user-early" | "user-light" | "user-early-light"
) && matches!(state, "online" | "active")
&& !name.is_empty()
&& name.len() <= 255)
.then(|| name.to_owned())
})
.collect();
Some(users.into_iter().collect())
});
report.source_id = "linux.logind:loginctl".into();
if limited && report.data.is_some() {
report = report.partial("SESSION_LIMIT");
report.truncated = true;
}
report
}
fn aggregate_jiffies(stat: &str) -> Option<Vec<u64>> {
stat.lines()
.find(|line| line.starts_with("cpu "))
.and_then(|line| {
line.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<_, _>>()
.ok()
})
}
fn linux_cpu_times(jiffies: &[u64]) -> Option<CpuTimes> {
// Linux already includes guest and guest_nice in user and nice.
let total = jiffies
.iter()
.take(8)
.try_fold(0_u64, |total, ticks| total.checked_add(*ticks))?;
let idle = jiffies
.get(3)?
.checked_add(jiffies.get(4).copied().unwrap_or_default())?;
Some(CpuTimes { total, idle })
}
pub fn cpu_times() -> Option<CpuTimes> {
let mut line = String::new();
BufReader::new(fs::File::open("/proc/stat").ok()?.take(4096))
.read_line(&mut line)
.ok()?;
if !line.ends_with('\n') {
return None;
}
linux_cpu_times(&aggregate_jiffies(&line)?)
}
pub fn cpu() -> Observation<Cpu> {
let info = read("/proc/cpuinfo", 1024 * 1024);
let stat = read("/proc/stat", 256 * 1024);
@@ -457,15 +593,7 @@ pub fn cpu() -> Observation<Cpu> {
.filter(|(k, _)| k.trim() == "model name")
.map(|(_, v)| v.trim().to_owned())
});
let aggregate_jiffies: Option<Vec<u64>> =
stat.lines().find(|l| l.starts_with("cpu ")).and_then(|l| {
l.split_whitespace()
.skip(1)
.map(str::parse)
.collect::<Result<Vec<_>, _>>()
.ok()
});
match aggregate_jiffies {
match aggregate_jiffies(&stat) {
Some(aggregate_jiffies) if logical_processors > 0 => Observation::valid(
"linux.cpu:/proc/cpuinfo,/proc/stat",
Cpu {
@@ -553,11 +681,12 @@ pub fn interfaces() -> Observation<Vec<Interface>> {
}
libc::AF_INET6 => {
let addr = &*item.ifa_addr.cast::<libc::sockaddr_in6>();
addresses.push(format!(
"{}%{}",
Ipv6Addr::from(addr.sin6_addr.s6_addr),
addr.sin6_scope_id
));
let ip = Ipv6Addr::from(addr.sin6_addr.s6_addr);
addresses.push(if addr.sin6_scope_id == 0 {
ip.to_string()
} else {
format!("{ip}%{}", addr.sin6_scope_id)
});
}
_ => {}
}
@@ -1116,7 +1245,36 @@ pub fn updates() -> Observation<UpdateStatus> {
}
result
}
fn virtualization_type(output: &process::Output) -> Option<DeviceType> {
if output.timed_out || output.truncated {
return None;
}
match (
output.code,
std::str::from_utf8(&output.stdout).ok()?.trim(),
) {
(Some(1), "none") => Some(DeviceType::Physical),
(Some(0), name) if !name.is_empty() && name != "none" => Some(DeviceType::Virtual),
_ => None,
}
}
fn machine_type(proxmox_ve: bool) -> Option<DeviceType> {
if proxmox_ve {
return Some(DeviceType::Hypervisor);
}
let output = process::run(
"/usr/bin/systemd-detect-virt",
&[],
Duration::from_secs(2),
512,
)
.ok()?;
virtualization_type(&output)
}
pub fn hardware() -> Observation<Hardware> {
const SOURCE: &str = "linux.dmi:/sys/class/dmi/id;systemd-detect-virt;pve-manager";
let mut readable_dmi = BTreeMap::new();
for field in [
"sys_vendor",
@@ -1132,15 +1290,36 @@ pub fn hardware() -> Observation<Hardware> {
readable_dmi.insert(field.into(), value);
}
}
if readable_dmi.is_empty() {
Observation::unavailable(
"linux.dmi:/sys/class/dmi/id",
Quality::Unsupported,
"DMI_UNAVAILABLE",
)
let proxmox_ve =
Path::new("/usr/bin/pveversion").is_file() && Path::new("/usr/bin/pvedaemon").is_file();
let device_type = machine_type(proxmox_ve);
let manufacturer = readable_dmi
.get("sys_vendor")
.and_then(|value| firmware_identifier(value));
let serial_credential = std::env::var_os("CREDENTIALS_DIRECTORY")
.map(|directory| std::path::PathBuf::from(directory).join("rmm-bios-serial"));
let bios_serial_number = [
Some("/sys/class/dmi/id/product_serial"),
Some("/proc/device-tree/serial-number"),
serial_credential.as_deref().and_then(Path::to_str),
]
.into_iter()
.flatten()
.find_map(|path| sys_text(path).and_then(|value| firmware_identifier(&value)));
if readable_dmi.is_empty() && device_type.is_none() && bios_serial_number.is_none() {
Observation::unavailable(SOURCE, Quality::Unsupported, "HARDWARE_UNAVAILABLE")
} else {
Observation::valid("linux.dmi:/sys/class/dmi/id", Hardware { readable_dmi })
.partial("READABLE_DMI_ONLY_NO_SMART_OR_ENCRYPTION_PROOF")
Observation::valid(
SOURCE,
Hardware {
readable_dmi,
device_type,
proxmox_ve,
manufacturer,
bios_serial_number,
},
)
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
}
}
@@ -1362,6 +1541,36 @@ mod tests {
assert_eq!(request.since_filter, "@100.123457");
assert_eq!(request.until_filter, "@101.987654");
}
#[test]
fn cpu_time_excludes_double_counted_guest_ticks_and_io_wait() {
let before = linux_cpu_times(&[10, 0, 5, 60, 10, 0, 0, 0, 4, 0]).unwrap();
let after = linux_cpu_times(&[30, 0, 5, 120, 30, 0, 0, 0, 20, 0]).unwrap();
assert_eq!(after.usage_since(before), Some(2_000));
assert_eq!(after.usage_since(after), None);
assert_eq!(before.usage_since(after), None);
assert!(linux_cpu_times(&[10, 0, 0]).is_none());
}
#[test]
fn machine_types_distinguish_proxmox_guests_and_probe_failures() {
assert_eq!(machine_type(true), Some(DeviceType::Hypervisor));
let mut output = process::Output {
code: Some(0),
stdout: b"kvm\n".to_vec(),
stderr: vec![],
truncated: false,
timed_out: false,
interrupted: false,
};
assert_eq!(virtualization_type(&output), Some(DeviceType::Virtual));
output.code = Some(1);
assert_eq!(virtualization_type(&output), None);
output.stdout = b"none\n".to_vec();
assert_eq!(virtualization_type(&output), Some(DeviceType::Physical));
output.timed_out = true;
assert_eq!(virtualization_type(&output), None);
}
#[test]
fn harmless_native_read_providers() {
assert_eq!(memory().quality, Quality::Valid);
+62 -11
View File
@@ -1,8 +1,20 @@
//! Additive JSON observation mapping inside the existing snapshot payload. This
//! does not introduce a protobuf tag, a fabricated receive time or a new scope.
use anyhow::Result;
//! does not introduce a protobuf tag or a fabricated receive time.
use anyhow::{Result, ensure};
use rmm_domain::inventory_document::LINUX_SOFTWARE_OBSERVATION_MAX_BYTES;
use serde_json::{Value, json};
fn truncate_rows(observation: &mut Value) -> bool {
let Some(rows) = observation["data"].as_array_mut().filter(|v| !v.is_empty()) else {
return false;
};
rows.truncate(rows.len() / 2);
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
true
}
pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<Value>> {
let value = serde_json::to_value(inventory)?;
let mut result = Vec::new();
@@ -14,13 +26,16 @@ pub fn observations(inventory: &crate::inventory::LinuxInventory) -> Result<Vec<
observation["scope"] = json!(format!("linux.{name}"));
// Bound each scope independently. Never drop unsupported/error metadata
// or imply that absent/truncated rows were deleted from a device.
while serde_json::to_vec(&observation)?.len() > 32768 {
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
if let Some(rows) = observation["data"].as_array_mut().filter(|v| !v.is_empty()) {
rows.truncate(rows.len() / 2);
} else {
let max_bytes = if name == "software" {
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
while serde_json::to_vec(&observation)?.len() > max_bytes {
if !truncate_rows(&mut observation) {
observation["truncated"] = json!(true);
observation["completeness"] = json!("partial");
observation["error_code"] = json!("WIRE_SCOPE_LIMIT");
observation["data"] = Value::Null;
observation["quality"] = json!("unknown");
break;
@@ -42,6 +57,20 @@ pub fn snapshot(extended: bool) -> Result<Value> {
Ok(base)
}
pub fn encode_snapshot(mut inventory: Value) -> Result<Vec<u8>> {
let mut bytes = serde_json::to_vec(&inventory)?;
// Preserve the other scopes when a large package list fills the snapshot.
while bytes.len() > 512 * 1024 {
let software = inventory
.get_mut("observations")
.and_then(Value::as_array_mut)
.and_then(|scopes| scopes.iter_mut().find(|scope| scope["scope"] == "linux.software"));
ensure!(software.is_some_and(truncate_rows), "INVENTORY_WIRE_LIMIT");
bytes = serde_json::to_vec(&inventory)?;
}
Ok(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -49,7 +78,7 @@ mod tests {
fn native_wire_scopes_preserve_quality_time_and_unsupported() {
let native = crate::inventory::collect_native();
let mapped = observations(&native).unwrap();
assert_eq!(mapped.len(), 11);
assert_eq!(mapped.len(), 12);
let smart = mapped.iter().find(|v| v["scope"] == "linux.smart").unwrap();
assert_eq!(smart["quality"], "unsupported");
assert!(smart["data"].is_null());
@@ -61,7 +90,12 @@ mod tests {
);
assert!(!observation["source_id"].as_str().unwrap().is_empty());
assert!(observation.get("received_at").is_none());
assert!(serde_json::to_vec(observation).unwrap().len() <= 32768);
let limit = if observation["scope"] == "linux.software" {
LINUX_SOFTWARE_OBSERVATION_MAX_BYTES
} else {
32768
};
assert!(serde_json::to_vec(observation).unwrap().len() <= limit);
}
let base = snapshot(false).unwrap();
assert!(serde_json::from_value::<rmm_domain::Inventory>(base).is_ok());
@@ -87,4 +121,21 @@ mod tests {
assert_eq!(software["truncated"], true);
assert_eq!(software["completeness"], "partial");
}
#[test]
fn snapshot_limit_shrinks_software_and_preserves_other_scopes() {
let network = json!({"scope":"linux.interfaces","data":"x".repeat(280 * 1024)});
let data = vec!["x".repeat(1024); 240];
let snapshot = json!({"observations":[
network,
{"scope":"linux.software","completeness":"complete","data":data},
]});
let bytes = encode_snapshot(snapshot).unwrap();
let bounded: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(bounded["observations"][0], network);
assert_eq!(bounded["observations"][1]["completeness"], "partial");
assert_eq!(
bounded["observations"][1]["data"].as_array().unwrap().len(),
120
);
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "rmm-agent-windows"
version.workspace = true
version = "0.1.16"
edition.workspace = true
license.workspace = true
@@ -43,7 +43,7 @@ rmm-updater = { path = "../updater" }
hex.workspace = true
ed25519-dalek = "=2.2.0"
rmm-update-history = { path = "../update-history" }
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
fs2 = "0.4.3"
x509-parser = { version = "=0.18.1", features = ["verify"] }
rcgen = { version = "=0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
@@ -52,7 +52,7 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
cc = "=1.11.1"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_RemoteDesktop", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading", "Win32_System_Shutdown"] }
[[example]]
name = "windows_reviewed_recovery"
@@ -185,6 +185,7 @@ mod native {
Payload::Heartbeat(Heartbeat {
instance_id: Uuid::new_v4().to_string(),
uptime_seconds: 1,
system_usage: None,
}),
)?;
let acknowledgement = send(client, &heartbeat).await?;
@@ -8,6 +8,10 @@ fn main() -> anyhow::Result<()> {
println!("enrolled-windows-update/1");
return Ok(());
}
if std::env::args().skip(1).eq(["--managed-script-helper-version"]) {
println!("managed-script-helper/1");
return Ok(());
}
rmm_agent_windows::helper_system::dispatch()
}
#[cfg(not(windows))]
@@ -11,6 +11,14 @@ fn main() -> anyhow::Result<()> {
println!("release-job-lock/1");
Ok(())
}
Some(flag) if flag == "--managed-script-helper-version" && args.next().is_none() => {
println!("managed-script-helper/1");
Ok(())
}
Some(flag) if flag == "--managed-script-policy-version" && args.next().is_none() => {
println!("release-preserves-script-policy/1");
Ok(())
}
Some(flag) if flag == "--verify-bootstrap" => {
let release = rmm_updater::verify_bootstrap_files(
rmm_agent_windows::release_platform::VERIFY,
+1 -1
View File
@@ -237,7 +237,7 @@ impl Store {
pub fn open_empty_history_snapshot() -> Result<Self> {
let store = Self::open(false)?;
ensure!(
store.db.is_readonly(rusqlite::DatabaseName::Main)?,
store.db.is_readonly(rusqlite::MAIN_DB)?,
"read-only intent snapshot required"
);
store
+1 -1
View File
@@ -505,7 +505,7 @@ impl Client {
self.check_pin()?;
// Static qualification only; a per-connection clock warm-up must not flap
// advertised capabilities (each change forces a reconnect).
let qualification=crate::system_capabilities::qualified(pin,true,reboot_privilege_available);
let qualification=crate::system_capabilities::qualified(pin,true);
let system_qualification_unavailable=qualification.is_err();
// Capability evidence is deny-only. A missing/stale optional record
// cannot remove the separately authenticated control/SignedSync lane.
+28 -4
View File
@@ -107,10 +107,13 @@ impl Settings {
})
}
pub(crate) fn windows_update_only(&self) -> bool {
self.schema_version >= 3 && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
(3..=4).contains(&self.schema_version) && self.enable_effects && self.windows_update_max_runtime_seconds.is_some()
&& self.allowed_script_profiles.is_none() && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot && self.max_runtime_seconds <= 30
}
pub(crate) fn managed_scripts(&self) -> bool {
self.schema_version == 5
}
fn permits_script(&self, job: &JobPayload) -> bool {
self.schema_version >= 3
&& job.execution_identity == "system"
@@ -133,7 +136,12 @@ impl Settings {
}
pub fn validate(&self) -> Result<()> {
ensure!(
matches!(self.schema_version, 1..=4)
matches!(self.schema_version, 1..=5)
&& (!self.managed_scripts()
|| (self.enable_effects && self.allowed_services.is_empty()
&& self.allowed_msi_recipe_sha256.is_none() && !self.allow_reboot
&& self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])))
&& (self.schema_version >= 2 || self.allowed_msi_recipe_sha256.is_none())
&& (self.schema_version >= 3 || self.allowed_script_profiles.is_none())
&& self
@@ -891,7 +899,7 @@ impl SystemHelper {
let pin = settings.pin()?;
ipc::publish_self_query_rights(&settings.agent.service_sid, &settings.helper.service_sid)?;
let (guard, db) = LedgerGuard::acquire(&settings.helper.service_sid, &settings.binding)?;
let clock = if settings.windows_update_only() {
let clock = if settings.windows_update_only() || settings.managed_scripts() {
RuntimeClock::enrolled_windows_update_helper(settings.binding.clone(), settings.helper.clone())
} else { RuntimeClock::new(rmm_time_attestation::Role::SystemHelper) }.for_generation(0);
let boot = WindowsBoot::capture()?;
@@ -1083,6 +1091,7 @@ impl SystemHelper {
serde_json::from_slice(&response.decision_bytes)?;
self.clock
.require_generation(decision.connection_generation)?;
let started = Instant::now();
self.wait_apply_clock(decision.issued_at,decision.valid_until)?;
self.sync()?;
let value = if let Some(grant)=crate::update_control::active_grant(&self.db)? {
@@ -1091,7 +1100,21 @@ impl SystemHelper {
&self.clock,&self.pin,&budget,grant)?;
self.sync.as_mut().unwrap().apply(&mut self.db,&guard,response,request_bytes,&self.clock,&self.boot)?
} else {
self.sync.as_mut().unwrap().apply(&mut self.db,&self.guard,response,request_bytes,&self.clock,&self.boot)?
// Refresh only a clock read that the core proves failed before
// its first transaction. Keep the original capture and deadline.
loop {
let result = self.sync.as_mut().unwrap().apply(
&mut self.db, &self.guard, response, request_bytes,
&self.clock, &self.boot,
);
match result {
Err(error) if rmm_agent_core::helper_reconcile::retryable_precommit_clock(&error)
&& started.elapsed() < Duration::from_secs(3) => {
std::thread::sleep(Duration::from_millis(20));
}
other => break other?,
}
}
};
let no_start_anchor = if value.ready
&& (self.settings.enable_effects
@@ -1130,6 +1153,7 @@ impl SystemHelper {
request,
} => {
let job = self.settings.binding.job(&request.job_bytes)?;
ensure!(self.settings.permits_script(&job), "SYSTEM_SCRIPT_REQUIRED");
if matches!(job.action, Action::UpdateAgent { .. }) {
ensure!(
self.pending_update_activation.is_none(),
+169 -13
View File
@@ -2,6 +2,9 @@
//! uninstall commands; registry entries are evidence, not verified MSI state.
use anyhow::{Result, ensure};
use chrono::Utc;
use rmm_domain::inventory_document::{
CpuTimes, DeviceType, SOFTWARE_OBSERVATION_MAX_BYTES, firmware_identifier,
};
use serde_json::{Value, json};
use std::{
mem::{size_of, zeroed},
@@ -9,8 +12,12 @@ use std::{
time::{Duration, Instant},
};
use windows_sys::Win32::{
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS},
System::{Registry::*, SystemInformation::*},
Foundation::{ERROR_FILE_NOT_FOUND, ERROR_NO_MORE_ITEMS, ERROR_SUCCESS, FILETIME},
System::{
Registry::*,
SystemInformation::*,
Threading::{GetActiveProcessorGroupCount, GetSystemTimes},
},
};
struct Registry(HKEY);
@@ -64,21 +71,119 @@ fn text(key: HKEY, name: &str) -> Result<Option<String>> {
Ok(Some(String::from_utf16(&data[..count - 1])?))
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
#[cfg(target_arch = "x86_64")]
fn non_microsoft_hypervisor() -> bool {
use std::arch::x86_64::__cpuid;
if __cpuid(1).ecx & (1 << 31) == 0 {
return false;
}
let vendor = __cpuid(0x4000_0000);
// The Microsoft hypervisor can also be active on physical VBS machines.
[vendor.ebx, vendor.ecx, vendor.edx]
!= [
u32::from_le_bytes(*b"Micr"),
u32::from_le_bytes(*b"osof"),
u32::from_le_bytes(*b"t Hv"),
]
}
#[cfg(not(target_arch = "x86_64"))]
fn non_microsoft_hypervisor() -> bool {
false
}
fn classify_machine(
hyper_v_host: bool,
guest_hypervisor: bool,
manufacturer: Option<&str>,
product: Option<&str>,
) -> Option<DeviceType> {
if hyper_v_host {
return Some(DeviceType::Hypervisor);
}
let manufacturer = manufacturer.unwrap_or_default().trim().to_ascii_lowercase();
let product = product.unwrap_or_default().trim().to_ascii_lowercase();
let virtual_firmware = [
"qemu",
"vmware",
"virtualbox",
"xen",
"parallels",
"bhyve",
"kvm",
"virtual machine",
"virtual platform",
]
.iter()
.any(|prefix| manufacturer.starts_with(prefix) || product.starts_with(prefix));
if guest_hypervisor || virtual_firmware {
return Some(DeviceType::Virtual);
}
(!manufacturer.is_empty() && !product.is_empty()).then_some(DeviceType::Physical)
}
fn machine_type(manufacturer: Option<&str>, product: Option<&str>) -> Option<DeviceType> {
let hyper_v_host = open(
HKEY_LOCAL_MACHINE,
r"SYSTEM\CurrentControlSet\Services\vmms",
KEY_WOW64_64KEY,
)
.is_ok();
classify_machine(
hyper_v_host,
non_microsoft_hypervisor(),
manufacturer,
product,
)
}
fn memory_status() -> Result<MEMORYSTATUSEX> {
let mut memory: MEMORYSTATUSEX = unsafe { zeroed() };
memory.dwLength = size_of::<MEMORYSTATUSEX>() as u32;
ensure!(
unsafe { GlobalMemoryStatusEx(&mut memory) } != 0
&& system.dwNumberOfProcessors > 0
&& memory.ullTotalPhys > 0
&& memory.ullAvailPhys <= memory.ullTotalPhys
&& memory.dwMemoryLoad <= 100,
"NATIVE_HARDWARE_QUERY"
);
Ok(memory)
}
pub fn physical_memory() -> Option<(u64, u64)> {
let memory = memory_status().ok()?;
Some((memory.ullAvailPhys, memory.ullTotalPhys))
}
pub fn cpu_times() -> Option<CpuTimes> {
// GetSystemTimes on a multi-group machine only reports the caller's group.
if unsafe { GetActiveProcessorGroupCount() } != 1 {
return None;
}
let (mut idle, mut kernel, mut user) = (
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
);
if unsafe { GetSystemTimes(&mut idle, &mut kernel, &mut user) } == 0 {
return None;
}
let ticks =
|time: FILETIME| (u64::from(time.dwHighDateTime) << 32) | u64::from(time.dwLowDateTime);
// Windows includes idle time in the kernel counter.
Some(CpuTimes {
total: ticks(kernel).checked_add(ticks(user))?,
idle: ticks(idle),
})
}
fn hardware() -> Result<Value> {
let mut system: SYSTEM_INFO = unsafe { zeroed() };
unsafe {
GetNativeSystemInfo(&mut system);
}
ensure!(system.dwNumberOfProcessors > 0, "NATIVE_HARDWARE_QUERY");
let memory = memory_status()?;
let cpu_model = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
@@ -88,16 +193,34 @@ fn hardware() -> Result<Value> {
.and_then(|key| text(key.0, "ProcessorNameString").ok().flatten())
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty());
let bios = open(
HKEY_LOCAL_MACHINE,
r"HARDWARE\DESCRIPTION\System\BIOS",
KEY_WOW64_64KEY,
)
.ok();
let read = |name| {
bios.as_ref()
.and_then(|key| text(key.0, name).ok().flatten())
};
let manufacturer = read("SystemManufacturer").and_then(|value| firmware_identifier(&value));
let product = read("SystemProductName");
let bios_serial_number = read("SystemSerialNumber")
.and_then(|value| firmware_identifier(&value))
.or_else(crate::inventory_sources::bios_serial);
Ok(
json!({"cpu_model":cpu_model, "logical_processors_visible":system.dwNumberOfProcessors,
"memory_total_bytes":memory.ullTotalPhys,"memory_available_bytes":memory.ullAvailPhys,
"memory_load_percent":memory.dwMemoryLoad}),
"memory_load_percent":memory.dwMemoryLoad,
"device_type":machine_type(manufacturer.as_deref(),product.as_deref()),
"manufacturer":manufacturer,"bios_serial_number":bios_serial_number}),
)
}
fn software() -> Result<Value> {
let began = Instant::now();
let mut entries = Vec::new();
let mut entry_bytes = 0;
let mut errors = 0u32;
let mut scanned = 0u32;
let mut truncated = false;
@@ -119,7 +242,7 @@ fn software() -> Result<Value> {
}
};
for index in 0..2048 {
if began.elapsed() > Duration::from_millis(250) || entries.len() >= 64 {
if began.elapsed() > Duration::from_millis(250) {
truncated = true;
break;
}
@@ -161,12 +284,12 @@ fn software() -> Result<Value> {
})();
match entry {
Ok(Some(entry)) => {
entries.push(entry);
if serde_json::to_vec(&entries)?.len() > 12288 {
entries.pop();
entry_bytes += serde_json::to_vec(&entry)?.len() + 1;
if entry_bytes > SOFTWARE_OBSERVATION_MAX_BYTES - 2048 {
truncated = true;
break;
}
entries.push(entry);
}
Ok(None) => {}
Err(_) => errors += 1,
@@ -197,7 +320,7 @@ pub fn observations() -> Vec<Value> {
[
(
"windows.hardware",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor",
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx+GetSystemFirmwareTable;registry:CentralProcessor,BIOS,vmms;cpuid",
hardware as Provider,
),
(
@@ -205,6 +328,8 @@ pub fn observations() -> Vec<Value> {
"windows.registry:HKLM.Uninstall:64+32",
software as Provider,
),
("windows.interfaces", "windows.win32:GetAdaptersAddresses", crate::inventory_sources::interfaces as Provider),
("windows.users", "windows.win32:WTSEnumerateSessions", crate::inventory_sources::users as Provider),
]
.into_iter()
.map(|(scope, source, collect)| {
@@ -226,3 +351,34 @@ pub fn observations() -> Vec<Value> {
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn machine_type_distinguishes_hyper_v_hosts_from_guests() {
let guest = (Some("Microsoft Corporation"), Some("Virtual Machine"));
assert_eq!(
classify_machine(false, false, guest.0, guest.1),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(true, false, guest.0, guest.1),
Some(DeviceType::Hypervisor)
);
assert_eq!(
classify_machine(false, false, Some("QEMU"), Some("Standard PC")),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, true, None, None),
Some(DeviceType::Virtual)
);
assert_eq!(
classify_machine(false, false, Some("Dell Inc."), Some("Precision")),
Some(DeviceType::Physical)
);
assert_eq!(classify_machine(false, false, None, None), None);
}
}
@@ -0,0 +1,266 @@
//! Local read-only inventory providers. Each result is bounded independently.
use anyhow::{Context, Result, ensure};
use rmm_domain::inventory_document::firmware_identifier;
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
ffi::c_void,
mem::size_of,
net::{Ipv4Addr, Ipv6Addr},
ptr, slice,
};
use windows_sys::Win32::{
Foundation::{ERROR_BUFFER_OVERFLOW, ERROR_NO_DATA, ERROR_SUCCESS},
NetworkManagement::IpHelper::*,
Networking::WinSock::{
AF_INET, AF_INET6, AF_UNSPEC, SOCKADDR_IN, SOCKADDR_IN6, SOCKET_ADDRESS,
},
System::{
RemoteDesktop::*,
SystemInformation::{GetSystemFirmwareTable, RSMB},
},
};
pub(crate) fn bios_serial() -> Option<String> {
let length = unsafe { GetSystemFirmwareTable(RSMB, 0, ptr::null_mut(), 0) };
if !(8..=1024 * 1024).contains(&length) {
return None;
}
let mut data = vec![0; length as usize];
if unsafe { GetSystemFirmwareTable(RSMB, 0, data.as_mut_ptr(), length) } != length {
return None;
}
let count = u32::from_le_bytes(data[4..8].try_into().ok()?) as usize;
smbios_serial(data.get(8..)?.get(..count)?)
}
fn smbios_serial(mut table: &[u8]) -> Option<String> {
while let Some(header) = table.get(..4) {
let length = usize::from(header[1]);
if length < 4 || header[0] == 127 {
break;
}
let strings = table.get(length..)?;
let end = strings.windows(2).position(|pair| pair == [0, 0])?;
if header[0] == 1 {
let offset = usize::from(*table.get(..length)?.get(7)?).checked_sub(1)?;
let serial = strings[..end].split(|&c| c == 0).nth(offset)?;
return firmware_identifier(std::str::from_utf8(serial).ok()?);
}
table = strings.get(end + 2..)?;
}
None
}
// Pointer fields returned by IP Helper refer into its caller-provided buffer.
fn at<T>(buffer: &[u64], pointer: *const T) -> Option<&T> {
let offset = (pointer as usize).checked_sub(buffer.as_ptr() as usize)?;
if offset.checked_add(size_of::<T>())? > std::mem::size_of_val(buffer) || !pointer.is_aligned()
{
return None;
}
Some(unsafe { &*pointer })
}
fn wide_name(buffer: &[u64], pointer: *const u16) -> Option<String> {
let mut text = Vec::new();
for i in 0..256 {
let character = *at(buffer, pointer.wrapping_add(i))?;
if character == 0 {
return (!text.is_empty()).then(|| String::from_utf16_lossy(&text));
}
text.push(character);
}
None
}
fn ip_address(buffer: &[u64], address: SOCKET_ADDRESS) -> Option<String> {
let sockaddr = at(buffer, address.lpSockaddr)?;
match sockaddr.sa_family {
AF_INET if address.iSockaddrLength >= size_of::<SOCKADDR_IN>() as i32 => {
let ipv4 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN>())?;
Some(Ipv4Addr::from(unsafe { ipv4.sin_addr.S_un.S_addr }.to_ne_bytes()).to_string())
}
AF_INET6 if address.iSockaddrLength >= size_of::<SOCKADDR_IN6>() as i32 => {
let ipv6 = at(buffer, address.lpSockaddr.cast::<SOCKADDR_IN6>())?;
let ip = Ipv6Addr::from(unsafe { ipv6.sin6_addr.u.Byte });
let scope = unsafe { ipv6.Anonymous.sin6_scope_id };
Some(if scope == 0 {
ip.to_string()
} else {
format!("{ip}%{scope}")
})
}
_ => None,
}
}
pub(crate) fn interfaces() -> Result<Value> {
let mut bytes = 15360_u32;
let mut buffer = vec![0_u64; (bytes as usize).div_ceil(8)];
let flags = GAA_FLAG_SKIP_ANYCAST
| GAA_FLAG_SKIP_MULTICAST
| GAA_FLAG_SKIP_DNS_SERVER
| GAA_FLAG_INCLUDE_ALL_INTERFACES;
let mut status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
if status == ERROR_BUFFER_OVERFLOW && bytes <= 1024 * 1024 {
buffer.resize((bytes as usize).div_ceil(8), 0);
status = unsafe {
GetAdaptersAddresses(
u32::from(AF_UNSPEC),
flags,
ptr::null(),
buffer.as_mut_ptr().cast(),
&mut bytes,
)
};
}
if status == ERROR_NO_DATA {
return Ok(json!({"entries":[],"truncated":false}));
}
ensure!(status == ERROR_SUCCESS, "ADAPTER_ADDRESSES");
let mut current = buffer.as_ptr().cast::<IP_ADAPTER_ADDRESSES_LH>();
let mut entries = Vec::new();
let mut truncated = false;
let mut size = 0;
while !current.is_null() && entries.len() < 128 {
let adapter = at(&buffer, current).context("ADAPTER_POINTER")?;
let mut next = adapter.FirstUnicastAddress.cast_const();
let mut addresses = BTreeSet::new();
for _ in 0..64 {
if next.is_null() {
break;
}
let address = at(&buffer, next).context("ADAPTER_ADDRESS_POINTER")?;
if let Some(ip) = ip_address(&buffer, address.Address) {
addresses.insert(ip);
}
next = address.Next.cast_const();
}
truncated |= !next.is_null();
let name = wide_name(&buffer, adapter.FriendlyName)
.or_else(|| wide_name(&buffer, adapter.Description))
.unwrap_or_else(|| {
format!("Adapter {}", unsafe {
adapter.Anonymous1.Anonymous.IfIndex
})
});
let mac = adapter
.PhysicalAddress
.get(..adapter.PhysicalAddressLength as usize)
.filter(|bytes| !bytes.is_empty())
.map(|bytes| {
bytes
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<Vec<_>>()
.join(":")
});
let entry = json!({"name":name,"addresses":addresses,"mac":mac});
size += serde_json::to_vec(&entry)?.len() + 1;
if size > 30 * 1024 {
truncated = true;
break;
}
entries.push(entry);
current = adapter.Next.cast_const();
}
Ok(json!({"entries":entries,"truncated":truncated || !current.is_null()}))
}
struct WtsMemory(*mut c_void);
impl Drop for WtsMemory {
fn drop(&mut self) {
if !self.0.is_null() {
unsafe { WTSFreeMemory(self.0) };
}
}
}
fn session_text(id: u32, class: WTS_INFO_CLASS) -> Option<String> {
let mut text = ptr::null_mut();
let mut bytes = 0;
if unsafe { WTSQuerySessionInformationW(ptr::null_mut(), id, class, &mut text, &mut bytes) }
== 0
{
return None;
}
let _guard = WtsMemory(text.cast());
if text.is_null() || !(2..=512).contains(&bytes) || bytes % 2 != 0 {
return None;
}
let units = unsafe { slice::from_raw_parts(text, (bytes / 2) as usize) };
String::from_utf16(units.split(|c| *c == 0).next()?).ok()
}
pub(crate) fn users() -> Result<Value> {
let mut list = ptr::null_mut();
let mut count = 0;
ensure!(
unsafe { WTSEnumerateSessionsW(ptr::null_mut(), 0, 1, &mut list, &mut count) } != 0,
"SESSION_QUERY"
);
let _guard = WtsMemory(list.cast());
let mut entries = BTreeSet::new();
let mut errors = 0;
let mut truncated = count > 256;
if count != 0 {
ensure!(!list.is_null(), "SESSION_LIST");
for session in unsafe { slice::from_raw_parts(list, count.min(256) as usize) } {
if session.SessionId == 0
|| ![WTSActive, WTSConnected, WTSDisconnected].contains(&session.State)
{
continue;
}
match session_text(session.SessionId, WTSUserName) {
Some(name) if !name.is_empty() => {
let account = match session_text(session.SessionId, WTSDomainName) {
Some(domain) if !domain.is_empty() => format!("{domain}\\{name}"),
_ => name,
};
if entries.len() >= 64 {
truncated = true;
break;
}
if account.len() <= 255 && !account.chars().any(char::is_control) {
entries.insert(account);
} else {
errors += 1;
}
}
Some(_) => {}
None => errors += 1,
}
}
}
ensure!(
errors == 0 || !entries.is_empty(),
"SESSION_INFORMATION_UNAVAILABLE"
);
Ok(json!({"entries":entries,"read_errors":errors,"truncated":truncated}))
}
#[cfg(test)]
mod tests {
use super::smbios_serial;
#[test]
fn reads_the_system_serial_and_rejects_incomplete_entries() {
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0\0").as_deref(),
Some("ABC-123")
);
assert_eq!(
smbios_serial(b"\x01\x08\x00\x00\x01\x00\x00\x02Vendor\0ABC-123\0"),
None
);
}
}
+1
View File
@@ -24,6 +24,7 @@ pub mod helper_system;
pub mod windows_update_setup;
#[cfg(windows)]
pub mod inventory;
mod inventory_sources;
#[cfg(windows)]
pub mod job_binding;
pub mod journal;
+38 -11
View File
@@ -1,6 +1,6 @@
//! Read-only Windows APIs. The kernel's recorded startup time identifies the boot.
use anyhow::{Context, Result, ensure};
use chrono::Utc;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{ffi::c_void, os::windows::ffi::OsStrExt, path::Path, ptr, time::Duration};
@@ -250,16 +250,36 @@ fn registry_string(name: &str) -> Result<String> {
);
Ok(String::from_utf16(&bytes[..size as usize / 2 - 1])?)
}
pub fn snapshot() -> Result<Value> {
let started = Utc::now();
let mut hostname = vec![0u16; 256];
let mut len = hostname.len() as u32;
pub(crate) fn computer_name(format: COMPUTER_NAME_FORMAT) -> Result<String> {
let mut name = [0u16; 256];
let mut len = name.len() as u32;
ensure!(
unsafe { GetComputerNameExW(ComputerNameDnsHostname, hostname.as_mut_ptr(), &mut len) }
!= 0,
unsafe { GetComputerNameExW(format, name.as_mut_ptr(), &mut len) } != 0
&& len > 0 && (len as usize) < name.len(),
"HOSTNAME_QUERY"
);
let hostname = String::from_utf16(&hostname[..len as usize])?;
Ok(String::from_utf16(&name[..len as usize])?)
}
fn install_date() -> Option<DateTime<Utc>> {
let key = wide(r"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
let name = wide("InstallDate");
let mut seconds = 0_u32;
let mut bytes = size_of::<u32>() as u32;
let status = unsafe { RegGetValueW(HKEY_LOCAL_MACHINE,key.as_ptr(),name.as_ptr(),RRF_RT_REG_DWORD,
ptr::null_mut(),ptr::from_mut(&mut seconds).cast(),&mut bytes) };
(status == 0 && bytes as usize == size_of::<u32>() && seconds > 0)
.then(|| DateTime::from_timestamp(i64::from(seconds), 0))
.flatten().filter(|time| *time <= Utc::now())
}
pub fn snapshot() -> Result<Value> {
snapshot_with_boot(None)
}
pub fn snapshot_with_boot(booted_at: Option<DateTime<Utc>>) -> Result<Value> {
let started = Utc::now();
let hostname = computer_name(ComputerNameDnsHostname)?;
let volume = wide(std::env::var("SystemDrive").context("SYSTEM_DRIVE")? + "\\");
let mut available = 0;
let mut total = 0;
@@ -277,7 +297,7 @@ pub fn snapshot() -> Result<Value> {
let mut snapshot = json!({"os":os,"hostname":hostname,"architecture":std::env::consts::ARCH,"root_total_bytes":total,"root_available_bytes":available,"root_available_inodes":null,
"collection_started_at":started,"collection_completed_at":completed,
"observations":[
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build}},
{"scope":"windows.os","source_id":"windows.registry:CurrentVersion;GetComputerNameExW;Kernel-General/12","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"product_name":product,"display_version":display,"build":build,"installed_at":install_date(),"booted_at":booted_at}},
{"scope":"windows.volumes","source_id":"windows.win32:GetDiskFreeSpaceExW","observed_at":completed,"quality":"valid","completeness":"partial","truncated":false,"error_code":null,"data":{"system_volume_total_bytes":total,"system_volume_available_bytes":available}},
{"scope":"windows.inodes","source_id":"windows.win32","observed_at":completed,"quality":"unsupported","completeness":"unknown","truncated":false,"error_code":"NOT_APPLICABLE","data":null}
]});
@@ -288,7 +308,7 @@ pub fn snapshot() -> Result<Value> {
snapshot["collection_completed_at"] = json!(Utc::now());
Ok(snapshot)
}
pub async fn boot_id() -> Result<String> {
pub async fn boot_identity() -> Result<(String, DateTime<Utc>)> {
// Fixed passive query only. Never interpolates a job or caller-supplied code.
// Avoid Win32_Product: it can cause MSI consistency checks and repairs.
let executable = Path::new(&std::env::var("SystemRoot")?)
@@ -324,7 +344,14 @@ if ($nodes.Count -ne 1) { throw 'BOOT_START_TIME' }
.try_into()?;
bytes[6] = (bytes[6] & 15) | 0x80;
bytes[8] = (bytes[8] & 63) | 0x80;
Ok(uuid::Uuid::from_bytes(bytes).to_string())
let ticks = text.parse::<i64>()?.checked_sub(621_355_968_000_000_000).context("BOOT_EPOCH")?;
let time = DateTime::from_timestamp(ticks.div_euclid(10_000_000), ticks.rem_euclid(10_000_000) as u32 * 100)
.context("BOOT_EPOCH")?;
Ok((uuid::Uuid::from_bytes(bytes).to_string(),time))
}
pub async fn boot_id() -> Result<String> {
boot_identity().await.map(|(id, _)| id)
}
#[cfg(test)]
+15 -1
View File
@@ -299,9 +299,13 @@ pub(crate) fn run_observed(
"SYSTEM_DRIVE_REQUIRED"
);
let system_drive = &system_text[..2];
let computer = crate::native::computer_name(
windows_sys::Win32::System::SystemInformation::ComputerNameNetBIOS,
)?;
for value in [
format!("SystemDrive={system_drive}"),
format!("COMPUTERNAME={computer}"),
format!("PATH={}\\System32;{}", system.display(), system.display()),
format!("SystemDrive={system_drive}"),
format!("SystemRoot={}", system.display()),
format!("TEMP={}", cwd.display()),
format!("TMP={}", cwd.display()),
@@ -455,6 +459,16 @@ pub(crate) fn run_observed(
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn script_process_receives_the_native_computer_name() {
let args = ["-NoProfile", "-NonInteractive", "-Command",
"if (!$env:COMPUTERNAME -or $env:COMPUTERNAME -ine [Environment]::MachineName) { exit 1 }"]
.map(OsString::from);
let output = run(&crate::actions::powershell().unwrap(), &args,
&std::env::temp_dir(), 20, 4096, &AtomicBool::new(false)).unwrap();
assert_eq!(output.exit_code, Some(0));
}
#[test]
fn arguments_never_become_shell_code_and_trailing_slashes_are_quoted() {
assert_eq!(
+30 -6
View File
@@ -289,6 +289,25 @@ impl Device {
}
}
/// Report the signed release layout of the already authenticated live SCM/IPC pair.
/// The server independently verifies the pair's catalog release and helper digest.
pub(crate) fn managed_script_release(pin: &crate::helper_ipc::Pin) -> Result<Uuid> {
let dir = pin.helper.binary.parent().context("missing installed helper directory")?;
let release = dir.file_name().and_then(|n| n.to_str()).context("missing release directory")?;
let id = Uuid::parse_str(release)?;
ensure!(release == id.to_string() && dir == generation(id)
&& pin.agent.binary == dir.join(AGENT) && pin.helper.binary == dir.join(HELPER),
"managed scripts require a pinned release pair");
let path = dir.join("manifest.json");
let raw = protected(&path, rmm_updater::MAX_MANIFEST_BYTES)?;
let manifest: ReleaseManifest = serde_json::from_slice(&raw)?;
ensure!(manifest.platform == VERIFY && manifest.release_id == id
&& manifest.artifacts[0].sha256 == pin.agent.binary_sha256
&& manifest.artifacts[1].sha256 == pin.helper.binary_sha256,
"managed helper differs from installed release manifest");
Ok(id)
}
fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
let root = generation(installed.release_id);
let raw = protected(&root.join("manifest.json"), rmm_updater::MAX_MANIFEST_BYTES)?;
@@ -319,10 +338,16 @@ fn local_manifest(installed: &Installed) -> Result<ReleaseManifest> {
// Only typed release UUIDs enter the fixed SCM command. The actual service path,
// LocalService account and absence of an independently provisioned helper are checked again on the target.
fn select(from: Uuid, to: Uuid) -> Result<()> {
fn select(from: &Installed, to: &Installed) -> Result<()> {
let manifest = local_manifest(to)?;
let [agent, helper] = manifest.artifacts.as_slice() else {
anyhow::bail!("incomplete installed release pair");
};
let script = include_str!("release_service_switch.ps1")
.replace("FROM_UUID", &from.to_string())
.replace("TO_UUID", &to.to_string());
.replace("FROM_UUID", &from.release_id.to_string())
.replace("TO_UUID", &to.release_id.to_string())
.replace("SELECTED_AGENT_SHA256", &agent.sha256)
.replace("SELECTED_HELPER_SHA256", &helper.sha256);
let windows = std::env::var_os("SystemRoot").context("Windows directory")?;
let ps = Path::new(&windows).join(r"System32\WindowsPowerShell\v1.0\powershell.exe");
let result = Command::new(ps)
@@ -338,8 +363,7 @@ fn select(from: Uuid, to: Uuid) -> Result<()> {
Ok(())
}
async fn rollback(t: &Transition) -> Result<()> {
local_manifest(&t.old)?;
select(t.new.release_id, t.old.release_id)?;
select(&t.new, &t.old)?;
write_record("rejected-release.json", &t.new)?;
fs::remove_file(record_path(INTENT))?;
Ok(())
@@ -494,7 +518,7 @@ async fn cycle() -> Result<()> {
let t = Transition { old: active, new };
write_record(INTENT, &t)?;
let start = chrono::Utc::now();
let selected = select(t.old.release_id, t.new.release_id);
let selected = select(&t.old, &t.new);
if selected.is_ok() {
for _ in 0..18 {
if let Ok(h) = device.health().await
@@ -4,6 +4,31 @@ function Get-Image([string]$Id) {
$image = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-agent-windows.exe')
return '"' + $image + '" --service --config "' + $configPath + '"'
}
function Get-HelperImage([string]$Id) {
Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery\releases\' + $Id + '\rmm-helper-windows.exe')
}
function Wait-Stopped([string]$Name) {
$control = Get-Service $Name
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
}
}
function Select-Image($Service, [string]$Image) {
if ($Service.PathName -cne $Image) {
$result = Invoke-CimMethod -InputObject $Service -MethodName Change -Arguments @{PathName=$Image}
if ($result.ReturnValue -ne 0) { throw 'SCM path change failed.' }
}
}
function Replace-Pin([string]$Path, [string]$Value) {
$temp = "$Path.next-$([Guid]::NewGuid())"
try {
[IO.File]::WriteAllText($temp, $Value, [Text.UTF8Encoding]::new($false))
[IO.File]::Replace($temp, $Path, [NullString]::Value)
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
$configPath = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery\config.json'
$from = Get-Image 'FROM_UUID'
$to = Get-Image 'TO_UUID'
@@ -13,16 +38,53 @@ if ($config.PSObject.Properties['enable_jobs'] -and $config.enable_jobs) {
if (-not $config.PSObject.Properties['localservice_time_policy'] -or
$config.localservice_time_policy -cne (Join-Path (Split-Path $configPath) 'job-time.json')) { throw 'Job-enabled pair requires a coordinated helper handoff.' }
}
$managed = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$helper = Get-CimInstance -ClassName Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if (-not $service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cnotin @($from,$to) -or (Get-Service 'RmmDiscoverySystemHelper' -ErrorAction SilentlyContinue)) { throw 'Unexpected service configuration.' }
if ($service.PathName -cne $to) {
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Stopped') {
$control.Stop()
$control.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(45))
$service.PathName -cnotin @($from,$to) -or ([bool]$helper -ne [bool]$managed)) { throw 'Unexpected service configuration.' }
if ($managed) {
$helperExe = Get-HelperImage 'TO_UUID'
$helperTo = '"' + $helperExe + '" --service'
$helperFrom = '"' + (Get-HelperImage 'FROM_UUID') + '" --service'
if ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cnotin @($helperFrom,$helperTo)) { throw 'Unexpected managed helper service.' }
$policyRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$settingsPath = Join-Path $policyRoot 'helper.json'
$settings = Get-Content -LiteralPath $settingsPath -Raw | ConvertFrom-Json
if ($settings.schema_version -ne 5) { throw 'Managed helper settings required.' }
# Old renderers require this input; the successor preserves the complete
# existing scope, including an absent long Windows Update permission.
$longRuntime = 3600
if ($settings.PSObject.Properties['windows_update_max_runtime_seconds']) { $longRuntime = $settings.windows_update_max_runtime_seconds }
$rendered = ([ordered]@{binding=$settings.binding; release_id='TO_UUID'
agent_sha256='SELECTED_AGENT_SHA256'; helper_sha256='SELECTED_HELPER_SHA256'
max_runtime_seconds=$longRuntime; managed_scripts=$true} | ConvertTo-Json -Depth 6 -Compress) |
& $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Signed successor helper could not render its pins.' }
$pins = $rendered | ConvertFrom-Json
# Rollback may select an earlier renderer. Compare the complete protected
# policy, allowing only the two release image paths and digests to change.
$scope = $pins.helper_settings | ConvertFrom-Json
if ($scope.agent.binary -cne (Join-Path (Split-Path $helperExe) 'rmm-agent-windows.exe') -or
$scope.helper.binary -cne $helperExe -or $scope.agent.binary_sha256 -cne 'SELECTED_AGENT_SHA256' -or
$scope.helper.binary_sha256 -cne 'SELECTED_HELPER_SHA256') { throw 'Rendered helper image pins differ from the selected release.' }
foreach ($role in @('agent','helper')) {
$scope.$role.binary = $settings.$role.binary
$scope.$role.binary_sha256 = $settings.$role.binary_sha256
}
$res = Invoke-CimMethod -InputObject $service -MethodName Change -Arguments @{PathName=$to}
if ($res.ReturnValue -ne 0) { throw 'SCM path change failed.' }
if (($scope | ConvertTo-Json -Depth 12 -Compress) -cne ($settings | ConvertTo-Json -Depth 12 -Compress)) {
throw 'Agent release cannot change the managed script authorization.'
}
Wait-Stopped 'RmmDiscoveryWindows'
Wait-Stopped 'RmmDiscoverySystemHelper'
Replace-Pin $settingsPath $pins.helper_settings
Replace-Pin (Join-Path $policyRoot 'agent-pin.json') $pins.agent_pin
Select-Image $helper $helperTo
Select-Image $service $to
Start-Service 'RmmDiscoverySystemHelper'
(Get-Service 'RmmDiscoverySystemHelper').WaitForStatus('Running', [TimeSpan]::FromSeconds(45))
} elseif ($service.PathName -cne $to) {
Wait-Stopped 'RmmDiscoveryWindows'
Select-Image $service $to
}
$control = Get-Service 'RmmDiscoveryWindows'
if ($control.Status -ne 'Running') {
+248 -47
View File
@@ -8,7 +8,7 @@ use rmm_agent_core::{
reconcile::{self, SyncClock},
};
use rmm_agent_windows::certificate_rotation::{ProtectedKeyFiles, RotationStore};
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
use rmm_agent_windows::{CAPABILITIES, inventory, job_binding::readonly_binding, journal::Journal, native};
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
use rmm_protocol::*;
use rusqlite::{Connection, OptionalExtension};
@@ -40,6 +40,8 @@ struct Config {
localservice_time_policy: Option<PathBuf>,
#[serde(default)]
windows_update_helper: bool,
#[serde(default)]
managed_script_helper: bool,
// Explicit protected opt-in only; this flag never qualifies a clock or pins.
#[serde(default)]
enable_jobs: bool,
@@ -90,6 +92,25 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
])
}
impl Config {
fn supports_customer_transfer(&self) -> bool {
cfg!(feature = "system-helper") && self.enable_jobs
&& self.localservice_time_policy.is_some() && self.job_binding_file.is_none()
&& !self.windows_echo_probe_only && !self.windows_update_helper
}
fn allows_script_action(&self, action: &Action, identity: &str) -> bool {
let Action::RunScript { interpreter, windows_execution_profile, .. } = action else {
return false;
};
let system = match &self.localservice_time_policy {
Some(_) => (self.managed_script_helper && action.full_maintenance())
|| (self.windows_update_helper && action.windows_update_or_identity_probe()),
None => self.job_binding_file.is_some() && action.full_maintenance(),
};
interpreter == "powershell"
&& windows_execution_profile.is_none_or(|p| self.profile_enabled(p))
&& action.valid_execution_identity(identity)
&& (identity == "agent_service" || (identity == "system" && system))
}
fn profile_enabled(&self, profile: rmm_domain::jobs::WindowsExecutionProfile) -> bool {
self.enable_jobs
&& (self.job_binding_file.is_some() || self.localservice_time_policy.is_some())
@@ -99,7 +120,8 @@ impl Config {
fn read(path: &Path) -> Result<Self> {
let raw = protected_read(path, 32768)?;
let config: Self = serde_json::from_slice(&raw)?;
if config.windows_update_helper {
ensure!(!(config.windows_update_helper && config.managed_script_helper), "AMBIGUOUS_ENROLLED_HELPER");
if config.windows_update_helper || config.managed_script_helper {
ensure!(config.localservice_time_policy.is_some() && cfg!(feature = "system-helper"), "ENROLLED_WINDOWS_UPDATE_HELPER_REQUIRED");
}
if let Some(policy) = &config.localservice_time_policy {
@@ -166,6 +188,16 @@ fn protected_read(path: &Path, max: usize) -> Result<Vec<u8>> {
);
Ok(fs::read(path)?)
}
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
let key = match previous {
Some(raw) => KeyPair::from_pem(std::str::from_utf8(raw)?)?,
None => KeyPair::generate()?,
};
let mut parameters = CertificateParams::default();
parameters.distinguished_name.push(DnType::CommonName, "customer-transfer");
let csr = parameters.serialize_request(&key)?.pem()?;
Ok((key.serialize_pem().into_bytes(), csr))
}
async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
let state = &config.state_directory;
let identity = state.join("identity.json");
@@ -608,12 +640,14 @@ struct Agent {
config: Config,
reported_version: String,
release_job_guard: Option<fs::File>,
transfer_gate: Option<fs::File>,
identity: EnrollmentResponse,
ca: Vec<u8>,
journal: Journal,
certificates: RotationStore,
key_files: ProtectedKeyFiles,
boot: String,
booted_at: chrono::DateTime<Utc>,
instance: String,
started: Instant,
binding: Option<Binding>,
@@ -817,7 +851,8 @@ impl Agent {
&identity.certificate_pem,
&identity.private_key_pem,
)?;
let helper = if self.config.localservice_time_policy.is_some() && !self.config.windows_update_helper {
let helper = if self.config.localservice_time_policy.is_some()
&& !self.config.windows_update_helper && !self.config.managed_script_helper {
None
} else { rmm_agent_windows::helper_runtime::Client::discover(
&self.identity.agent_id,
@@ -916,7 +951,7 @@ impl Agent {
let _ = time_helper.time_close(generation).await;
}
helper_report.record(&helper_state, "system_helper", &result);
tokio::time::sleep(mode.interval(result.is_ok())).await;
tokio::time::sleep(mode.helper_interval(result.is_ok())).await;
}
let _ = time_helper.time_close(generation).await;
}));
@@ -1405,8 +1440,7 @@ impl Agent {
Ok(())
}
fn supported_job(&self, job: &rmm_domain::jobs::JobPayload) -> bool {
if self.config.localservice_time_policy.is_some() && job.execution_identity != "agent_service"
&& !(self.config.windows_update_helper && job.execution_identity == "system" && job.action.windows_update_or_identity_probe()) {
if !self.config.allows_script_action(&job.action, &job.execution_identity) {
return false;
}
if self.config.windows_echo_probe_only
@@ -1543,12 +1577,54 @@ impl Agent {
}
Ok(false)
}
async fn stage_customer_transfer(&mut self) -> Result<bool> {
if !self.config.supports_customer_transfer() || self.running.is_some()
|| self.prepared || self.deferred_sync.is_some() || self.deferred_permit.is_some()
|| self.release_job_guard.is_some() {
return Ok(false);
}
let (Some(binding), Some(ledger)) = (&self.binding, &self.ledger) else {
return Ok(false);
};
if !rmm_agent_core::customer_transfer::idle(self.journal.connection(), ledger)? {
return Ok(false);
}
#[cfg(feature = "system-helper")]
if self.helper_control_busy_for_sync() || self.update_health.is_some() {
return Ok(false);
}
// Keep the release service from replacing the program during the handoff.
let binding = binding.clone();
if !self.reserve_release_gate()? {
return Ok(false);
}
let result = async {
let identity = self.certificates.current(
self.journal.connection(), &self.key_files, Utc::now().timestamp(),
)?;
let client = crate::https_channel::mtls_client(
self.config.connect_address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
)?;
let base = format!("https://{}:{}", self.config.server_name, self.config.connect_address.port());
rmm_agent_core::customer_transfer::stage(
&client, &base, &self.config.state_directory, &binding, transfer_csr,
).await
}.await;
let gate = self.release_job_guard.take();
if matches!(&result, Ok(true)) {
self.transfer_gate = gate;
}
result
}
fn capabilities(&self) -> Vec<String> {
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
#[cfg(target_env = "gnu")]
caps.push("agent.release.windows.gnu/1".into());
// queue_update_observation emits the passive update status in every profile.
caps.push("agent.update/1".into());
if self.config.supports_customer_transfer() {
caps.push(rmm_domain::customer_transfer::CAPABILITY.into());
}
if self.config.windows_echo_probe_only {
caps.push("windows.echo-probe/1".into());
}
@@ -1558,9 +1634,6 @@ impl Agent {
&& native::require_local_service().is_ok()
{
caps.push("rmm.sync.v1".into());
if !self.config.windows_echo_probe_only {
caps.push("refresh_inventory".into());
}
if rmm_agent_windows::actions::powershell().is_ok() {
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
if self.config.profile_enabled(
@@ -1573,10 +1646,10 @@ impl Agent {
if !self.config.windows_echo_probe_only
&& let Some(helper) = &self.helper
{
caps.extend(helper.qualified_capabilities());
if helper.update_observer_configured()
&& self.update_observer.cached().is_some_and(|r|r.observation.predecessor.as_ref().is_some_and(|p|p.helper_sha256==helper.helper_binary_hash())) {
for cap in self.update_observer.capabilities(){if !caps.contains(&cap){caps.push(cap);}}
if self.config.job_binding_file.is_some()
|| self.config.managed_script_helper || self.config.windows_update_helper
{
caps.extend(helper.qualified_capabilities());
}
}
}
@@ -1778,20 +1851,40 @@ impl Agent {
let prepared = sync.prepare(
self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context,
context.clone(),
helper,
&self.clock,
);
#[cfg(feature = "system-helper")]
if helper.is_some()
&& prepared
.as_ref()
.is_err_and(|error| error.to_string() == "SYSTEM_HELPER_APPLY_UNCONFIRMED")
{
// This authenticated readback already established why another
// capture cannot advance this channel.
self.helper_apply_unconfirmed = true;
}
let prepared = match (prepared, helper) {
(Err(error), Some(snapshot)) if error.to_string() == "SYSTEM_HELPER_APPLY_UNCONFIRMED" => {
self.helper_apply_unconfirmed = true;
// The helper supplied a fresh authenticated snapshot on its serialized
// lane. Only an idle actor may ask the core to prove an exact missed ACK.
if self.running.is_some() || self.prepared || self.deferred_sync.is_some()
|| self.deferred_permit.is_some() || self.helper_control.is_some()
|| self.helper_probe.is_some() || self.update_pending
|| self.update_prefetch.is_some() || self.update_health.is_some()
{
return Err(error);
}
use rmm_agent_windows::helper_runtime::intent;
let idle = if Path::new(intent::DB).try_exists()? {
intent::Store::open(false)?.pending()?.is_empty()
} else {
snapshot.attempts.is_empty()
};
if !idle {
return Err(error);
}
sync.prepare_with_closed_control_idle(
self.journal.connection_mut(),
self.ledger.as_ref().context("LEDGER_REQUIRED")?,
context, Some(snapshot), &self.clock, true,
)
}
(ordinary, _) => ordinary,
};
let prepared = prepared?;
#[cfg(feature = "system-helper")]
{
@@ -2386,8 +2479,8 @@ impl Agent {
if self.journal.count()? > 0 || !jobs::events(self.journal.connection())?.is_empty() {
return Ok(false);
}
let data = serde_json::to_vec(&native::snapshot()?)?;
ensure!(data.len() <= 32768, "WINDOWS_INVENTORY_LIMIT");
let data = serde_json::to_vec(&native::snapshot_with_boot(Some(self.booted_at))?)?;
ensure!(data.len() <= 256 * 1024, "WINDOWS_INVENTORY_LIMIT");
let envelope = self.envelope(
generation,
Payload::InventorySnapshot(InventorySnapshot {
@@ -2503,7 +2596,7 @@ impl Agent {
};
self.renew_certificate(admission.as_deref()).await?;
}
self.boot = native::boot_id().await?;
(self.boot, self.booted_at) = native::boot_identity().await?;
let advertised = self.capabilities();
let hello = self.envelope(
0,
@@ -2568,6 +2661,7 @@ impl Agent {
let mut rotation_at = Instant::now();
let mut rotation_after = Duration::from_secs(30);
let mut heartbeat = Instant::now() - Duration::from_secs(60);
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_secs(30);
let mut tick = tokio::time::interval(Duration::from_millis(20));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
@@ -2619,9 +2713,12 @@ impl Agent {
// A transiently stale clock skips this tick; it must not end the session.
if let Ok(now)=self.clock.now() && let Some(offer)=jobs::next_at(self.journal.connection(),now)? {
let job=self.binding.as_ref().context("JOB_BINDING_REQUIRED")?.job(&offer.payload_bytes)?;
ensure!(self.scope_permits(&offer,&job),"WINDOWS_ECHO_OFFER_OUT_OF_SCOPE");
if now>=job.start_before {self.record(generation,&offer,"",jobs::no_start("expired","START_DEADLINE_EXPIRED"))?;needs_sync=true;}
else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") {
else if !self.config.allows_script_action(&job.action, &job.execution_identity) || !self.scope_permits(&offer, &job) {
// Only next_at's accepted row is known to have no reserved permit.
self.record(generation, &offer, "", jobs::no_start("failed", "LEGACY_ACTION_RETIRED"))?;
needs_sync = true;
} else if now-chrono::Duration::seconds(2)>=job.not_before && self.ready_identity(generation,job.execution_identity=="system") {
#[cfg(feature="system-helper")]
let prefetched=self.prefetch_update(generation,&offer,&job).await?;
#[cfg(not(feature="system-helper"))]
@@ -2707,6 +2804,11 @@ impl Agent {
if rotation_at.elapsed() >= rotation_after {
rotation_at = Instant::now();
rotation_after = Duration::from_secs(30);
match self.stage_customer_transfer().await {
Ok(true) => return Ok(()),
Ok(false) => (),
Err(_) => eprintln!("CUSTOMER_TRANSFER_PENDING"),
}
let now = Utc::now().timestamp();
if self
.certificates
@@ -2739,9 +2841,19 @@ impl Agent {
// inventory offline. Retry setup at the next heartbeat.
eprintln!("PASSIVE_SIGNED_TIME_UNAVAILABLE");
}
let cpu = inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = inventory::physical_memory();
let payload = Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.map(|(available, _)| available),
ram_total_bytes: memory.map(|(_, total)| total),
}),
});
let h = self.envelope(generation, payload)?;
channel.send(&h).await?;
@@ -2751,6 +2863,7 @@ impl Agent {
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}),
)?;
channel.poll(poll).await?;
@@ -2770,7 +2883,7 @@ impl Agent {
self.replay(&channel, generation).await?;
replay = Instant::now();
}
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(86400) {
if !stop.load(Ordering::SeqCst) && inventory.elapsed() >= Duration::from_secs(300) {
self.queue_inventory(generation)?;
inventory = Instant::now();
}
@@ -2855,7 +2968,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
);
let path = Path::new(&arguments[2]);
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
let config = Config::read(path)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()?;
runtime.block_on(async {
let mut gate = None;
loop {
match run_service_binding(path, stop, gate.take()).await? {
Some(held) => gate = Some(held),
None => return Ok(()),
}
}
})
}
async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_guard: Option<fs::File>) -> Result<Option<fs::File>> {
let mut config = Config::read(path)?;
native::require_local_service()?;
ensure!(
config.state_directory.is_absolute(),
@@ -2871,21 +3000,50 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
let child = child?;
native::private_path(&child.path(), child.file_type()?.is_dir())?;
}
let journal = Journal::open(&config.state_directory)?;
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.worker_threads(2)
.build()?;
runtime.block_on(async move {
let identity = enrollment(&config, &ca).await?;
let mut journal=journal;
if rmm_agent_core::customer_transfer::pending(&config.state_directory)? {
#[cfg(feature = "system-helper")]
{
ensure!(config.supports_customer_transfer(), "TRANSFER_CONFIG");
let policy = config.localservice_time_policy.as_deref().context("TRANSFER_POLICY")?;
let signer = rmm_agent_windows::signed_clock::enrolled_transfer_signer(policy)?;
loop {
if stop.load(Ordering::SeqCst) {
return Ok(None);
}
match rmm_agent_core::customer_transfer::activate(&config.state_directory, &signer) {
Ok(()) => break,
Err(error) if error.downcast_ref::<std::io::Error>()
.is_some_and(|e| matches!(e.raw_os_error(), Some(32 | 33))) => {
// Another service can briefly hold a read-only handle.
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err(error) => return Err(error),
}
}
}
#[cfg(not(feature = "system-helper"))]
anyhow::bail!("TRANSFER_CONFIG");
}
drop(release_guard);
let mut journal = Journal::open(&config.state_directory)?;
let identity = enrollment(&config, &ca).await?;
journal.pin_identity(&identity.agent_id)?;
let boot = native::boot_id().await?;
let (boot, booted_at) = native::boot_identity().await?;
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
#[cfg(feature = "system-helper")]
let binding = if let Some(policy) = &config.localservice_time_policy {
Some(rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?)
} else { binding };
let (binding, installed_tenant) = if let Some(policy) = &config.localservice_time_policy {
let mut enrolled = rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?;
let installed = enrolled.tenant_id;
if config.supports_customer_transfer()
&& let Some(target) = rmm_agent_core::customer_transfer::assigned_tenant(
&config.state_directory, &identity, &enrolled.public_key_hex,
)? {
enrolled.tenant_id = target;
// Elevated helpers are bound to the original installation.
config.managed_script_helper = false;
}
(Some(enrolled), Some(installed))
} else { (binding, None) };
if let Some(binding)=&binding {
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
native::private_path(&config.state_directory.join("jobs"),true)?;
@@ -2902,7 +3060,9 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
#[cfg(feature = "system-helper")]
let clock = if let Some(policy) = &config.localservice_time_policy {
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(binding,policy.clone()).for_generation(0) }
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
).for_generation(0) }
} else { clock };
let mut config=config;
if config.enable_jobs {
@@ -2924,12 +3084,14 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
config,
reported_version: installed_version()?,
release_job_guard: None,
transfer_gate: None,
identity,
ca,
journal,
certificates,
key_files,
boot,
booted_at,
instance: Uuid::new_v4().to_string(),
started: Instant::now(), binding, ledger, _ledger_file:ledger_file, clock, sync,
#[cfg(feature="system-helper")]
@@ -2987,6 +3149,12 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
if let Err(error) = agent.session(stop).await {
record_session_error(&agent.config.state_directory, &error);
}
if let Some(guard) = agent.transfer_gate.take() {
if let Some(worker) = agent.readiness_worker.take() {
let _ = worker.await;
}
return Ok(Some(guard));
}
if start.elapsed() > Duration::from_secs(60) {
backoff = 1;
}
@@ -3005,8 +3173,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
tokio::time::sleep(Duration::from_millis(250)).await;
}
}
Ok(())
})
Ok(None)
}
pub fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
@@ -3026,8 +3193,8 @@ pub fn main() -> Result<()> {
}
if args == ["--native-probe"] {
let runtime = tokio::runtime::Runtime::new()?;
let boot = runtime.block_on(native::boot_id())?;
let inventory = native::snapshot()?;
let (boot, booted_at) = runtime.block_on(native::boot_identity())?;
let inventory = native::snapshot_with_boot(Some(booted_at))?;
println!(
"{}",
serde_json::json!({"platform":"windows","architecture":std::env::consts::ARCH,"hostname_available":!inventory["hostname"].as_str().unwrap_or("").is_empty(),"system_volume_available":inventory["root_available_bytes"].as_u64().is_some(),"inodes":null,"boot_id":boot,"capabilities":CAPABILITIES,"jobs_supported":false})
@@ -3067,6 +3234,40 @@ fn record_session_error(state: &Path, error: &anyhow::Error) {
mod tests {
use super::*;
#[cfg(feature = "system-helper")]
#[test]
fn accepted_actions_require_the_current_local_script_scope_before_a_permit() {
let mut config: Config = serde_json::from_value(serde_json::json!({
"server_name":"fixture", "connect_address":"127.0.0.1:443", "ca_file":"ca",
"state_directory":"state", "enrollment_token_file":"token", "transport":"https",
"localservice_time_policy":"job-time.json", "enable_jobs":true,
"windows_execution_profile":"powershell_51_remote_signed"
})).unwrap();
let mut script: Action = serde_json::from_value(serde_json::json!({
"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 1",
"arguments":[],"expected_stdout":null,"windows_execution_profile":"powershell_51_remote_signed"
})).unwrap();
assert!(config.allows_script_action(&script, "agent_service"));
let legacy = Action::RefreshInventory { scope: "windows.base".into() };
assert!(!config.allows_script_action(&legacy, "agent_service"));
assert!(!config.allows_script_action(&script,"system"));
let Action::RunScript { ref mut privileged_script_profile, .. } = script else { unreachable!() };
*privileged_script_profile = Some(rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1);
config.windows_update_helper = true;
assert!(!config.allows_script_action(&script,"system"));
config.windows_update_helper = false;
config.managed_script_helper = true;
assert!(config.allows_script_action(&script, "system"));
assert!(!config.allows_script_action(&legacy, "system"));
config.localservice_time_policy = None;
config.managed_script_helper = false;
config.job_binding_file = Some("job-binding.json".into());
assert!(!config.allows_script_action(&legacy, "agent_service"));
assert!(!config.allows_script_action(&legacy, "system"));
assert!(config.allows_script_action(&script, "system"));
config.job_binding_file = None;
assert!(!config.allows_script_action(&script, "system"));
}
#[cfg(feature = "system-helper")]
#[tokio::test]
async fn gate_close_retains_the_original_helper_apply_worker_without_replaying_it() {
let (sender, receiver) = tokio::sync::oneshot::channel::<()>();
+50 -11
View File
@@ -31,6 +31,15 @@ impl SamplingMode {
(Self::Jobs, false) => Duration::from_millis(500),
}
}
pub fn helper_interval(self, verified: bool) -> std::time::Duration {
match (self, verified) {
// Each refresh verifies both service images over the pipe. A held
// signed time sample remains usable for up to five minutes.
(Self::Jobs, true) => std::time::Duration::from_secs(5),
_ => self.interval(verified),
}
}
}
fn independent_time_key(time_key_hex: &str, job_key_hex: &str) -> Result<[u8; 32]> {
@@ -802,10 +811,7 @@ mod installed {
tenant_id: Uuid,
job_signing_public_key_hex: String,
}
pub fn enrolled_binding(
policy: &Path,
registration: &rmm_protocol::EnrollmentResponse,
) -> Result<rmm_agent_core::auth::Binding> {
fn installed_policy(policy: &Path) -> Result<LocalPolicy> {
crate::job_binding::check_admin_readonly(policy)?;
ensure!(
std::fs::metadata(policy)?.len() <= MAX_CONFIG_BYTES as u64,
@@ -816,6 +822,16 @@ mod installed {
p.schema_version == 1 && !p.tenant_id.is_nil() && digest(&p.job_signing_public_key_hex),
"INSTALLED_JOB_TRUST"
);
Ok(p)
}
pub fn enrolled_transfer_signer(policy: &Path) -> Result<String> {
Ok(installed_policy(policy)?.job_signing_public_key_hex)
}
pub fn enrolled_binding(
policy: &Path,
registration: &rmm_protocol::EnrollmentResponse,
) -> Result<rmm_agent_core::auth::Binding> {
let p = installed_policy(policy)?;
let binding = rmm_agent_core::auth::Binding {
tenant_id: p.tenant_id,
agent_id: Uuid::parse_str(&registration.agent_id)?,
@@ -963,6 +979,7 @@ mod installed {
generation: u64,
binding: &rmm_agent_core::auth::Binding,
policy_file: &Path,
installed_tenant: Uuid,
helper: Option<&ipc::PeerPin>,
) -> Result<Self> {
let mut failure_fence = ConstructorFailureFence { armed: true };
@@ -1002,7 +1019,7 @@ mod installed {
.map(|(id, key)| Ok((id, independent_time_key(&key, &binding.public_key_hex)?)))
.collect::<Result<BTreeMap<_, _>>>()?;
ensure!(
p.tenant_id == binding.tenant_id
p.tenant_id == installed_tenant
&& p.job_signing_public_key_hex == binding.public_key_hex,
"TIME_POLICY_BINDING"
);
@@ -1394,7 +1411,7 @@ mod installed {
pub struct RuntimeClock {
role: Role,
enrolled_helper: Option<ipc::PeerPin>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>,
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
}
#[derive(Clone)]
@@ -1414,14 +1431,16 @@ mod installed {
pub fn enrolled_local_service(
binding: rmm_agent_core::auth::Binding,
policy: std::path::PathBuf,
installed_tenant: Uuid,
) -> Self {
let mut value = Self::new(Role::Agent);
value.local_policy = Some((binding, policy));
value.local_policy = Some((binding, policy, installed_tenant));
value
}
pub fn enrolled_windows_update_helper(binding: rmm_agent_core::auth::Binding, helper: ipc::PeerPin) -> Self {
let mut value = Self::new(Role::SystemHelper);
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json")));
let installed_tenant = binding.tenant_id;
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json"), installed_tenant));
value.enrolled_helper = Some(helper);
value
}
@@ -1440,8 +1459,8 @@ mod installed {
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
self.close()?;
let clock = match &self.local_policy {
Some((binding, policy)) => {
SignedClock::open_local_service(generation, binding, policy, self.enrolled_helper.as_ref()).await?
Some((binding, policy, installed_tenant)) => {
SignedClock::open_local_service(generation, binding, policy, *installed_tenant, self.enrolled_helper.as_ref()).await?
}
None => SignedClock::open(self.role, generation).await?,
};
@@ -1561,7 +1580,7 @@ mod installed {
#[cfg(all(windows, feature = "system-helper"))]
pub use installed::{
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
enrolled_binding,
enrolled_binding, enrolled_transfer_signer,
};
#[cfg(test)]
@@ -1637,6 +1656,26 @@ mod tests {
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn helper_sampling_spaces_successes_and_retries_failures_quickly() {
use std::time::Duration;
assert_eq!(
SamplingMode::Jobs.helper_interval(true),
Duration::from_secs(5)
);
assert_eq!(
SamplingMode::Jobs.helper_interval(false),
Duration::from_millis(500)
);
for verified in [false, true] {
assert_eq!(
SamplingMode::Passive.helper_interval(verified),
Duration::from_secs(30)
);
}
}
fn sample(ns: u64) -> Sample {
Sample {
wall_utc_ns: 1_800_000_000_000_000_000 + ns as i64,
+28 -63
View File
@@ -34,7 +34,6 @@ struct Qualification {
pub fn qualified(
pin: &Pin,
clock_qualified: bool,
reboot_privilege_available: Option<bool>,
) -> Result<Vec<String>> {
if !clock_qualified {
return Ok(vec![]);
@@ -42,12 +41,24 @@ pub fn qualified(
pin.validate()?;
let (settings, _handles) = helper_system::read_settings()?;
ensure!(serde_json::to_vec(&settings.pin()?)? == serde_json::to_vec(pin)?, "system qualification pin");
if settings.windows_update_only() {
// The caller has verified an independent helper-role clock and the live
// peer. Only the two built-in scripts pass both local and server gates.
return Ok(vec!["helper.system.v1".into(), format!("helper.binary.sha256:{}",pin.helper.binary_sha256),
format!("helper.policy.sha256:{}",pin.policy_sha256), "system:run_script".into(),
rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()]);
if settings.windows_update_only() || settings.managed_scripts() {
// The caller has verified the live enrolled peer and its independent clock.
let mut caps = vec![
"helper.system.v1".into(),
format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
format!("helper.policy.sha256:{}", pin.policy_sha256),
"system:run_script".into(),
];
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
}
if settings.managed_scripts() {
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
if let Ok(id) = crate::release_service::managed_script_release(pin) {
caps.push(format!("script.helper.release:{id}"));
}
}
return Ok(caps);
}
let ordinary = load_ordinary(pin);
let (q, result_bytes) = match ordinary {
@@ -80,67 +91,21 @@ pub fn qualified(
&& settings.enable_effects,
"system qualification effective policy"
);
if !q.actions.iter().any(|action| action == "run_script") {
return Ok(vec![]);
}
let general = settings.allowed_script_profiles.as_deref() ==
Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]);
let windows_update = settings.windows_update_max_runtime_seconds.is_some();
ensure!(settings.schema_version >= 3 && (general || windows_update), "system script qualification policy");
let mut caps = vec![
"helper.system.v1".into(),
format!("helper.binary.sha256:{}", pin.helper.binary_sha256),
format!("helper.policy.sha256:{}", pin.policy_sha256),
"system:run_script".into(),
];
for action in q.actions {
match action.as_str() {
"run_script" => {
let general = settings.allowed_script_profiles.as_deref() ==
Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]);
let windows_update = settings.windows_update_max_runtime_seconds.is_some();
ensure!(settings.schema_version >= 3 && (general || windows_update), "system script qualification policy");
caps.push("system:run_script".into());
if general { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.to_owned()); }
if windows_update { caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned()); }
}
"set_service_state" => {
ensure!(
!settings.allowed_services.is_empty(),
"system SCM qualification policy"
);
caps.extend(["set_service_state", "system:set_service_state"].map(str::to_string));
}
"ensure_package" => {
ensure!(
settings.schema_version >= 2
&& settings
.allowed_msi_recipe_sha256
.as_ref()
.is_some_and(|v| !v.is_empty())
&& crate::msi_cache::stage_configured(),
"system MSI qualification policy"
);
caps.extend(
[
"ensure_package",
"system:ensure_package",
rmm_domain::windows_execution::MSI_CAPABILITY,
]
.map(str::to_string),
);
}
"reboot" => {
ensure!(
settings.schema_version == 4
&& settings.allow_reboot
&& reboot_privilege_available == Some(true),
"system reboot qualification policy or live token"
);
caps.extend(
[
"reboot",
"system:reboot",
rmm_domain::windows_reboot::CAPABILITY,
]
.map(str::to_string),
);
}
_ => unreachable!("validated qualification action"),
}
}
if general { caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into()); }
if windows_update { caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into()); }
Ok(caps)
}
fn read(path: &Path, max: u64) -> Result<Vec<u8>> {
@@ -49,9 +49,5 @@ impl Observer {
pub fn observation(&self,generation:u64)->AgentUpdateObservation{
self.cached().filter(|v|v.generation==generation).map(|v|v.observation.clone()).unwrap_or_else(||AgentUpdateObservation::not_configured(rmm_agent_windows::release_platform::WIRE,chrono::Utc::now()))
}
pub fn capabilities(&self)->Vec<String>{
let Some(value)=self.cached() else{return vec![];};
let(Some(updater),Some(predecessor))=(&value.observation.updater,&value.observation.predecessor) else{return vec![];};
vec![rmm_domain::agent_update::APPLY_CAPABILITY.into(),rmm_domain::agent_update::CHECK_CAPABILITY.into(),"update_agent".into(),"system:update_agent".into(),"helper.system.v1".into(),format!("updater.binary.sha256:{}",updater.binary_sha256),format!("updater.policy.sha256:{}",updater.policy_sha256),format!("helper.binary.sha256:{}",predecessor.helper_sha256)]
}
}
@@ -1,5 +1,4 @@
//! Render the two public configuration files for the narrowly scoped, enrolled
//! development helper. The operator installs them after reviewing the live pair.
//! Render the enrolled script helper settings and peer pin for installation or a signed pair update.
use crate::{
helper_ipc::{self as ipc, PeerPin},
helper_system::Settings,
@@ -20,6 +19,8 @@ struct Input {
agent_sha256: String,
helper_sha256: String,
max_runtime_seconds: u32,
#[serde(default)]
managed_scripts: bool,
}
pub fn render() -> Result<()> {
@@ -47,8 +48,8 @@ pub fn render() -> Result<()> {
binary_sha256: digest,
})
};
let settings = Settings {
schema_version: 3,
let mut settings = Settings {
schema_version: if data.managed_scripts { 5 } else { 3 },
binding: data.binding,
agent: role(
crate::SERVICE_NAME,
@@ -63,13 +64,26 @@ pub fn render() -> Result<()> {
data.helper_sha256,
)?,
allowed_services: vec![],
max_runtime_seconds: 30,
max_runtime_seconds: if data.managed_scripts { 120 } else { 30 },
enable_effects: true,
allow_reboot: false,
allowed_msi_recipe_sha256: None,
allowed_script_profiles: None,
allowed_script_profiles: data.managed_scripts.then(|| {
vec![rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
}),
windows_update_max_runtime_seconds: Some(data.max_runtime_seconds),
};
if data.managed_scripts && std::path::Path::new(crate::helper_system::CONFIG_PATH).try_exists()? {
// Older fixed workers call this same renderer without a predecessor
// argument. Read the protected local settings before changing image pins.
let (previous, _pins) = crate::helper_system::read_settings()?;
ensure!(
previous.managed_scripts()
&& ipc::binding_hash(&previous.binding)? == ipc::binding_hash(&settings.binding)?,
"MANAGED_SCRIPT_PREDECESSOR_SCOPE"
);
settings = Settings { agent: settings.agent, helper: settings.helper, ..previous };
}
settings.validate()?;
let pin = settings.pin()?;
let result = serde_json::json!({"helper_settings":serde_json::to_string(&settings)?,
+1 -1
View File
@@ -21,7 +21,7 @@ sha2.workspace = true
tokio.workspace = true
tokio-tungstenite.workspace = true
uuid.workspace = true
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
fs2 = "0.4.3"
rmm-domain = { path = "../domain" }
rmm-protocol = { path = "../protocol" }
+5 -285
View File
@@ -1,241 +1,8 @@
//! Approved artifact prefetch before a grant; Full independently admits the handoff.
//! Passive signed-release observations and retained update evidence.
use anyhow::{Context, Result, ensure};
use rmm_domain::{
agent_update::{
APPLY_CAPABILITY, ArtifactDescriptor, ArtifactRole, CHECK_CAPABILITY, Platform,
},
jobs::{Action, JobPayload},
};
use rmm_privileged_helper::{Binding, Request, control, update_admission::Accepted};
use sha2::{Digest, Sha256};
use std::{
fs::{self, File, OpenOptions},
io::{Read, Write},
os::unix::fs::{MetadataExt, OpenOptionsExt},
path::{Path, PathBuf},
time::{Duration, Instant},
};
const MAXIMUM: u64 = 256 * 1024 * 1024;
const CHUNK: u64 = 512 * 1024;
pub struct Prefetch(pub tokio::task::JoinHandle<Result<()>>);
impl Drop for Prefetch {
fn drop(&mut self) {
self.0.abort();
}
}
fn directory(path: &Path, create: bool) -> Result<()> {
if create && !path.try_exists()? {
std::fs::DirBuilder::new().mode(0o700).create(path)?;
}
let m = fs::symlink_metadata(path)?;
ensure!(
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 993 && m.mode() & 0o777 == 0o700,
"UPDATE_PREFETCH_DIRECTORY"
);
Ok(())
}
use std::os::unix::fs::DirBuilderExt;
fn parent(job: &JobPayload) -> Result<PathBuf> {
ensure!(
unsafe { libc::geteuid() } == 993,
"UPDATE_PREFETCH_AGENT_UID"
);
let base = Path::new("/var/lib/rmm-agent-remote");
directory(base, false)?;
let base = base.join("update-downloads");
directory(&base, true)?;
let base = base.join(job.job_id.to_string());
directory(&base, true)?;
let base = base.join(job.attempt_id.to_string());
directory(&base, true)?;
Ok(base)
}
fn label(a: &ArtifactDescriptor) -> &'static str {
match a.role {
ArtifactRole::Agent => "agent.bin",
ArtifactRole::Helper => "helper.bin",
}
}
fn checked(path: &Path, a: &ArtifactDescriptor) -> Result<()> {
let mut f = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(path)?;
let m = f.metadata()?;
ensure!(
m.is_file()
&& m.uid() == 993
&& m.mode() & 0o777 == 0o600
&& m.nlink() == 1
&& m.len() == a.bytes,
"UPDATE_PREFETCH_FILE"
);
let mut h = Sha256::new();
let mut n = 0;
let mut buf = [0; 65536];
loop {
let size = f.read(&mut buf)?;
if size == 0 {
break;
}
n += size as u64;
ensure!(n <= a.bytes, "UPDATE_PREFETCH_LENGTH");
h.update(&buf[..size]);
}
ensure!(
n == a.bytes && format!("{:x}", h.finalize()) == a.sha256,
"UPDATE_PREFETCH_DIGEST"
);
Ok(())
}
pub async fn prefetch(client: reqwest::Client, base: String, job: JobPayload) -> Result<()> {
let Action::UpdateAgent { update } = &job.action else {
anyhow::bail!("UPDATE_ACTION_REQUIRED")
};
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
ensure!(
manifest.validate() && manifest.platform == Platform::LinuxX64,
"UPDATE_PREFETCH_MANIFEST"
);
let pjob = job.clone();
let folder = tokio::task::spawn_blocking(move || parent(&pjob)).await??;
let deadline = Instant::now() + Duration::from_secs(600);
for artifact in manifest.artifacts {
ensure!(
artifact.bytes > 0 && artifact.bytes <= MAXIMUM,
"UPDATE_PREFETCH_LIMIT"
);
let path = folder.join(label(&artifact));
let existing = path.clone();
let desc = artifact.clone();
if tokio::task::spawn_blocking(move || -> Result<bool> {
if existing.try_exists()? {
checked(&existing, &desc)?;
Ok(true)
} else {
Ok(false)
}
})
.await??
{
continue;
}
let stage = folder.join(format!("{}.partial", label(&artifact)));
let stage_path = stage.clone();
let mut file = tokio::task::spawn_blocking(move || {
OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(stage_path)
})
.await??;
let mut offset = 0;
let mut hash = Sha256::new();
while offset < artifact.bytes {
ensure!(
Instant::now() < deadline && chrono::Utc::now() < job.start_before,
"UPDATE_PREFETCH_EXPIRED"
);
let length = CHUNK.min(artifact.bytes - offset);
let url = format!(
"{base}/agent/v1/update-artifacts/{}?job_id={}&attempt_id={}&offset={offset}&length={length}",
artifact.artifact_id, job.job_id, job.attempt_id
);
let mut response = client.get(&url).send().await?;
let partial = offset != 0 || length != artifact.bytes;
ensure!(
response.url().as_str() == url
&& response.status()
== if partial {
reqwest::StatusCode::PARTIAL_CONTENT
} else {
reqwest::StatusCode::OK
},
"UPDATE_PREFETCH_HTTP"
);
let h = response.headers();
ensure!(
h.get("x-artifact-sha256").and_then(|v| v.to_str().ok())
== Some(artifact.sha256.as_str())
&& h.get("content-type").and_then(|v| v.to_str().ok())
== Some("application/octet-stream")
&& !h.contains_key("content-encoding")
&& response.content_length() == Some(length),
"UPDATE_PREFETCH_HEADERS"
);
if partial {
ensure!(
h.get("content-range").and_then(|v| v.to_str().ok())
== Some(
format!(
"bytes {}-{}/{}",
offset,
offset + length - 1,
artifact.bytes
)
.as_str()
),
"UPDATE_PREFETCH_RANGE"
);
} else {
ensure!(!h.contains_key("content-range"), "UPDATE_PREFETCH_RANGE");
}
let mut bytes = Vec::with_capacity(length as usize);
while let Some(chunk) = response.chunk().await? {
ensure!(
bytes.len() + chunk.len() <= length as usize,
"UPDATE_PREFETCH_BODY_LIMIT"
);
bytes.extend_from_slice(&chunk);
}
ensure!(
bytes.len() == length as usize && Instant::now() < deadline,
"UPDATE_PREFETCH_BODY_LENGTH"
);
hash.update(&bytes);
file = tokio::task::spawn_blocking(move || -> Result<File> {
file.write_all(&bytes)?;
Ok(file)
})
.await??;
offset += length;
}
ensure!(
format!("{:x}", hash.finalize()) == artifact.sha256,
"UPDATE_PREFETCH_DIGEST"
);
let dir = folder.clone();
tokio::task::spawn_blocking(move || -> Result<()> {
file.sync_all()?;
drop(file);
fs::hard_link(&stage, &path)?;
fs::remove_file(stage)?;
File::open(dir)?.sync_all()?;
checked(&path, &artifact)
})
.await??;
}
Ok(())
}
/// No Outcome is invented on acceptance; loss after write stays ambiguous.
pub fn handoff(binding: &Binding, request: &Request, grant: uuid::Uuid) -> Result<Accepted> {
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("UPDATE_FULL_SOCKET_REQUIRED")?;
let pin =
std::env::var_os("RMM_FULL_MAINTENANCE_POLICY_FILE").context("UPDATE_FULL_PIN_REQUIRED")?;
let pin = control::GeneralPin::read(Path::new(&pin), binding)?;
ensure!(
pin.profile == "full_maintenance_v1",
"UPDATE_FULL_PROFILE_REQUIRED"
);
control::general_probe(Path::new(&socket), binding, &pin)?;
let ack: Accepted =
control::exchange(Path::new(&socket), request, Duration::from_secs(50), 4096)?;
ack.matches(request, grant)?;
Ok(ack)
}
use rmm_domain::agent_update::Platform;
use rmm_privileged_helper::Binding;
use std::path::Path;
/// Opaque public metadata authenticated by the current protected Full peer,
/// with complete guarded history verified there. No caller JSON constructor.
@@ -336,57 +103,10 @@ impl Observer {
}
self.cached()
.cloned()
.unwrap_or_else(|| Observation::not_configured(Platform::LinuxX64, chrono::Utc::now()))
.unwrap_or_else(|| Observation::not_configured(Platform::NATIVE_LINUX, chrono::Utc::now()))
}
pub fn catalog_record(&self) -> Option<GuardedRecord> {
self.cached()?;
self.record.clone()
}
pub fn capabilities(&self) -> Vec<String> {
let Some(value) = self
.cached()
.filter(|v| v.quality == rmm_domain::agent_update::ObservationQuality::Valid)
else {
return vec![];
};
let (Some(updater), Some(predecessor)) = (&value.updater, &value.predecessor) else {
return vec![];
};
vec![
APPLY_CAPABILITY.into(),
CHECK_CAPABILITY.into(),
"update_agent".into(),
"root:update_agent".into(),
"helper.root.v1".into(),
format!("updater.binary.sha256:{}", updater.binary_sha256),
format!("updater.policy.sha256:{}", updater.policy_sha256),
format!("helper.binary.sha256:{}", predecessor.helper_sha256),
]
}
}
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
(|| -> Result<bool> {
ensure!(
unsafe { libc::geteuid() } == 993 && job.execution_identity == "root",
"UPDATE_AGENT_PRINCIPAL"
);
let Action::UpdateAgent { update } = &job.action else {
return Ok(false);
};
let observation = rmm_privileged_helper::update_admission::observe(
Path::new("/run/rmm-helper-maintenance/control.sock"),
binding,
Some(update.release_envelope.clone()),
Some(update.updater.keyring_generation),
)?;
Ok(observation.validate()
&& observation.quality == rmm_domain::agent_update::ObservationQuality::Valid
&& observation.predecessor.as_ref() == Some(&update.predecessor)
&& observation.updater.as_ref() == Some(&update.updater)
&& observation.candidate_previews.iter().any(|c| {
c.manifest_sha256 == update.manifest_sha256
&& c.peer_pin_transition == update.peer_pin_transition
}))
})()
.unwrap_or(false)
}
+9 -7
View File
@@ -15,7 +15,7 @@ use rmm_domain::{
};
use rmm_privileged_helper::{Binding, TrustedClock};
use rmm_updater::{
ActiveRelease, Platform as ReleasePlatform, ReleaseRelation, SignedRelease, TrustedContext,
ActiveRelease, ReleaseRelation, SignedRelease, TrustedContext,
TrustedUpdateKey, UpdateKeyring, verify_release,
};
use serde::Deserialize;
@@ -346,12 +346,12 @@ impl Trust {
.try_into()
.map_err(|_| anyhow::anyhow!("UPDATE_CATALOG_KEY_SIZE"))?;
ensure!(
key.platform == Platform::LinuxX64 && key.public_key_hex != binding.public_key_hex,
key.platform == Platform::NATIVE_LINUX && key.public_key_hex != binding.public_key_hex,
"UPDATE_CATALOG_KEY_SEPARATION"
);
trusted.push(TrustedUpdateKey::new(
public,
ReleasePlatform::LinuxX64,
Platform::NATIVE_LINUX.into(),
key.first_sequence,
key.last_sequence,
key.revoked,
@@ -426,7 +426,7 @@ impl Trust {
},
&self.keys,
&TrustedContext {
platform: ReleasePlatform::LinuxX64,
platform: Platform::NATIVE_LINUX.into(),
now_utc_seconds: now,
keyring_generation: self.generation,
protocol_major: self.protocol,
@@ -522,16 +522,18 @@ async fn request(
async fn fetch(client: &reqwest::Client, address: SocketAddr) -> Result<Vec<u8>> {
let response = client
.get(format!(
"https://{}:{}/agent/v1/releases/current?platform=x86_64-unknown-linux-gnu",
"https://{}:{}/agent/v1/releases/current?platform={}",
crate::https_channel::server_name()?,
address.port()
address.port(),
Platform::NATIVE_LINUX.target_triple()
))
.send()
.await?;
crate::https_channel::bounded_body(response, RESPONSE_LIMIT, "application/json").await
}
#[cfg(test)]
// These fixtures provision the legacy x86-64 manual updater profile.
#[cfg(all(test, target_arch = "x86_64"))]
mod tests {
use super::*;
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
+1 -1
View File
@@ -319,7 +319,7 @@ pub fn context(
let scope = match job.action {
rmm_domain::jobs::Action::UpdateAgent { ref update } => {
match update.manifest().map_err(anyhow::Error::msg)?.platform {
update::Platform::LinuxX64 => "linux.base",
update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
}
}
+4 -357
View File
@@ -1,118 +1,7 @@
//! Dedicated APT route: no fallback to generic helper, shell or SSH. Readiness
//! is nonce/root-peer/identity/profile/stack pinned before advertising or use.
use anyhow::{Context, Result, ensure};
use rmm_domain::jobs::JobPayload;
use rmm_privileged_helper::{Binding, Outcome, Request, apt as provider, readiness};
use std::{
ffi::OsString,
path::{Path, PathBuf},
};
pub fn socket_for(
job: &JobPayload,
general: Option<OsString>,
apt: Option<OsString>,
) -> Result<PathBuf> {
if job.action.full_maintenance() {
return Ok(PathBuf::from(
std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("FULL_MAINTENANCE_SOCKET_NOT_CONFIGURED")?,
));
}
select_socket(provider::is_apt_action(job), general, apt)
}
fn select_socket(
is_apt: bool,
general: Option<OsString>,
apt: Option<OsString>,
) -> Result<PathBuf> {
if is_apt {
let socket = PathBuf::from(apt.context("APT_HELPER_SOCKET_NOT_CONFIGURED")?);
ensure!(
socket == Path::new(readiness::SOCKET),
"APT_HELPER_SOCKET_PROFILE"
);
Ok(socket)
} else {
Ok(PathBuf::from(
general.context("GENERAL_HELPER_SOCKET_NOT_CONFIGURED")?,
))
}
}
fn status(binding: &Binding) -> Result<readiness::Response> {
let path =
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_HELPER_PIN_NOT_CONFIGURED")?;
let pin = readiness::Pin::read(Path::new(&path), binding)?;
let socket =
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_HELPER_SOCKET_NOT_CONFIGURED")?;
readiness::probe(Path::new(&socket), binding, &pin)
}
fn recovery_status(binding: &Binding) -> Result<readiness::Response> {
let path =
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_RECOVERY_PIN_REQUIRED")?;
let pin = readiness::Pin::read(Path::new(&path), binding)?;
let socket =
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_RECOVERY_SOCKET_REQUIRED")?;
readiness::planning_for_recovery(Path::new(&socket), binding, &pin)
}
pub fn capabilities_from(response: &readiness::Response) -> Vec<String> {
if response.profile != "apt_only" {
return vec![];
}
let mut result = vec![];
if response.fixture_acceptance_ready && !response.bootstrap_recipes.is_empty() {
result.push("apt_native_acceptance".into());
}
if !response.accepted_recipes.is_empty() {
result.push("ensure_package".into());
}
if response
.accepted_recipes
.iter()
.any(|r| r == provider::UPDATE_RECIPE)
{
result.push("apply_updates".into());
}
result
}
pub fn capabilities(binding: &Binding) -> Vec<String> {
let normal = status(binding)
.map(|s| {
let mut caps = capabilities_from(&s);
if !caps.is_empty() {
let roots: Vec<String> = caps.iter().map(|c| format!("root:{c}")).collect();
caps.extend(roots);
caps.extend([
"helper.root.v1".into(),
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
"apt.manifest.v2".into(),
]);
if s.fixture_acceptance_ready && !s.bootstrap_recipes.is_empty() {
caps.push("apt.native-acceptance.v1".into());
}
if !s.accepted_recipes.is_empty() {
caps.push("apt.native-accepted.v1".into());
}
}
caps
})
.unwrap_or_default();
if !normal.is_empty() {
return normal;
}
recovery_status(binding)
.map(|s| {
vec![
"apt_native_acceptance".into(),
"root:apt_native_acceptance".into(),
"helper.root.v1".into(),
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
"apt.manifest.v2".into(),
"apt.native-acceptance.v1".into(),
]
})
.unwrap_or_default()
}
//! Passive APT observations for installations with a configured planning source.
use anyhow::{Context, Result};
use rmm_privileged_helper::{Binding, readiness};
use std::path::Path;
/// Called only by the periodic blocking inventory worker, never heartbeat or a
/// caller-selected live query. Failure retains honest unknown/not_configured.
@@ -142,103 +31,6 @@ pub fn planning_observation(binding: Option<&Binding>) -> serde_json::Value {
}
}
}
fn recipe_ready(job: &JobPayload, response: &readiness::Response) -> Result<()> {
ensure!(
job.execution_identity == "root" && provider::is_apt_action(job),
"APT_TYPED_ROOT_ACTION_REQUIRED"
);
let action = serde_json::to_value(&job.action)?;
let manifest: provider::AptExecutionManifest = serde_json::from_value(
action
.get("apt_manifest")
.context("APT_MANIFEST_NOT_CONFIGURED")?
.clone(),
)?;
manifest.resolved_apt_transaction.validate_fixture()?;
let recipe = &manifest.resolved_apt_transaction.recipe_id;
if let Some(reference) = &manifest.native_recovery {
let planning = response
.planning
.as_ref()
.context("APT_RECOVERY_PLANNING_REQUIRED")?;
planning.validate(chrono::Utc::now())?;
ensure!(
job.action.name() == "apt_native_acceptance"
&& manifest.schema_version == 4
&& manifest.action == "apt-native-acceptance"
&& planning.native_recovery.as_ref() == Some(reference)
&& planning.baseline_sha256 == manifest.resolved_apt_transaction.baseline_sha256
&& planning.status_fingerprint
== manifest.resolved_apt_transaction.status_fingerprint
&& planning.runtime_sha256 == manifest.runtime_sha256
&& planning.provider_sha256 == manifest.provider_sha256
&& planning.hook_sha256 == manifest.hook_sha256
&& planning.apt_config_sha256 == manifest.apt_config_sha256,
"APT_RECOVERY_FRESH_PLAN_BINDING"
);
return Ok(());
}
if job.action.name() == "apt_native_acceptance" {
ensure!(
manifest.action == "apt-native-acceptance"
&& response.fixture_acceptance_ready
&& response.bootstrap_recipes.contains(recipe),
"APT_FIXTURE_READINESS_REQUIRED"
);
} else {
ensure!(
manifest.action == "apt-execute" && response.accepted_recipes.contains(recipe),
"APT_NATIVE_ACCEPTANCE_REQUIRED"
);
ensure!(
job.action.name() != "apply_updates" || recipe == provider::UPDATE_RECIPE,
"APT_UPDATE_RECIPE_SCOPE"
);
}
Ok(())
}
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
job_status(binding, job)
.and_then(|s| recipe_ready(job, &s))
.is_ok()
}
fn job_status(binding: &Binding, job: &JobPayload) -> Result<readiness::Response> {
if matches!(&job.action,rmm_domain::jobs::Action::AptNativeAcceptance{apt_manifest,..}if apt_manifest.native_recovery.is_some())
{
recovery_status(binding)
} else {
status(binding)
}
}
pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result<Outcome> {
let socket = socket_for(
job,
std::env::var_os("RMM_HELPER_SOCKET"),
std::env::var_os("RMM_APT_HELPER_SOCKET"),
)?;
if provider::is_apt_action(job) {
recipe_ready(job, &job_status(binding, job)?)?;
}
rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds)
}
pub fn invoke_with_control(
binding: &Binding,
job: &JobPayload,
request: &Request,
observe: impl FnMut() -> Result<()>,
) -> Result<Outcome> {
if !job.action.full_maintenance() {
return invoke(binding, job, request);
}
ensure!(
crate::helper_sync::general_supported(binding, job),
"FULL_MAINTENANCE_POLICY_REQUIRED"
);
let socket = socket_for(job, None, None)?;
rmm_privileged_helper::invoke_controlled(&socket, request, job.max_runtime_seconds, observe)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -251,149 +43,4 @@ mod tests {
assert!(observation["data"].is_null());
assert!(observation.get("received_at").is_none());
}
#[test]
fn typed_actions_require_their_own_fixture_readiness_or_accepted_recipe() {
let id = uuid::Uuid::new_v4();
let now = chrono::Utc::now();
let tx = serde_json::json!({"schema_version":1,"recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","platform":"ubuntu-24.04-amd64",
"resolver_config_version":"rmm-apt-local-v1","no_reboot":true,"status_fingerprint":"a".repeat(64),"baseline_sha256":"b".repeat(64),
"packages":[{"name":"rmm-mvp-test","architecture":"all","old_version":null,"new_version":"1.0","origin":"rmm-test",
"sha256":rmm_domain::apt_transaction::INSTALL_SHA,"size":20672,
"archive_path":format!("/var/lib/rmm-apt-transaction/archives/{}.deb",rmm_domain::apt_transaction::INSTALL_SHA)}]});
let bytes = serde_json::to_vec(&tx).unwrap();
let manifest = serde_json::json!({"type":"rmm.apt.helper-action","schema_version":2,"action":"apt-native-acceptance","execution_profile":"dev-test",
"transaction_sha256":rmm_domain::jobs::hash(&bytes),"resolved_apt_transaction":tx,"transaction_bytes":bytes,
"provider_sha256":"a".repeat(64),"hook_sha256":"a".repeat(64),"apt_config_sha256":"a".repeat(64),"runtime_sha256":"a".repeat(64),"test_result_id":"fixture-test"});
let mut job:JobPayload=serde_json::from_value(serde_json::json!({"schema_version":1,"tenant_id":id,"asset_id":id,"agent_id":id,
"enrollment_generation":1,"assignment_version":1,"job_id":id,"attempt_id":id,"execution_identity":"root",
"not_before":now,"start_before":now+chrono::Duration::minutes(1),"max_runtime_seconds":300,"max_output_bytes":4096,
"action":{"action":"apt_native_acceptance","recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","apt_manifest":manifest}})).unwrap();
assert!(job.action.validate());
let identity = readiness::Identity {
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
signing_key_id: "a".repeat(64),
};
let mut response = readiness::Response {
schema_version: 1,
challenge: id,
identity,
profile: "apt_only".into(),
provider_stack_sha256: "a".repeat(64),
fixture_acceptance_ready: true,
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
accepted_recipes: vec![],
ledger_device: 1,
ledger_inode: 2,
lock_device: 1,
lock_inode: 3,
planning: None,
};
recipe_ready(&job, &response).unwrap();
let mut normal = manifest;
normal["action"] = serde_json::json!("apt-execute");
job.action=serde_json::from_value(serde_json::json!({"action":"ensure_package","provider":"apt","package":"rmm-mvp-test","version":"1.0",
"architecture":"all","recipe_version":"1","installation_context":"system","recipe_id":provider::INSTALL_RECIPE,"apt_manifest":normal})).unwrap();
assert!(job.action.validate());
assert!(recipe_ready(&job, &response).is_err());
response.accepted_recipes = vec![provider::UPDATE_RECIPE.into()];
assert!(recipe_ready(&job, &response).is_err());
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
recipe_ready(&job, &response).unwrap();
}
#[test]
fn apt_route_cannot_fall_back_to_general_or_a_caller_path() {
assert!(select_socket(true, Some("/run/general.sock".into()), None).is_err());
assert!(
select_socket(
true,
Some("/run/general.sock".into()),
Some("/tmp/fake.sock".into())
)
.is_err()
);
assert_eq!(
select_socket(
true,
Some("/run/general.sock".into()),
Some(readiness::SOCKET.into())
)
.unwrap(),
Path::new(readiness::SOCKET)
);
}
#[test]
fn bootstrap_readiness_never_claims_package_acceptance() {
let id = readiness::Identity {
tenant_id: uuid::Uuid::new_v4(),
asset_id: uuid::Uuid::new_v4(),
agent_id: uuid::Uuid::new_v4(),
enrollment_generation: 1,
assignment_version: 1,
signing_key_id: "a".repeat(64),
};
let mut response = readiness::Response {
schema_version: 1,
challenge: uuid::Uuid::new_v4(),
identity: id,
profile: "apt_only".into(),
provider_stack_sha256: "a".repeat(64),
fixture_acceptance_ready: true,
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
accepted_recipes: vec![],
ledger_device: 1,
ledger_inode: 2,
lock_device: 1,
lock_inode: 3,
planning: None,
};
assert_eq!(capabilities_from(&response), vec!["apt_native_acceptance"]);
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
assert!(!capabilities_from(&response).contains(&"apply_updates".into()));
response
.accepted_recipes
.push(provider::UPDATE_RECIPE.into());
assert!(capabilities_from(&response).contains(&"apply_updates".into()));
}
#[test]
fn generic_script_never_uses_apt_socket() {
let now = chrono::Utc::now();
let id = uuid::Uuid::new_v4();
let job = JobPayload {
schema_version: 1,
tenant_id: id,
asset_id: id,
agent_id: id,
enrollment_generation: 1,
assignment_version: 1,
job_id: id,
attempt_id: id,
action: rmm_domain::jobs::Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "root".into(),
not_before: now,
start_before: now + chrono::Duration::minutes(1),
max_runtime_seconds: 300,
max_output_bytes: 4096,
};
assert!(socket_for(&job, None, Some(readiness::SOCKET.into())).is_err());
assert_eq!(
socket_for(
&job,
Some("/run/general.sock".into()),
Some(readiness::SOCKET.into())
)
.unwrap(),
Path::new("/run/general.sock")
);
}
}
+61 -90
View File
@@ -41,16 +41,12 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot {
.collect(),
}
}
fn general(binding: &Binding, full: bool) -> Result<control::Response> {
let (socket_name, pin_name, profile) = if full {
(
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
"RMM_FULL_MAINTENANCE_POLICY_FILE",
"full_maintenance_v1",
)
} else {
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general")
};
fn script_helper(binding: &Binding) -> Result<control::Response> {
let (socket_name, pin_name, profile) = (
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
"RMM_FULL_MAINTENANCE_POLICY_FILE",
"full_maintenance_v1",
);
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
@@ -207,97 +203,72 @@ impl Helpers {
Ok(applied.as_ref().map(map))
}
}
pub fn general_capabilities(binding: &Binding) -> Vec<String> {
let mut caps = profile_capabilities(binding, false);
caps.extend(profile_capabilities(binding, true));
caps.sort();
caps.dedup();
caps
}
fn profile_capabilities(binding: &Binding, full: bool) -> Vec<String> {
pub fn script_capabilities(binding: &Binding) -> Vec<String> {
(|| -> Result<Vec<String>> {
let response = general(binding, full)?;
let policy = response.policy.context("NO_GENERAL_POLICY")?;
let response = script_helper(binding)?;
let binary = response
.helper_binary_sha256
.context("SCRIPT_HELPER_BINARY_PROOF_REQUIRED")?;
ensure!(
rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"SCRIPT_INTERPRETER_UNAVAILABLE"
);
let mut caps = vec![
"run_script".into(),
"root:run_script".into(),
"helper.root.v1".into(),
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.policy.sha256:{}", response.policy_sha256),
format!("helper.binary.sha256:{binary}"),
];
if full {
ensure!(
policy.schema_version == 2
&& policy.profile == "full_maintenance_v1"
&& policy.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]),
"FULL_MAINTENANCE_POLICY_REQUIRED"
);
let binary = policy
.helper_binary_sha256
.as_ref()
.context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?;
ensure!(
response.helper_binary_sha256.as_ref() == Some(binary),
"FULL_MAINTENANCE_BINARY_PROOF_REQUIRED"
);
caps.push(format!("helper.binary.sha256:{binary}"));
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
}
let mut actions = vec![];
if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() {
actions.push("run_script");
}
if !policy.allowed_services.is_empty() {
actions.extend(["set_service_state", "query_logs"]);
}
if policy.allow_reboot {
actions.push("reboot");
}
for action in actions {
caps.push(action.into());
caps.push(format!("root:{action}"));
if let Some(release) = std::env::var("RMM_SCRIPT_HELPER_RELEASE")
.ok()
.and_then(|value| Uuid::parse_str(&value).ok())
.filter(|id| !id.is_nil())
{
caps.push(format!("script.helper.release:{release}"));
}
Ok(caps)
})()
.unwrap_or_default()
}
pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
(|| -> Result<bool> {
let p = general(binding, job.action.full_maintenance())?
.policy
.context("NO_GENERAL_POLICY")?;
Ok(match &job.action {
rmm_domain::jobs::Action::RunScript { interpreter, .. } => {
p.allow_root_scripts
&& job.action.valid_execution_identity(&job.execution_identity)
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& (!job.action.full_maintenance()
|| p.allowed_script_profiles.as_ref().is_some_and(|v| {
v.contains(
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
)
}))
&& match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
}
}
rmm_domain::jobs::Action::SetServiceState { unit, state } => {
p.allowed_services.contains(unit)
&& matches!(state.as_str(), "running" | "stopped")
&& job.max_runtime_seconds >= 180
}
rmm_domain::jobs::Action::QueryLogs { unit, .. } => {
p.allowed_services.contains(unit) && job.max_runtime_seconds >= 20
}
rmm_domain::jobs::Action::Reboot { .. } => {
p.allow_reboot && job.max_runtime_seconds >= 60
}
pub fn script_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
let rmm_domain::jobs::Action::RunScript { interpreter, .. } = &job.action else {
return false;
};
job.execution_identity == "root"
&& job.action.full_maintenance()
&& job.action.valid_execution_identity(&job.execution_identity)
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
})
})()
.unwrap_or(false)
}
&& script_helper(binding).is_ok()
}
pub fn invoke_script(
binding: &Binding,
job: &rmm_domain::jobs::JobPayload,
request: &rmm_privileged_helper::Request,
observe: impl FnMut() -> Result<()>,
) -> Result<rmm_privileged_helper::Outcome> {
ensure!(
script_supported(binding, job),
"SCRIPT_HELPER_POLICY_REQUIRED"
);
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
.context("SCRIPT_HELPER_SOCKET_REQUIRED")?;
rmm_privileged_helper::invoke_controlled(
Path::new(&socket),
request,
job.max_runtime_seconds,
observe,
)
}
impl Helpers {
+45 -225
View File
@@ -1,183 +1,46 @@
use anyhow::{Result, ensure};
use anyhow::Result;
#[cfg(test)]
use prost::Message;
#[cfg(test)]
use rmm_domain::jobs::hash;
use rmm_domain::jobs::{Action, JobPayload};
use rmm_privileged_helper::{Binding, Outcome};
use rmm_privileged_helper::Binding;
use rmm_protocol::*;
use rusqlite::Connection;
#[cfg(test)]
use uuid::Uuid;
pub fn supported(job: &JobPayload) -> bool {
if rmm_privileged_helper::apt::is_apt_action(job) {
// A configured environment path alone is never a capability proof.
// Caller binding is independently provisioned, not taken from the job.
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
let Action::RunScript { interpreter, .. } = &job.action else {
return false;
};
if unsafe { libc::geteuid() } == 0
|| !job.action.valid_execution_identity(&job.execution_identity)
{
return false;
}
// The network process must never execute a script with accidental root.
supported_as(
job,
unsafe { libc::geteuid() },
std::env::var_os("RMM_HELPER_SOCKET").is_some(),
)
}
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
if matches!(job.action, Action::UpdateAgent { .. }) {
return binding.is_some_and(|b| crate::agent_update_apply::supported(b, job));
}
if rmm_privileged_helper::apt::is_apt_action(job) {
// SAFETY: geteuid has no preconditions.
return unsafe { libc::geteuid() } != 0
&& binding.is_some_and(|b| crate::apt::supported(b, job));
}
if job.execution_identity == "root" {
return unsafe { libc::geteuid() } != 0
&& binding.is_some_and(|b| crate::helper_sync::general_supported(b, job));
}
supported(job)
}
fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
let unprivileged = uid != 0;
if job.execution_identity == "root" && unprivileged {
return helper_configured
&& matches!(
job.action,
Action::RunScript { .. } | Action::SetServiceState { .. } | Action::Reboot { .. }
);
}
job.execution_identity == "agent_service"
&& unprivileged
&& match &job.action {
Action::RunScript { interpreter, .. } => match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
},
Action::RefreshInventory { scope } => scope == "linux.base",
Action::QueryLogs { .. } => log_request(job).is_ok(),
_ => false,
match job.execution_identity.as_str() {
"root" => {
job.action.full_maintenance()
&& binding.is_some_and(|b| crate::helper_sync::script_supported(b, job))
}
"agent_service" => match interpreter.as_str() {
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
_ => false,
},
_ => false,
}
}
pub use rmm_agent_core::jobs::{
denied_request, ack, event, events, interrupted, interrupted_request, next, no_start, permit_request,
recover_interrupted_outcome, requesting, reserve_request, result, transition,
ack, denied_request, event, events, interrupted, interrupted_request, next, no_start,
permit_request, recover_interrupted_outcome, requesting, reserve_request, result, transition,
};
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
supported_with_binding(job, Some(binding))
})
}
pub fn execute(job: &JobPayload) -> Outcome {
let result = match &job.action {
Action::RunScript { .. } => rmm_privileged_helper::script(job),
Action::RefreshInventory { .. } => rmm_agent_linux::collect().and_then(|i| {
let bytes = serde_json::to_vec(&i)?;
ensure!(bytes.len() <= job.max_output_bytes as usize, "INVENTORY_OUTPUT_LIMIT");
Ok(Outcome { state: "succeeded".into(), stdout: bytes, stderr: vec![], exit_code: None,
output_truncated: false, reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"linux.base","observed_at":chrono::Utc::now(),"completeness":"partial"}), error_code: String::new() })
}),
Action::QueryLogs { .. } => query_logs(job),
_ => Err(anyhow::anyhow!("unsupported action")),
};
result.unwrap_or_else(|_| Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
}
fn allowed_log_units() -> Result<Vec<rmm_agent_linux::actions::ServiceUnit>> {
let path = std::env::var_os("RMM_LOG_UNITS_FILE")
.ok_or_else(|| anyhow::anyhow!("LOG_ALLOWLIST_NOT_CONFIGURED"))?;
let path = std::path::Path::new(&path);
rmm_privileged_helper::private_path(path, unsafe { libc::geteuid() }, false)?;
ensure!(
std::fs::metadata(path)?.len() <= 32768,
"LOG_ALLOWLIST_SIZE"
);
let units: Vec<String> = serde_json::from_slice(&std::fs::read(path)?)?;
ensure!(
!units.is_empty() && units.len() <= 128,
"LOG_ALLOWLIST_SIZE"
);
units
.iter()
.map(|u| rmm_agent_linux::actions::ServiceUnit::new(u))
.collect()
}
pub fn logs_available() -> bool {
allowed_log_units().is_ok()
&& rmm_agent_linux::inventory::capabilities()
.get("logs.journald")
.is_some_and(|o| o.data == Some(true))
}
fn log_request(job: &JobPayload) -> Result<rmm_agent_linux::inventory::JournalRequest> {
log_request_for(job, &allowed_log_units()?)
}
fn log_request_for(
job: &JobPayload,
allowed: &[rmm_agent_linux::actions::ServiceUnit],
) -> Result<rmm_agent_linux::inventory::JournalRequest> {
let Action::QueryLogs {
unit,
since,
until,
max_lines,
} = &job.action
else {
anyhow::bail!("NOT_LOG_QUERY")
};
ensure!(job.max_runtime_seconds >= 20, "LOG_RUNTIME_TOO_SHORT");
rmm_agent_linux::inventory::JournalRequest::new(
rmm_agent_linux::actions::ServiceUnit::new(unit)?,
allowed,
u64::try_from(since.timestamp())?,
u64::try_from(until.timestamp())?,
*max_lines as usize,
(job.max_output_bytes as usize).min(256 * 1024),
)?
.precise_window(*since, *until)
}
fn query_logs(job: &JobPayload) -> Result<Outcome> {
let observation = rmm_agent_linux::inventory::query_journal(&log_request(job)?);
let valid = observation.quality == rmm_agent_linux::inventory::Quality::Valid;
let error = observation.error_code.clone().unwrap_or_default();
let mut value = serde_json::to_value(&observation)?;
while serde_json::to_vec(&value)?.len() > job.max_output_bytes as usize {
let Some(lines) = value["data"]["json_lines"]
.as_array_mut()
.filter(|v| !v.is_empty())
else {
return Ok(Outcome {
state: "failed".into(),
..Outcome::unknown("LOG_RESULT_METADATA_EXCEEDS_OUTPUT_LIMIT")
});
};
lines.remove(0);
value["truncated"] = serde_json::json!(true);
value["completeness"] = serde_json::json!("partial");
value["error_code"] = serde_json::json!("LOG_SERIALIZED_OUTPUT_LIMIT");
}
Ok(Outcome {
state: if valid { "succeeded" } else { "failed" }.into(),
stdout: serde_json::to_vec(&value)?,
stderr: vec![],
exit_code: None,
output_truncated: value["truncated"] == true,
reboot_required: false,
evidence: serde_json::json!({"postconditions_passed":valid,"source_id":observation.source_id,
"observed_at":value["observed_at"],"quality":value["quality"],"completeness":value["completeness"],
"cursor_status":"not_advanced_no_ack_contract","provider_error_code":error}),
error_code: if valid {
String::new()
} else if error.is_empty() {
"LOG_PROVIDER_UNAVAILABLE".into()
} else {
error
},
})
}
/// With no backend SyncResponse contract, a reconnect/restart cannot prove an
/// earlier reservation never started. Telemetry and evidence replay continue;
/// all new effects stop. Do not paper over this with a new start request.
#[cfg(test)]
pub fn begin_session(db: &Connection) -> Result<bool> {
@@ -228,8 +91,13 @@ mod tests {
assignment_version: 2,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::RefreshInventory {
scope: "linux.base".into(),
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: "true".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
not_before: now,
@@ -254,7 +122,7 @@ mod tests {
let mut db = storage::open(&path).unwrap();
let job = binding.job(&offer.payload_bytes).unwrap();
if unsafe { libc::geteuid() } == 0 {
assert!(!supported(&job));
assert!(!supported_with_binding(&job, Some(&binding)));
assert!(accept(&db, &binding, &offer).is_err());
} else {
assert!(accept(&db, &binding, &offer).unwrap());
@@ -326,20 +194,24 @@ mod tests {
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn network_process_never_executes_as_accidental_root() {
fn legacy_actions_and_unbound_root_are_rejected_before_any_reservation() {
let (path, binding, offer) = fixture();
let mut job = binding.job(&offer.payload_bytes).unwrap();
assert!(!supported_as(&job, 0, false));
assert!(!supported_as(&job, 0, true));
job.execution_identity = "root".into();
assert!(!supported_as(&job, 1000, false));
assert!(!supported_as(&job, 0, true));
job.action = Action::Reboot {
reason: "explicit root only".into(),
reconnect_timeout_seconds: 60,
dependency_group: "test".into(),
};
assert!(supported_as(&job, 1000, true));
assert!(!supported_with_binding(&job, Some(&binding)));
for identity in ["agent_service", "root"] {
job.execution_identity = identity.into();
job.action = Action::Reboot {
reason: "legacy fixture".into(),
reconnect_timeout_seconds: 60,
dependency_group: "test".into(),
};
assert!(!supported_with_binding(&job, Some(&binding)));
job.action = Action::RefreshInventory {
scope: "linux.base".into(),
};
assert!(!supported_with_binding(&job, Some(&binding)));
}
std::fs::remove_dir_all(path).unwrap();
}
#[test]
@@ -363,56 +235,4 @@ mod tests {
drop(db);
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn live_logs_enforce_actual_action_window_allowlist_limits_and_runtime() {
let (path, binding, offer) = fixture();
let mut job = binding.job(&offer.payload_bytes).unwrap();
let unit = rmm_agent_linux::actions::ServiceUnit::new("rmm-test.service").unwrap();
let now = chrono::Utc::now();
job.max_runtime_seconds = 20;
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::minutes(1),
until: now,
max_lines: 10,
};
assert!(log_request_for(&job, &[]).is_err());
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_ok());
job.max_runtime_seconds = 10;
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
job.max_runtime_seconds = 20;
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::hours(25),
until: now,
max_lines: 10,
};
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
job.action = Action::QueryLogs {
unit: unit.as_str().into(),
since: now - chrono::Duration::minutes(1),
until: now,
max_lines: 1001,
};
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn refresh_is_a_new_measurement_with_real_observation_time() {
let (path, binding, offer) = fixture();
let job = binding.job(&offer.payload_bytes).unwrap();
let before = chrono::Utc::now();
let outcome = execute(&job);
assert_eq!(outcome.state, "succeeded");
let observed =
chrono::DateTime::parse_from_rfc3339(outcome.evidence["observed_at"].as_str().unwrap())
.unwrap();
assert!(observed >= before);
assert!(
serde_json::from_slice::<rmm_domain::Inventory>(&outcome.stdout)
.unwrap()
.validate()
);
std::fs::remove_dir_all(path).unwrap();
}
}
+120 -49
View File
@@ -64,6 +64,8 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
rotation_policy: certificate_rotation::RotationPolicy,
catalog: agent_update_catalog::Checker,
update_observer: agent_update_apply::Observer,
transfer_state: Option<PathBuf>,
transfer_gate: Option<fs::File>,
}
#[derive(Default)]
struct EffectFence {
@@ -425,15 +427,8 @@ impl<C: reconcile::SyncClock> Agent<C> {
|| binding.verify(&request, Utc::now()).is_err()
{
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
} else if matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) {
match agent_update_apply::handoff(&binding, &request, grant.grant_id) {
// Full now owns this original. The stable updater may
// stop us. Reconciliation alone supplies its final result.
Ok(_) => return,
Err(_) => rmm_privileged_helper::Outcome::unknown("UPDATE_HANDOFF_UNCONFIRMED"),
}
} else if job.execution_identity == "root" {
apt::invoke_with_control(&binding, &job, &request, || {
helper_sync::invoke_script(&binding, &job, &request, || {
ensure!(
!cancellation.load(Ordering::SeqCst)
&& fence.running_generation.load(Ordering::SeqCst) == generation
@@ -446,7 +441,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
})
} else {
jobs::execute(&job)
rmm_privileged_helper::script(&job).unwrap_or_else(|_| rmm_privileged_helper::Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
};
let _ = completed.blocking_send((offer, grant, outcome));
});
@@ -472,6 +467,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
"heartbeat/1".into(),
"agent.update/1".into(),
];
if self.transfer_state.is_some() {
capabilities.push(rmm_domain::customer_transfer::CAPABILITY.into());
}
#[cfg(target_arch = "aarch64")]
capabilities.push(rmm_domain::agent_update::LINUX_ARM64_RELEASE_CAPABILITY.into());
if self.binding.is_some() {
capabilities.push("rmm.sync.v1".into());
}
@@ -481,24 +481,43 @@ impl<C: reconcile::SyncClock> Agent<C> {
if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
capabilities.push("run_script".into());
}
capabilities.push("refresh_inventory".into());
if jobs::logs_available() {
capabilities.push("query_logs".into());
}
capabilities.extend(apt::capabilities(binding));
capabilities.extend(helper_sync::general_capabilities(binding));
if self.clock.trusted() {
capabilities.extend(self.update_observer.capabilities());
if self.helpers.is_some() {
capabilities.extend(helper_sync::script_capabilities(binding));
}
}
capabilities.sort();
capabilities.dedup();
capabilities
}
fn queue_inventory(&mut self) {
async fn stage_customer_transfer(&mut self) -> Result<bool> {
let (Some(dir), Some(binding)) = (&self.transfer_state, &self.binding) else {
return Ok(false);
};
if !self.running_cancels.is_empty() || self.prepared.is_some()
|| !rmm_agent_core::customer_transfer::idle(&self.db, &self.ledger)? {
return Ok(false);
}
let identity = self.certificates.current(Utc::now().timestamp())?;
let client = https_channel::mtls_client(
self.address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
)?;
let base = format!("https://{}:{}", https_channel::server_name()?, self.address.port());
let guard = fs::File::open(env::var_os("RMM_RELEASE_LOCK").context("RELEASE_LOCK_REQUIRED")?)?;
match fs2::FileExt::try_lock_shared(&guard) {
Ok(()) => (),
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => return Ok(false),
Err(error) => return Err(error.into()),
}
if rmm_agent_core::customer_transfer::stage(&client, &base, dir, binding, transfer_csr).await? {
self.transfer_gate = Some(guard);
return Ok(true);
}
Ok(false)
}
fn queue_inventory(&mut self) -> bool {
if self.inventory_inflight || !storage::passive_collection_ready(&self.db).unwrap_or(false)
{
return;
return false;
}
self.inventory_inflight = true;
let sender = self.inventory_tx.clone();
@@ -526,12 +545,12 @@ impl<C: reconcile::SyncClock> Agent<C> {
.push(agent_update_catalog::observation(report, Utc::now()));
inventory["collection_completed_at"] = serde_json::json!(Utc::now());
}
let bytes = serde_json::to_vec(&inventory)?;
ensure!(bytes.len() <= 512 * 1024, "INVENTORY_WIRE_LIMIT");
let bytes = rmm_agent_linux::wire::encode_snapshot(inventory)?;
Ok((bytes, Utc::now().timestamp_millis()))
});
let _ = sender.blocking_send(result);
});
true
}
fn queue_update_observation(&mut self, generation: u64) -> Result<()> {
if !storage::passive_collection_ready(&self.db)? {
@@ -662,6 +681,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
let mut inventory_at = Instant::now();
let mut update_at = Instant::now();
let mut heartbeat_at = Instant::now();
let mut previous_cpu = None;
let mut heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
let mut tick = tokio::time::interval(Duration::from_secs(5));
let mut sync_at = Instant::now();
@@ -670,8 +690,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
let mut first_heartbeat = true;
let mut health_task: Option<PendingUpdateHealth> = None;
let mut health_inventory_prefix: Option<String> = None;
let mut update_prefetch: Option<(JobOffer, agent_update_apply::Prefetch)> = None;
let mut prefetched = std::collections::HashSet::new();
loop {
tokio::select! {
Some(result) = self.inventory_rx.recv() => {
@@ -748,7 +766,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
// First preserve the original completion without unlocking.
// A startup can replay it if the journal transaction is lost.
let state = outcome.state.clone();
let refresh_capabilities=state=="succeeded" && serde_json::from_slice::<rmm_domain::jobs::JobPayload>(&offer.payload_bytes)?.action.name()=="apt_native_acceptance";
rmm_privileged_helper::persist_outcome(&self.ledger,&grant,&outcome)?;
let serialized = serde_json::to_vec(&outcome)?;
self.record(generation, &offer, &grant.grant_id.to_string(), outcome)?;
@@ -756,17 +773,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
rmm_privileged_helper::finish(&self.ledger, &grant, &outcome)?;
if state == "unknown" { eprintln!("job effect unknown: device execution lock retained"); }
needs_sync=true;self.replay(&ws, generation).await?;
if refresh_capabilities {return Ok(());}
}
_ = tick.tick() => {
self.replay(&ws, generation).await?;
if update_prefetch.as_ref().is_some_and(|(_,task)|task.0.is_finished()) {
let (offer, mut task)=update_prefetch.take().context("UPDATE_PREFETCH_REQUIRED")?;
match (&mut task.0).await {
Ok(Ok(())) => {prefetched.insert((offer.job_id.clone(),offer.attempt_id.clone()));},
_ => {self.record(generation,&offer,"",jobs::no_start("failed","UPDATE_ARTIFACT_PREFETCH_FAILED"))?;needs_sync=true;}
}
}
let busy:bool=self.db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get(0))?;
let update=self.update_proof()?;
let pending_update=self.binding.as_ref().map(|binding|rmm_agent_core::jobs::needs_update_control(&self.db,&self.ledger,binding)).transpose()?.unwrap_or(false);
@@ -775,10 +784,10 @@ impl<C: reconcile::SyncClock> Agent<C> {
let decoded=proof.decode().map_err(anyhow::Error::msg)?;
let event:Option<rmm_updater_handoff::Event>=decoded.events.last().map(|raw|serde_json::from_slice(raw)).transpose()?;
if event.is_some_and(|event|matches!(event.evidence,rmm_updater_handoff::Evidence::ServicesStarted{..}|rmm_updater_handoff::Evidence::RollbackServicesStarted{..})) {
if health_inventory_prefix.as_deref()!=Some(proof.head_sha256.as_str()) {
if health_inventory_prefix.as_deref()!=Some(proof.head_sha256.as_str()) && self.queue_inventory() {
// Fixed update health includes one genuinely new
// normal base sample, never a fresh timestamp on old data.
self.queue_inventory();health_inventory_prefix=Some(proof.head_sha256.clone());
health_inventory_prefix=Some(proof.head_sha256.clone());
}
if health_task.is_none() && self.prepared.is_none() {
match self.start_update_health(proof) {Ok(task)=>health_task=task,Err(error)=>{report_closed_gate(&error);self.close_gate();needs_sync=true;}}
@@ -802,18 +811,12 @@ impl<C: reconcile::SyncClock> Agent<C> {
let job = self.binding.as_ref().context("binding")?.job(&offer.payload_bytes)?;
if Utc::now() >= job.start_before {
self.record(generation, &offer, "", jobs::no_start("expired", "START_DEADLINE_EXPIRED"))?;
} else if !matches!(job.action,rmm_domain::jobs::Action::RunScript{..})
|| (job.execution_identity=="root" && !job.action.full_maintenance()) {
self.record(generation, &offer, "", jobs::no_start("failed","LEGACY_ACTION_RETIRED"))?;
} else if !self.ready(generation,job.execution_identity=="root") {
needs_sync=true;
} else if Utc::now() >= job.not_before {
if matches!(job.action,rmm_domain::jobs::Action::UpdateAgent{..}) && !prefetched.contains(&(offer.job_id.clone(),offer.attempt_id.clone())) {
if update_prefetch.is_none() {
let identity=self.certificates.current(Utc::now().timestamp())?;
let client=https_channel::mtls_client(self.address,&self.ca,&identity.certificate_pem,&identity.private_key_pem)?;
let base=format!("https://{}:{}",https_channel::server_name()?,self.address.port());
update_prefetch=Some((offer.clone(),agent_update_apply::Prefetch(tokio::spawn(agent_update_apply::prefetch(client,base,job)))));
}
continue;
}
// Reserve before send. A lost response must never cause
// a second permit request for this attempt.
// The root updater holds this lock exclusively while it checks
@@ -839,11 +842,21 @@ impl<C: reconcile::SyncClock> Agent<C> {
}
if first_heartbeat || heartbeat_at.elapsed() >= heartbeat_after {
first_heartbeat = false;
let cpu = rmm_agent_linux::inventory::cpu_times();
let cpu_usage_basis_points = cpu.zip(previous_cpu)
.and_then(|(current, previous)| current.usage_since(previous));
previous_cpu = cpu;
let memory = rmm_agent_linux::inventory::memory().data;
let heartbeat = self.envelope(
generation,
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: Some(SystemUsage {
cpu_usage_basis_points,
ram_available_bytes: memory.as_ref().and_then(|m| m.available_bytes),
ram_total_bytes: memory.map(|m| m.total_bytes),
}),
}),
)?;
ws.send(&heartbeat).await?;
@@ -853,6 +866,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
Payload::Heartbeat(Heartbeat {
instance_id: self.instance.clone(),
uptime_seconds: self.started.elapsed().as_secs(),
system_usage: None,
}),
)?;
ws.poll(poll).await?;
@@ -860,12 +874,18 @@ impl<C: reconcile::SyncClock> Agent<C> {
heartbeat_at = Instant::now();
heartbeat_after = Duration::from_millis(rand::random_range(27_000..33_000));
}
if inventory_at.elapsed() >= Duration::from_secs(60) {
self.queue_inventory();
// A simultaneous update report can fill the durable queue. Keep
// inventory due until collection actually starts.
if inventory_at.elapsed() >= Duration::from_secs(60) && self.queue_inventory() {
inventory_at = Instant::now();
}
if rotation_at.elapsed() >= Duration::from_secs(30) {
rotation_at = Instant::now();
match self.stage_customer_transfer().await {
Ok(true) => return Ok(()),
Ok(false) => (),
Err(_) => eprintln!("customer transfer waiting for a valid handoff"),
}
if self
.certificates
.due(self.rotation_policy, Utc::now().timestamp())?
@@ -890,6 +910,27 @@ impl<C: reconcile::SyncClock> Agent<C> {
}
}
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
let key = match previous {
Some(raw) => PKey::private_key_from_pem(raw)?,
None => {
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
PKey::from_ec_key(EcKey::generate(&group)?)?
}
};
let mut csr = X509Req::builder()?;
let mut name = X509NameBuilder::new()?;
name.append_entry_by_text("CN", "customer-transfer")?;
csr.set_subject_name(&name.build())?;
csr.set_pubkey(&key)?;
csr.sign(&key, MessageDigest::sha256())?;
Ok((key.private_key_to_pem_pkcs8()?, String::from_utf8(csr.build().to_pem()?)?))
}
fn customer_transfer_signer(dir: &Path) -> Result<rmm_privileged_helper::SigningKey> {
rmm_privileged_helper::SigningKey::read(&dir.join("job-signing-key.json"), unsafe { libc::geteuid() })
}
async fn enrollment(dir: &Path, address: std::net::SocketAddr, ca: &[u8]) -> Result<String> {
let identity = dir.join("identity.json");
if identity.exists() {
@@ -967,6 +1008,18 @@ async fn main() -> Result<()> {
PathBuf::from(env::var("RMM_AGENT_STATE").unwrap_or_else(|_| "devstate/agent".into()));
storage::prepare_dir(&dir)?;
let _lock = storage::lock(&dir)?;
let mut release_guard = None;
loop {
if rmm_agent_core::customer_transfer::pending(&dir)? {
let signer = customer_transfer_signer(&dir)?;
rmm_agent_core::customer_transfer::activate(&dir, &signer.public_key_hex)?;
}
drop(release_guard.take());
release_guard = Some(run_agent(&dir).await?);
}
}
async fn run_agent(dir: &Path) -> Result<fs::File> {
let address = env::var("RMM_CONNECT_ADDR")
.unwrap_or_else(|_| "127.0.0.1:18443".into())
.parse()?;
@@ -995,6 +1048,20 @@ async fn main() -> Result<()> {
enrollment_generation: 1, assignment_version: 1, public_key_hex: String::new(),
});
}
let transfer_state = (env::var_os("RMM_JOB_BINDING_FILE").is_none()
&& env::var_os("RMM_ENROLLMENT_TENANT").is_some()
&& env::var("RMM_JOB_SIGNING_KEY_BOOTSTRAP").as_deref() == Ok("1")
&& env::var_os("RMM_RELEASE_LOCK").is_some()).then(|| dir.to_owned());
let mut moved = false;
if transfer_state.is_some() && let Some(binding) = binding.as_mut()
&& dir.join("job-signing-key.json").try_exists()? {
let identity: EnrollmentResponse = serde_json::from_slice(&fs::read(dir.join("identity.json"))?)?;
let signer = customer_transfer_signer(dir)?;
if let Some(tenant) = rmm_agent_core::customer_transfer::assigned_tenant(dir, &identity, &signer.public_key_hex)? {
binding.tenant_id = tenant;
moved = true;
}
}
let certificate_dir = dir.join("certificates");
let certificates = certificate_rotation::RotationStore::open(
&certificate_dir,
@@ -1026,10 +1093,9 @@ async fn main() -> Result<()> {
let sync = binding
.as_ref()
.map(|b| reconcile::ClientSync::new(b.clone()));
let helpers = binding
.as_ref()
.map(helper_sync::Helpers::configured)
.transpose()?;
let helpers = if moved { None } else {
binding.as_ref().map(helper_sync::Helpers::configured).transpose()?
};
let mut rotation_policy = certificate_rotation::RotationPolicy::default();
if let Ok(after) = env::var("RMM_ROTATION_TEST_AFTER_SECONDS") {
ensure!(
@@ -1071,6 +1137,8 @@ async fn main() -> Result<()> {
rotation_policy,
catalog: agent_update_catalog::Checker::default(),
update_observer: agent_update_apply::Observer::default(),
transfer_state,
transfer_gate: None,
};
agent.recover_interrupted()?;
let mut backoff = 1_u64;
@@ -1080,6 +1148,9 @@ async fn main() -> Result<()> {
report_closed_gate(&error);
}
agent.close_gate();
if let Some(guard) = agent.transfer_gate.take() {
return Ok(guard);
}
eprintln!("channel unavailable; retrying with jitter (no jobs can execute)");
if started.elapsed() > Duration::from_secs(60) {
backoff = 1;
+4
View File
@@ -152,6 +152,8 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
rotation_policy: certificate_rotation::RotationPolicy::default(),
catalog: agent_update_catalog::Checker::default(),
update_observer: agent_update_apply::Observer::default(),
transfer_state: None,
transfer_gate: None,
};
// A forged local consumption/start cannot become a purported grant result.
agent
@@ -541,6 +543,8 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
rotation_policy: certificate_rotation::RotationPolicy::default(),
catalog: agent_update_catalog::Checker::default(),
update_observer: agent_update_apply::Observer::default(),
transfer_state: None,
transfer_gate: None,
};
for _ in 0..rounds {
assert!(
@@ -42,7 +42,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
signature: URL_SAFE_NO_PAD.encode([1_u8; 64]),
};
let transition = match platform {
Platform::LinuxX64 if full => PeerPinTransition::LinuxGeneralFullV1 {
Platform::LinuxX64 | Platform::LinuxArm64 if full => PeerPinTransition::LinuxGeneralFullV1 {
general_pin_sha256: "10".repeat(32),
full: LinuxFullTransition {
schema_version: 1,
@@ -57,7 +57,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
effective_signing_key_id: "17".repeat(32),
},
},
Platform::LinuxX64 => PeerPinTransition::UnchangedGeneralPinV1 {
Platform::LinuxX64 | Platform::LinuxArm64 => PeerPinTransition::UnchangedGeneralPinV1 {
general_pin_sha256: "10".repeat(32),
},
Platform::WindowsX64 | Platform::WindowsGnuX64 => PeerPinTransition::WindowsCodePairV1 {
@@ -110,7 +110,7 @@ fn fixture(platform: Platform, full: bool) -> serde_json::Value {
update: Box::new(update),
},
execution_identity: match platform {
Platform::LinuxX64 => "root",
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
}
.into(),
+24 -1
View File
@@ -50,11 +50,34 @@ impl UpdateKeyringFile {
pub enum Platform {
#[serde(rename = "x86_64-unknown-linux-gnu")]
LinuxX64,
#[serde(rename = "aarch64-unknown-linux-gnu")]
LinuxArm64,
#[serde(rename = "x86_64-pc-windows-msvc")]
WindowsX64,
#[serde(rename = "x86_64-pc-windows-gnu")]
WindowsGnuX64,
}
pub const LINUX_ARM64_RELEASE_CAPABILITY: &str = "agent.release.linux.arm64/1";
impl Platform {
#[cfg(all(target_os = "linux", target_arch = "aarch64"))]
pub const NATIVE_LINUX: Self = Self::LinuxArm64;
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
pub const NATIVE_LINUX: Self = Self::LinuxX64;
pub const fn is_linux(self) -> bool {
matches!(self, Self::LinuxX64 | Self::LinuxArm64)
}
pub const fn target_triple(self) -> &'static str {
match self {
Self::LinuxX64 => "x86_64-unknown-linux-gnu",
Self::LinuxArm64 => "aarch64-unknown-linux-gnu",
Self::WindowsX64 => "x86_64-pc-windows-msvc",
Self::WindowsGnuX64 => "x86_64-pc-windows-gnu",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactRole {
@@ -708,7 +731,7 @@ impl ResolvedAgentUpdate {
}
pub fn execution_identity(&self) -> Option<&'static str> {
self.manifest().ok().map(|m| match m.platform {
Platform::LinuxX64 => "root",
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
})
}
+50
View File
@@ -0,0 +1,50 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub const CAPABILITY: &str = "device.customer_transfer/1";
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Offer {
pub transfer_id: Uuid,
pub source_tenant_id: Uuid,
pub source_agent_id: Uuid,
pub target_tenant_id: Uuid,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Binding {
pub offer: Offer,
pub asset_id: Uuid,
pub agent_id: Uuid,
pub certificate_sha256: String,
}
impl Binding {
pub fn signing_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
let mut bytes = b"rust-discovery:customer-transfer:1\0".to_vec();
bytes.extend(serde_json::to_vec(self)?);
Ok(bytes)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Receipt {
pub binding: Binding,
pub signature_hex: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CertificateRequest {
pub csr_pem: String,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CertificateResponse {
pub certificate_pem: String,
pub receipt: Receipt,
}
+65 -3
View File
@@ -1,7 +1,47 @@
//! Additive bounded passive metadata; the strict original Inventory stays intact.
use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const SOFTWARE_OBSERVATION_MAX_BYTES: usize = 128 * 1024;
pub const LINUX_SOFTWARE_OBSERVATION_MAX_BYTES: usize = 256 * 1024;
pub fn firmware_identifier(value: &str) -> Option<String> {
let value = value.trim_matches(|c: char| c == '\0' || c.is_whitespace());
let lower = value.to_ascii_lowercase();
(!value.is_empty()
&& value.len() <= 255
&& !value.chars().any(char::is_control)
&& !matches!(lower.as_str(), "none" | "unknown" | "not specified" | "not applicable"
| "default string" | "to be filled by o.e.m." | "system serial number")
&& !value.bytes().all(|b| b == b'0'))
.then(|| value.to_owned())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceType {
Physical,
Virtual,
Hypervisor,
}
#[derive(Clone, Copy)]
pub struct CpuTimes {
pub total: u64,
pub idle: u64,
}
impl CpuTimes {
pub fn usage_since(self, previous: Self) -> Option<u32> {
let total = self.total.checked_sub(previous.total)?;
let idle = self.idle.checked_sub(previous.idle)?;
let busy = total.checked_sub(idle)?;
(total != 0)
.then(|| ((u128::from(busy) * 10_000 + u128::from(total / 2)) / u128::from(total)) as u32)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Observation {
@@ -66,7 +106,7 @@ pub fn validate_for_scope(
.map_err(|_| "INVALID_AGENT_UPDATE_OBSERVATION")?
!= update
|| !typed.agent_update.validate()
|| (typed.agent_update.platform == crate::agent_update::Platform::LinuxX64) != (scope == "linux.base")
|| typed.agent_update.platform.is_linux() != (scope == "linux.base")
|| typed.agent_update.observed_at - now > chrono::Duration::seconds(45)
|| now - typed.agent_update.observed_at > chrono::Duration::hours(72)
{
@@ -127,10 +167,15 @@ pub fn validate_for_scope(
}
let mut scopes = std::collections::BTreeSet::new();
for item in observations {
let max_bytes = match (scope, item["scope"].as_str()) {
("linux.base", Some("linux.software")) => LINUX_SOFTWARE_OBSERVATION_MAX_BYTES,
("windows.base", Some("windows.software")) => SOFTWARE_OBSERVATION_MAX_BYTES,
_ => 32768,
};
if serde_json::to_vec(item)
.map_err(|_| "INVALID_OBSERVATION")?
.len()
> 32768
> max_bytes
{
return Err("OBSERVATION_SIZE");
}
@@ -225,6 +270,23 @@ mod tests {
assert!(validate(&serde_json::to_vec(&unknown).unwrap(), now).is_err());
}
#[test]
fn larger_linux_package_lists_fit_the_software_scope() {
let now = Utc::now();
let mut v = base();
let package = json!({"name":"some-package","version":"1.0","architecture":"amd64"});
v["collection_started_at"] = json!(now);
v["collection_completed_at"] = json!(now);
v["observations"] = json!([{"scope":"linux.software","source_id":"dpkg-query","observed_at":now,"quality":"valid","completeness":"complete","truncated":false,"error_code":null,"data":vec![package; 2200]}]);
let bytes = serde_json::to_vec(&v).unwrap();
assert!(bytes.len() > SOFTWARE_OBSERVATION_MAX_BYTES);
assert!(validate(&bytes, now).is_ok());
v["observations"][0]["scope"] = json!("linux.hardware");
assert_eq!(
validate(&serde_json::to_vec(&v).unwrap(), now).unwrap_err(),
"OBSERVATION_SIZE"
);
}
#[test]
fn windows_scope_does_not_weaken_linux_or_accept_platform_spoofing() {
let now = Utc::now();
let mut v = base();
+1
View File
@@ -3,6 +3,7 @@ pub mod agent_update;
pub mod agent_update_provisioning;
pub mod apt_transaction;
pub mod checkpoint_repair;
pub mod customer_transfer;
pub mod inventory_document;
pub mod jobs;
pub mod reconciliation;
-172
View File
@@ -1,172 +0,0 @@
# PostgreSQL pre-auth state adapter
Enable package feature **`postgres-state`**. Dependencies: SQLx 0.8 (PostgreSQL and
Tokio/rustls only; no macros/automatic migrations), RustCrypto `aes-gcm` 0.10.
The default build still has no SQL dependency. No root-workspace changes are needed.
## Migration and least privilege
Export: `rmm_oidc_auth::postgres::MIGRATION_SQL`, exactly the package-owned file
`sql/001_oidc_login_states.sql`. Transfer this SQL into a future **normal server
migration** under the migration/owner identity; the adapter never runs it. It is
deliberately not idempotent and creates a dedicated schema/table:
`rmm_oidc_auth.login_states(state_hash bytea PRIMARY KEY, binding_hash bytea,
expires_at bigint, created_at bigint, encryption_key_ref text,
encryption_nonce bytea, ciphertext bytea)` plus expiry index and integrity checks.
This is **global PREAUTH state**, not tenant data: no tenant IDs, principal IDs,
memberships or user attributes. Use a separate global-auth-service pool/role, not a
tenant transaction with previous RLS context. Grant only:
```sql
GRANT USAGE ON SCHEMA rmm_oidc_auth TO your_auth_service_runtime_role;
GRANT SELECT, INSERT, DELETE ON rmm_oidc_auth.login_states TO your_auth_service_runtime_role;
```
Replace the example role identifier through the normal deployment configuration,
not a request parameter. Runtime must be **non-owner, NOSUPERUSER, NOBYPASSRLS**,
without schema CREATE, UPDATE, TRUNCATE, tenant-table or migration permissions.
No RLS bypass is needed: the global table intentionally has no tenant RLS policy.
Membership and approval checks remain in the tenant-bound application layer.
Use verified PostgreSQL TLS for remote databases and restricted local transport
where appropriate. Never print DB URLs/passwords or enable parameter logging.
## Configuration and public API
```rust,ignore
use rmm_oidc_auth::postgres::PostgresStateStore;
// Pool supplied by the backend with the dedicated restricted global-auth role.
// Configure bounded acquisition timeout (e.g. 5 seconds) and pool size there.
let state_store = PostgresStateStore::new(
global_auth_pool,
secret_resolver.as_ref(),
"secret-store:rmm/oidc-state-key/version-1".into(),
10_000, // global outstanding-state capacity, including expired rows
).await?;
// Pass Arc::new(state_store) as the unchanged StateStore port to
// OidcAuth::discover(..., Profile::Production, ..., ...).
```
`PostgresStateStore::new(PgPool, &dyn SecretResolver, key_ref: String,
capacity: u32) -> Result<Self>` resolves exactly the configured reference, once.
The secret is **32 cryptographically random bytes encoded as unpadded base64url**.
Do not derive it from a password, the OIDC client secret, or a token claim. The
reference must identify an **immutable version**, not a mutable `latest` alias.
Store the key outside PostgreSQL and backups of login-state ciphertext. Ref strings
are metadata, not secret values. Never log the resolved key.
The library does not automatically read environment configuration. A backend may
map e.g. `RMM_OIDC_STATE_BACKEND=postgres`, `RMM_OIDC_STATE_KEY_REF` and a private DB
connection reference to this constructor; these are integration examples, not
implemented server flags. Missing/invalid configuration must fail startup closed.
`is_persistent()` is true for this adapter; `Profile::Production` continues rejecting
the memory adapter independently. No production in-memory fallback is provided.
## Confidentiality, atomicity and lifetime
- The existing flow generates 256-bit opaque state/binding values and passes only
canonical SHA-256 base64url hashes to `StateStore`. PostgreSQL stores their decoded
**32-byte digests**, not raw handles/cookies. Nonce and verifier are validated as
canonical 32-byte random-value encodings before persistence.
- The complete `PendingLogin` JSON is encrypted with **AES-256-GCM**, a fresh random
96-bit encryption nonce and authenticated associated data binding a fixed format
domain/version, state hash, browser-binding hash, expiry and configured key ref.
Plaintext serialization/decryption buffers and resolved key bytes are zeroized.
The store, pending records and key material have no Debug/log implementation.
Hashes, expiry, version reference and ciphertext length remain DB-visible.
A privileged DBA can delete/deny service, but cannot forge a valid encrypted login
without the external key. Protect the auth-service process and secret resolver.
- Insertion refuses expired states, TTL above **300 seconds**, duplicates and
capacity outside 1..=100,000. Database checks independently bound expiry relative
to creation (600 seconds for clock skew); DB clock also rejects expired insertions.
- A transaction-scoped, database-local advisory lock serializes admission checks
across adapter instances. A fresh READ COMMITTED snapshot prevents capacity races,
even on pools with a different default isolation level. All instances sharing a
table must use the **same capacity policy**. No upsert/overwrite path exists.
- Consumption is one parameterized **`DELETE ... WHERE state_hash=$1 AND
binding_hash=$2 AND encryption_key_ref=$3 AND expires_at > GREATEST($4, DB_now)
RETURNING ...`**. Exactly one concurrent callback receives a record. Wrong binding,
wrong key version, missing/replayed or expired state does not delete a valid row.
Thus a guessed-handle/wrong-cookie request cannot burn someone else's state.
- Delete is committed **before** authenticated decryption/parsing. Corruption,
nonce/code-exchange failure or later callback failure never restores state. A
connection failure during commit has uncertain delivery and fails closed: restart
login, never replay a potentially consumed flow.
- `cleanup_expired(batch: u32) -> Result<u64>` deletes only expired rows, at most
`batch` (1..=**1,000**), using the expiry index and one atomic CTE/DELETE.
It intentionally does not use SELECT FOR UPDATE, which would require granting
UPDATE privilege to this read/insert/delete-only role. Concurrent cleanup calls
may select the same expired batch; only one deletes it, another may return zero.
Call periodically from the global auth service; no background scheduler is spawned.
Each adapter transaction uses a 5-second statement timeout and 2-second lock
timeout; pool/network timeouts are the backend's connection policy. Expired rows
count against capacity until cleaned, deliberately failing closed under overload.
Rate-limit login start/callback independently; database capacity is not a rate limit.
- Key rotation for this first adapter is **drain then switch**: pause new logins,
allow outstanding flows to complete/expire, clean expired rows, switch all instances
to a new versioned external key, resume. Do not silently mutate a referenced key or
mix key versions during rolling deployment. Rotate well before 2^32 encryptions per
key. Old/incompatible ciphertext cannot be accepted by a differently configured key.
All queries use fixed schema/table names and bound data. No runtime table/schema
name interpolation, DDL, role changes, tenant RLS changes or session approvals occur.
## Explicit real PostgreSQL test
```sh
python3 crates/oidc-auth/tests/run_postgres.py
```
The runner refuses an existing container named **`rust-discovery-oidc-test`**. It
creates only that disposable PostgreSQL 17.6 container, publishes an automatically
allocated port **only on 127.0.0.1**, generates a private ephemeral password in memory,
and removes its own container/anonymous volumes afterwards. Existing PostgreSQL and
RMM containers are never inspected for credentials, restarted, migrated or reset.
No credential file, stdout secret, host service package or VM change is needed.
The Rust integration test is explicitly ignored in ordinary test runs. The runner
opts in with `RMM_OIDC_TEST_ALLOW_OWNER_DDL=isolated` and a private
`RMM_OIDC_TEST_DATABASE_URL` passed only through process environment; only the
disposable owner test identity applies fixture DDL and creates a separate restricted
runtime role. Do not point these variables at a real server database.
Checks: runtime nonownership/no superuser/no BYPASSRLS/no schema CREATE and actual
DDL rejection; encrypted persistence; wrong-cookie non-burning; caller/DB expiry;
duplicate/replay rejection; exactly one winner among 16 callbacks; authenticated
ciphertext-tamper rejection and consumption; concurrent capacity 2/8; bounded TTL
cleanup; invalid hashes/TTL rejection. This is a local native PostgreSQL test, not
server/VM or external-IdP acceptance. Actual run results are recorded separately.
## Actual local verification — 2026-11-12
Executed on the development Linux host, not the Linux test VM:
- `cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features --locked -- -D warnings`: passed.
- `cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked`:
**13 unit tests passed**, 0 failed; the explicit-owner PostgreSQL test is ignored
in this general run; 0 documentation tests.
- `python3 crates/oidc-auth/tests/run_postgres.py`: **1 actual PostgreSQL integration
test passed**, 0 failed, 0 ignored. PostgreSQL 17.6; restricted non-owner role with
real DDL/UPDATE rejection; **1/16** concurrent consume winners; **2/8** concurrent
capacity admissions. Also checked ciphertext, binding non-burning, DB/caller expiry,
duplicates/replay, tamper consumption, cleanup limits, key-version mismatch,
invalid key/hash and overlong TTL rejection. Own disposable container removed.
- `cargo check --manifest-path crates/oidc-auth/Cargo.toml --lib --no-default-features --locked`: passed.
- `cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check`: passed.
- `cargo package --manifest-path crates/oidc-auth/Cargo.toml --allow-dirty --features postgres-state --locked`:
packaged **11 files** and verified the extracted package build successfully.
Non-failing warning: package metadata has no description/documentation/homepage/repository.
The first Clippy run rejected a deprecated generic-array nonce constructor; replaced
with array conversion, no lint suppression. The first real database run reached
cleanup but failed there: SELECT FOR UPDATE required UPDATE permission. Cleanup
was changed to a bounded atomic CTE/DELETE, retaining the restricted role rather
than expanding its privileges. Both subsequent real PostgreSQL runs passed, including
the final expanded test. No server DB migration/reset, runtime server restart,
membership change, host package installation, VM effect or production acceptance.
The migration has been applied only to the disposable test database. Applying it
through normal server migrations, provisioning the global auth role/key reference,
and wiring backend configuration/routes remain explicit integration work.
+3 -162
View File
@@ -1,164 +1,5 @@
# RMM OIDC authentication adapter (standalone package)
# Authentisierung im MVP
Optional encrypted SQLx/PostgreSQL login-state storage and its migration/permissions
contract: **[POSTGRES.md](POSTGRES.md)** (`postgres-state` feature).
Die öffentliche WebUI verwendet ein lokales Konto mit Passwort und TOTP. Der MCP-Server prüft kundengebundene Bearer-Tokens. Die Einrichtung dieser beiden Zugänge steht in der [Betriebsanleitung](../../docs/public-access.md).
This crate is **not wired into the server** and does not change the root workspace.
It authenticates against a configured HTTPS OIDC provider using real RSA signatures,
discovery, JWKS and authorization-code exchange. It never grants tenant membership,
roles, approval authority or an RMM session by itself. External IdP configuration is
currently **not_configured**; no external-provider or VM acceptance is claimed.
## Explicit supported provider profile
- RS256 only, RSA signing JWKS with unique `kid`, `alg=RS256`, `use=sig`.
Mixed-algorithm JWKS are deliberately rejected by this initial strict profile.
- Configured issuer is the only authority. Discovery's issuer must match exactly;
authorization, token and JWKS endpoints must be HTTPS, same **origin** (including
port) as that issuer, with no userinfo, fragment or query. Providers using a separate
CDN/origin for JWKS are not supported, rather than automatically trusted.
- Normal rustls trust roots, optional explicitly provisioned CA roots; no HTTP,
insecure certificate mode, HTTP redirects or environment proxy. Administrators
must restrict configured issuers/network egress; user input cannot choose issuers.
- Browser: authorization code, `openid`, PKCE S256, random nonce/state/browser binding,
fixed registered HTTPS callback, `client_secret_post`. The IdP must advertise these
features. PKCE rejection surfaces as `CodeExchange`; response bodies are not logged.
- MCP: RFC 9068 JWT **access** token with `typ=at+jwt`, dedicated resource audience,
approved `client_id`, required `jti`, issuer/signature/expiry/nbf/iat checks, required scopes.
Opaque/introspected tokens and other JWT access-token profiles are unsupported.
Browser ID tokens are never accepted as bearer credentials.
- JWT validity uses zero clock leeway; synchronize clocks. Browser multiple audiences
require matching `azp`; any supplied browser `azp` must match the browser client ID.
- JWKS cache TTL 300 seconds; unknown-kid refresh throttled to once per second,
serialized across callers. A newly rotated key may require retry after one second.
Invalid JWKS/failed refresh clears the old key cache and fails closed. Revocation of
a cached key is bounded by the TTL, not instantaneous. Issuer operator must rotate
to a **new kid** (same-kid replacement is visible on the next TTL refresh).
- HTTP connect timeout 3 seconds, total request timeout 10 seconds, response 128 KiB,
JWT 32 KiB, code 4 KiB, maximum 64 signing keys. No refresh-token persistence.
## Public integration API
```rust,ignore
let auth = OidcAuth::discover(
Config {
issuer: Url::parse("https://idp.example/realms/rmm")?,
browser_client_id: "rmm-browser".into(),
client_secret_ref: "secret-store:rmm/oidc-client".into(),
redirect_uri: Url::parse("https://rmm.example/auth/oidc/callback")?,
mcp_audience: "https://rmm.example/mcp".into(),
mcp_client_ids: BTreeSet::from(["approved-mcp-client".into()]),
},
Profile::Production,
persistent_state_store,
secret_resolver,
vec![], // normal roots; provision a private CA explicitly if necessary
).await?;
let start: LoginStart = auth.login_start().await?;
// Set start.binding_set_cookie and redirect to start.authorization_url.
let identity: Identity = auth.callback(Callback {
code: parsed_query_code,
state: parsed_query_state,
browser_binding: parsed_host_binding_cookie,
}).await?;
let bearer: BearerIdentity = auth
.verify_mcp_bearer(raw_bearer, &["inventory:read"]).await?;
```
`SecretResolver::resolve(reference)` returns `secrecy::SecretString`; resolve from an
authorized secret store, never from a token claim. The adapter exposes only coarse
typed `Error`s, not reqwest errors (which may contain URLs), codes or token bodies.
Do not log callback URLs, authorization URLs, cookies, state records, secrets or JWTs.
Sensitive flow types intentionally do not implement `Debug`.
### Required server/cookie adapter work (not implemented here)
1. Register login start and **GET** callback routes. Rate-limit both; do not allow
caller-supplied issuer, audience, scopes, redirect URI or post-login return URL.
Reject duplicate query/cookie parameters and provider error callbacks. Return
`Cache-Control: no-store` and `Referrer-Policy: no-referrer` on all auth routes;
avoid request/query logging and third-party resources there.
2. Set `LoginStart.binding_set_cookie` verbatim: `__Host-rmm_oidc_binding`, Secure,
HttpOnly, Path=/, **SameSite=Lax**, Max-Age=300, no Domain. Strict would omit this
cookie on the cross-site provider callback. Start replaces an outstanding binding;
multi-tab login is intentionally fail-closed, not a bypass.
3. Pass only parsed code/state and binding cookie value to `callback`. The store must
atomically consume state before token exchange. On terminal callback success or
failure, clear binding with `CLEAR_BINDING_COOKIE`; failures require fresh login.
4. Resolve `Identity { issuer, subject }` to a persistent principal and **current**
scoped memberships. Email and untrusted group/role claims are not identity keys or
memberships (this crate does not expose them). No implicit all-tenant role.
5. On browser success only, rotate/create a new opaque RMM session, bound to that
principal, with bounded expiry and the existing Secure/HttpOnly/host-only
**SameSite=Strict** final session cookie. Keep CSRF token + exact Origin checks
for writes, authorization checks and explicit UI plan approval. An ID token is
not an RMM session cookie or permission to approve a plan.
6. Bearer always wins over browser cookies. Use `verify_mcp_bearer` only for MCP/API
bearer paths; combine returned scopes with persistent memberships on **every**
request. Never construct an interactive browser session or approval context from
a bearer token, even if a principal has an approver membership. Preserve
`pending_approval` and all immutable plan/attempt bindings.
7. Logout must invalidate the **server-side RMM session**, clear the final cookie,
require its normal CSRF/Origin checks and prevent reuse. IdP logout is intentionally
not implemented or falsely advertised; local logout does not end an IdP session.
8. Disable dev identities/simulated principals in production independently of this
crate. Existing dev identity auth is not replaced until the backend is integrated.
### Persistent state store port
Alternative adapters must implement async `StateStore::{insert, consume}` plus `is_persistent() == true` using
shared durable storage. Do not merely return true for a memory-backed adapter.
State lookup keys and browser bindings supplied to the store are SHA-256 base64url
hashes; records contain nonce, verifier and absolute Unix expiry. Protect record
contents at rest and restrict database access. `insert` must enforce unique keys,
bounded capacity and expiry cleanup. `consume` must perform one atomic conditional
delete/return based on `(state_hash, binding_hash, expires_at > now)`; no read-then-
delete race, no restoration after exchange/nonce failure. A SQL transaction or
`DELETE ... WHERE ... RETURNING` is suitable. Store failures must fail closed.
`dev::InMemoryStateStore::new(dev::DevTestOnly)` exists only under the explicit
`dev-memory-store` feature or unit tests. `Profile::Production` rejects it. This is
not a production SQL adapter. The optional PostgreSQL adapter below supplies durable
encrypted storage; applying its migration and server wiring remain integration work.
## Targeted local verification
```sh
cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check
cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings
cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features
```
Tests run a native loopback HTTPS OIDC provider with an ephemeral private CA, real
2048-bit RSA signing keys/JWKS, actual one-use authorization codes, real form-encoded
token exchange and server-enforced PKCE. The CA is added only to the test clients,
never to the host truststore. No checked-in private key, external IdP, VM modification,
host-service installation, Docker/server restart or reboot is needed. The provider
is a test double, not a claim of external-provider interoperability or VM acceptance.
Test assertions/counters contain no secret output. Run results are reported separately
by the implementation dispatch, not presumed by these commands.
### Actual local verification (2026-11-12)
Executed on the development Linux host, not the Linux test VM:
- `cargo fmt --manifest-path crates/oidc-auth/Cargo.toml --check`: passed.
- `cargo clippy --manifest-path crates/oidc-auth/Cargo.toml --all-targets --all-features -- -D warnings`: passed.
- `cargo test --manifest-path crates/oidc-auth/Cargo.toml --all-features --locked`:
**13 passed, 0 failed**; 0 documentation tests. Covers real code exchange,
browser binding/replay/expiry/concurrency, PKCE failure, nonce/authorized party,
issuer/audience/expiry/nbf/iat/required claims/scopes, algorithm/signature/ID-token
confusion, JWKS caching/rotation, actual TLS trust/hostname rejection, discovery
origin restrictions, HTTP redirect rejection and response/token size limits.
- `cargo metadata --manifest-path crates/oidc-auth/Cargo.toml --no-deps --format-version 1`:
independent workspace at `crates/oidc-auth`, exactly one member and own lockfile.
Initial build checks found missing URL serde and JWT PEM feature flags; both were
fixed. Clippy found an unnecessary test `format!`, also fixed. The final commands
above passed after those corrections. Pinned lockfile resolves jsonwebtoken 10.4.0,
reqwest 0.12.28 and rustls 0.23.46 on the repository's Rust 1.99.1 toolchain.
Not executed in that initial verification: external real-IdP interoperability, production SQL state adapter,
server routes/cookies/sessions/membership integration, VM execution or browser UI
login against the running RMM server. Timeout values are configured; a deliberately
stalling provider timeout test has not been run. No production acceptance claimed.
Dieses Rust-Paket wird vom Server als lokale Abhängigkeit eingebunden und enthält den separat konfigurierbaren OIDC-Adapter. Im öffentlichen MVP ist dieser Adapter deaktiviert. [Server-Abhängigkeiten](../server/Cargo.toml) · [Authentisierung im Server](../server/src/auth.rs)
+5 -1
View File
@@ -5,5 +5,9 @@ edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
sqlx.workspace = true
# Use the PostgreSQL driver directly. SQLx 0.8's generic migration and type
# features also resolve the obsolete SQLite driver in the shared lockfile.
sqlx = { package = "sqlx-core", version = "=0.8.6", features = ["migrate", "_rt-tokio", "_tls-rustls-ring-webpki"] }
sqlx-macros = { version = "=0.8.6", features = ["migrate"] }
sqlx-postgres = { version = "=0.8.6", features = ["migrate", "chrono", "uuid", "json"] }
uuid.workspace = true
+6 -5
View File
@@ -1,17 +1,18 @@
use anyhow::{Result, ensure};
use sqlx::{PgPool, Postgres, Transaction};
use sqlx::{query::query, query_scalar::query_scalar};
use sqlx_postgres::{PgPool, PgTransaction};
use uuid::Uuid;
pub async fn tenant_tx(pool: &PgPool, tenant: Uuid) -> Result<Transaction<'_, Postgres>> {
pub async fn tenant_tx(pool: &PgPool, tenant: Uuid) -> Result<PgTransaction<'_>> {
let mut tx = pool.begin().await?;
sqlx::query("SELECT set_config('app.tenant_id', $1, true)")
query("SELECT set_config('app.tenant_id', $1, true)")
.bind(tenant.to_string())
.execute(&mut *tx)
.await?;
Ok(tx)
}
pub async fn verify_application_role(pool: &PgPool) -> Result<()> {
let unsafe_role: bool = sqlx::query_scalar(
let unsafe_role: bool = query_scalar(
"SELECT rolsuper OR rolbypassrls OR EXISTS (SELECT 1 FROM pg_tables WHERE schemaname='public' AND tableowner=current_user) FROM pg_roles WHERE rolname=current_user",
).fetch_one(pool).await?;
ensure!(
@@ -22,7 +23,7 @@ pub async fn verify_application_role(pool: &PgPool) -> Result<()> {
}
pub async fn migrate(url: &str) -> Result<()> {
let pool = PgPool::connect(url).await?;
sqlx::migrate!("../../migrations").run(&pool).await?;
sqlx_macros::migrate!("../../migrations").run(&pool).await?;
pool.close().await;
Ok(())
}
+1 -1
View File
@@ -15,7 +15,7 @@ serde_json.workspace = true
uuid.workspace = true
libc = "0.2.177"
fs2 = "0.4.3"
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
rmm-domain = { path = "../domain" }
rmm-agent-linux = { path = "../agent-linux" }
+4 -2
View File
@@ -78,9 +78,11 @@ impl Config {
})
}
fn validate_profile(&self) -> Result<()> {
let state = self.state.as_path();
ensure!(
self.state.as_path()
== std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE),
state == std::path::Path::new(rmm_privileged_helper::readiness::SHARED_STATE)
|| (self.profile == HelperProfile::FullMaintenanceV1
&& state == std::path::Path::new("/var/lib/rmm-discovery-helper")),
"SHARED_HELPER_LEDGER_REQUIRED"
);
if self.profile == HelperProfile::FullMaintenanceV1 {
@@ -110,7 +110,7 @@ pub fn observe_record(
&& response.ledger_inode != 0
&& response.lock_inode != 0
&& response.observation.validate()
&& response.observation.platform == Platform::LinuxX64,
&& response.observation.platform == Platform::NATIVE_LINUX,
"UPDATE_OBSERVER_RESPONSE_BINDING"
);
let record = rmm_domain::agent_update_provisioning::InstalledReleaseRecord::from_bytes(
@@ -346,7 +346,7 @@ pub fn collect(db: &Connection, local: Local<'_>, request: &Request) -> Result<R
));
let observation = AgentUpdateObservation {
schema_version: 1,
platform: Platform::LinuxX64,
platform: Platform::NATIVE_LINUX,
observed_at,
quality: ObservationQuality::Valid,
predecessor: Some(trust.predecessor().clone()),
+12
View File
@@ -81,6 +81,17 @@ pub struct Heartbeat {
pub instance_id: String,
#[prost(uint64, tag = "2")]
pub uptime_seconds: u64,
#[prost(message, optional, tag = "3")]
pub system_usage: Option<SystemUsage>,
}
#[derive(Clone, PartialEq, Message)]
pub struct SystemUsage {
#[prost(uint32, optional, tag = "1")]
pub cpu_usage_basis_points: Option<u32>,
#[prost(uint64, optional, tag = "2")]
pub ram_available_bytes: Option<u64>,
#[prost(uint64, optional, tag = "3")]
pub ram_total_bytes: Option<u64>,
}
#[derive(Clone, PartialEq, Message)]
pub struct InventorySnapshot {
@@ -156,6 +167,7 @@ mod tests {
payload: Some(Payload::Heartbeat(Heartbeat {
instance_id: "x".into(),
uptime_seconds: 1,
system_usage: None,
})),
..Default::default()
};
-200
View File
@@ -1,200 +0,0 @@
# Integrated OIDC/OAuth authentication
The server now wires `rmm-oidc-auth` into real browser, HTTP and MCP paths. External
IdP deployment is **not_configured** unless the administrator supplies configuration.
No external-provider interoperability or production/VM acceptance is implied.
## Configuration
Set `RMM_OIDC_CONFIG_FILE` to an absolute, regular non-symlink **0600** JSON file
with a same-owner, non-group/world-writable parent. All secret references are absolute
0600 private files with that same owner and safe parent. Their contents are never
passed as argv, logged, reflected in errors or read as shell. Example (placeholders):
```json
{
"issuer": "https://idp.example/realms/rmm",
"browser_client_id": "rmm-browser",
"client_secret_ref": "/private/rmm/oidc-client-secret-v1",
"redirect_uri": "https://rmm.example/auth/oidc/callback",
"mcp_audience": "https://rmm.example/mcp",
"mcp_client_ids": ["approved-mcp-client"],
"auth_database_url_ref": "/private/rmm/oidc-auth-database-url",
"state_key_ref": "/private/rmm/oidc-state-key-v1",
"extra_ca_file": null,
"testsimulation": false
}
```
`RMM_UI_ORIGIN` must be the exact HTTPS origin without trailing slash. The callback
must equal that origin plus `/auth/oidc/callback`. Normal roots are used; optional
`extra_ca_file` explicitly provisions a private IdP CA, never an insecure TLS mode.
Issuer discovery/JWKS/endpoints use configured-issuer same-origin HTTPS, no redirects,
fixed RS256 and bounded requests. The supported provider profile is documented in
`../oidc-auth/README.md` (PKCE S256, nonce, client_secret_post; RFC9068 access tokens).
`state_key_ref` contains 32 random bytes encoded as unpadded base64url, with an
immutable versioned reference. The package's AES-256-GCM state protection, 300-second
TTL, atomic binding/consume, capacity and drain-before-key-rotation rules remain intact.
Global state cleanup runs in bounded 1,000-row batches every 30 seconds.
Production requires `RMM_PROFILE=production`, `RMM_DEV_AUTH=false`, configured OIDC
and **no** RMM_DEV_USERNAME/PASSWORD, RMM_OPERATOR_A/B or RMM_VIEWER_A/B values.
Production with dev auth is rejected before connecting. `testsimulation=true` is
accepted only in the explicit development profile, never derived from token claims.
Development retains the existing separately credentialed browser/viewer/operator
paths. Neither profile silently falls back after invalid explicit bearer credentials.
Non-OIDC production gaps remain: the local ArtifactStore is still development-only;
artifact-dependent features fail closed until a production adapter is supplied.
Root/APT selected policies remain development-only and unchanged in their authority.
## Migration and provisioning
Normal migration **0011_oidc_auth.sql** creates global encrypted pre-auth state and
the administrator-maintained external identity index, extends membership kind with
`human` and constrains authorization audit pairs to exactly:
- `dev_test_browser_simulation` + `testsimulation=true`
- `human_webui` + `testsimulation=false`
The runtime does **not** create schemas, tables, identities, memberships or roles.
Apply normal migrations without resetting DB/PKI. Provision a separate global-auth
login identity with only schema USAGE and table SELECT/INSERT/DELETE on
`rmm_oidc_auth.login_states`. The server verifies that this pool is neither superuser,
BYPASSRLS, table owner nor schema creator, and cannot SELECT tenant memberships.
The tenant application pool remains `rmm_app`, nonowner and RLS-bound. Neither needs
a general RLS bypass. Do not reuse the tenant application's database URL for auth state.
An administrator explicitly registers each external `(issuer,subject)` in
`public.oidc_principals` and assigns tenant routing references; the principal ID is:
`oidc:` + lowercase SHA-256 hex of compact UTF-8 JSON `[issuer,subject]`.
Rust helper: `oidc::principal_id`. Email/group claims are never identity or membership.
The index is routing metadata only: each chosen tenant still requires a current,
unrevoked `memberships` row with explicit permissions. Browser login additionally
requires membership kind **human**. No auto-registration, tenant or role grants occur.
Disabling the index entry revokes subsequent auth and persisted permission rechecks,
including start-time rights checks for existing plans. Membership revocation is read
on every authenticated HTTP/MCP call, not cached from an ID token or browser session.
Only narrow, fixed-search-path SECURITY DEFINER lookup functions expose identity
routing/enabled status to rmm_app; they do not bypass/query memberships RLS or return
foreign inventory. MCP/HTTP permissions intersect the validated access-token scopes
with current membership. Script/root operations retain their additional permission
and selected-helper checks. Bearers have no interactive session context, even with
an approver membership/scope plus a valid browser cookie.
## UI-compatible routes and cookie contract
- `GET /auth/config`: `{oidc_configured,oidc_login_url,dev_login_enabled}`.
`oidc_login_url` is `/auth/oidc/login` when configured, otherwise null. UI can show
a nonempty configured-provider sign-in link without knowing secrets.
- `GET /auth/oidc/login`: code-flow redirect, binding cookie
`__Host-rmm_oidc_binding`, Secure/HttpOnly/Path=/, **SameSite=Lax**, 300 seconds.
- `GET /auth/oidc/callback`: code + state (optional issuer response check), duplicate
query/cookie rejection, one-use DB state, token exchange and nonce/PKCE/signature
checks, persistent principal/membership mapping. Clears binding on success/failure.
Establishes a new opaque RMM session and redirects only to `/`, never user input.
- `GET /auth/session`: existing DTO retained (`principal`, `tenant_id`, `permissions`,
`roles`, `csrf_token`, `testsimulation`, `approval_origin`). Final cookie remains
`__Host-rmm_session`, Secure/HttpOnly/host-only, **SameSite=Strict**, one hour.
Sessions remain in memory; restart requires fresh OIDC login, not job resubmission.
- `POST /auth/logout`: exact Origin + session CSRF; server-side invalidation and cookie
clearing. Local RMM logout only; no false claim of IdP logout.
All auth responses are no-store/no-referrer. Do not enable callback/query logging,
browser traces, HAR, screenshots or third-party resources on auth pages. Browser
writes and plan authorizations retain exact Origin/CSRF and immutable plan binding.
Tenant selection comes from the API path, overriding an incoming X-RMM-Tenant header;
MCP dispatch selects its explicit tenant_id. X-RMM-Tenant is only a selection hint for
other calls, never authority: it must exist in the mapped index AND current tenant
membership. `/api/v1/tenants` lists current readable memberships using separate RLS
transactions. Foreign tenant/asset paths remain not-found, not token-controlled routing.
## Targeted integration tests
`python3 tests/oidc/server_integration.py` starts an ephemeral native TLS mock IdP
and native loopback API instance against the existing development PostgreSQL. It
provisions/removes only its own synthetic identity/human membership and a distinct
restricted auth-state login role. No approval/job/permit/VM fixture is fabricated.
It uses a private ephemeral CA, real RSA signatures/JWKS, actual one-use code exchange
and PKCE. The Chromium step uses a temporary NSS truststore, no TLS bypass/artifacts,
and actual provider UI navigation/cross-site callback; **no job approval** occurs.
It also starts a configured production-profile API with simulation false to check
the production auth path, not to claim real-provider/human production acceptance.
Credentials are parsed internally from local private development configuration;
never printed, sourced, passed in argv or included in test failure output.
Existing backend contract, transport, pages/catalog, sync and local integration tests
remain required after deployment. Actual commands/counts are returned by the dispatch;
the descriptions here are not presumed successful test results.
## Verified local auth increment (2026-11-12)
- Native server build and `cargo clippy -p rmm-server --all-targets --locked -- -D warnings`
passed; changed server files passed targeted rustfmt checking.
- Targeted Rust tests: server **7**, domain **11**, protocol **3**, persistence **0**;
all passed. Three server tests cover the added cookie/scope/identity contracts.
- Standalone OIDC package: **13** unit tests passed; the ordinary run explicitly
ignores its owner-opt-in database test, then `tests/run_postgres.py` ran that **1**
real PostgreSQL integration test successfully (1/16 consume, 2/8 capacity).
- Integrated native server/real mock TLS/real PostgreSQL/Chromium test:
**35 assertions passed**, including production-profile startup with OIDC configured,
simulation false and dev login absent, and actual MCP tool scope enforcement.
No plan was approved or executed by this increment.
- Python syntax checks and Node browser-script syntax check passed.
Initial build/harness failures were corrected without weakening checks: root Cargo
needed to exclude the nested standalone OIDC workspace; Python environment merging
needed to avoid duplicate keywords; dev login must not register its JSON extractor
route in production; MCP testing must consume a concrete SSE response instead of
waiting for stream closure. A backend regression also exposed that tenant-denied
authentication must preserve NOT_FOUND in the MCP/HTTP structured error code; the
shared mapper now preserves it instead of calling every failure UNAUTHENTICATED.
External IdP configuration and all VM/real-human production-approval acceptance
remain open. The running development deployment intentionally retains its existing
dev identities unless an administrator provisions the OIDC configuration and the
separate state-pool identity; no sample provider is silently enabled there.
### Final deployed backend verification
Normal additive migrations **0009, 0010 and 0011** were applied without DB/PKI
reset; successful migration history is **1 through 11**. Docker release build of
server **and agent** succeeded after adding the exact embedded helper unit
`deploy/linux/rmm-apt-helper.service` to the Docker COPY/context whitelist. The
unit/helper/provider source and its hardening were not altered by this auth work.
`python3 deploy/dev.py up` rebuilt/recreated only the project server/migration service;
existing PostgreSQL stayed running. Final server observation:
- started **2026-11-12T19:12:38.969913632Z**, status running;
- image `sha256:545318218433a5d0be96c9368096cb2850b059be0b690bee5044ab28aad5cb82`;
- published TLS port only `127.0.0.1:18443`; PostgreSQL has no published port;
- actual `/auth/config` returns dev login enabled, OIDC not configured, login URL null.
All five affected backend integration programs then passed against that deployment:
| Program | Actual PASS assertions |
| --- | ---: |
| `tests/backend_contract.py` | 42 |
| `tests/backend_transport.py` | 20 |
| `tests/backend_pages_catalog.py` | 25 |
| `tests/backend_sync.py` | 28 |
| `tests/local_integration.py` | 35 |
| **Total** | **150** |
These are assertion counts in five integration programs, not 150 Rust test cases.
They cover unchanged immutable pending/approval boundaries, mTLS and rotation,
fencing/housekeeping, catalog/pagination/membership, signing-key/bootstrap,
Sync/reconnect/restore denial, extended native inventory and tenant isolation.
The final NOT_FOUND mapper correction passed the previously failing MCP foreign-
tenant contract. Four additional actual database-boundary assertions passed:
rmm_app cannot directly read pre-auth state or the external identity index, the
narrow lookup rejects a missing identity, and rmm_app remains non-superuser/non-BYPASSRLS.
No VM/systemd/root/APT effect, positive plan approval or privileged-helper execution
was performed by this dispatch. Linux-MVP, positive consumed-job/helper SyncAck and
real external-IdP/human production-approval acceptance remain separate gates.
+2 -3
View File
@@ -36,7 +36,7 @@ pub async fn download(
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, t).await?;
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying','awaiting_reboot') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL").bind(a).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or(Error(StatusCode::NOT_FOUND,"NOT_FOUND"))?;
let job: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
let plan_bytes: Vec<u8> = row.get("plan_payload");
if rmm_domain::jobs::hash(&plan_bytes) != row.get::<String, _>("plan_hash") {
@@ -46,8 +46,7 @@ pub async fn download(
if job.action.windows_msi().is_some() {
crate::windows_msi_catalog::validate_job_binding(&plan, &job)?;
crate::catalog::check(&mut tx, &job.action).await?;
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?;
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
crate::jobs::authorize_approved_job(&s, &mut tx, t, &plan, &job, &row).await?;
}
if job.asset_id != row.get::<Uuid, _>("asset_id")
+55 -1
View File
@@ -4,6 +4,7 @@ use chrono::{DateTime, Utc};
use prost::Message;
use rmm_domain::MAX_MESSAGE;
use rmm_protocol::*;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use sqlx::Row;
use uuid::Uuid;
@@ -146,7 +147,14 @@ pub async fn ingest(
match &e.payload {
Some(Payload::Heartbeat(h)) => {
Uuid::parse_str(&h.instance_id)?;
sqlx::query("UPDATE agent_installations SET last_contact_at=now() WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).execute(&mut *tx).await?;
let usage = h.system_usage.as_ref().and_then(|sample| system_usage(sample, observed));
sqlx::query("UPDATE agent_installations SET last_contact_at=now(),
system_usage=CASE WHEN $2::jsonb IS NULL THEN system_usage
ELSE COALESCE(system_usage,'{}'::jsonb) || $2 END,
system_usage_observed_at=CASE WHEN $2::jsonb ? 'ram_available_bytes'
THEN $3 ELSE system_usage_observed_at END
WHERE agent_id=$1 AND revoked_at IS NULL")
.bind(agent).bind(usage).bind(observed).execute(&mut *tx).await?;
}
Some(Payload::InventorySnapshot(s)) => {
ensure!(
@@ -197,3 +205,49 @@ pub async fn ingest(
e.connection_generation,
))
}
fn system_usage(sample: &SystemUsage, observed: DateTime<Utc>) -> Option<Value> {
let cpu = sample
.cpu_usage_basis_points
.filter(|&value| value <= 10_000);
let memory = sample
.ram_available_bytes
.zip(sample.ram_total_bytes)
.filter(|&(available, total)| total > 0 && available <= total);
let mut usage = serde_json::Map::new();
if let Some(cpu) = cpu {
usage.insert("cpu_usage_percent".into(), json!(f64::from(cpu) / 100.0));
usage.insert("cpu_usage_observed_at".into(), json!(observed));
}
if let Some((available, total)) = memory {
usage.insert("ram_available_bytes".into(), json!(available));
usage.insert("ram_total_bytes".into(), json!(total));
}
(!usage.is_empty()).then_some(Value::Object(usage))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_zero_usage_and_ignores_invalid_metrics_without_losing_the_heartbeat() {
let mut sample = SystemUsage {
cpu_usage_basis_points: Some(0),
ram_available_bytes: Some(0),
ram_total_bytes: Some(1),
};
let now = Utc::now();
let measured = system_usage(&sample, now).unwrap();
assert_eq!(measured["cpu_usage_percent"], json!(0.0));
assert_eq!(measured["cpu_usage_observed_at"], json!(now));
assert_eq!(measured["ram_available_bytes"], json!(0));
assert_eq!(measured["ram_total_bytes"], json!(1));
sample.cpu_usage_basis_points = Some(10_001);
let partial = system_usage(&sample, now).unwrap();
assert!(partial.get("cpu_usage_percent").is_none());
assert!(partial.get("cpu_usage_observed_at").is_none());
sample.ram_available_bytes = Some(2);
assert_eq!(system_usage(&sample, now), None);
}
}
+1 -1
View File
@@ -418,7 +418,7 @@ async fn issue(
&& snapshot.sha256 == hex::decode(hash(&snapshot.data)).map_err(|_| denied())?,
)?;
let scope = match action.manifest().map_err(|_| denied())?.platform {
update::Platform::LinuxX64 => "linux.base",
update::Platform::LinuxX64 | update::Platform::LinuxArm64 => "linux.base",
update::Platform::WindowsX64 | update::Platform::WindowsGnuX64 => "windows.base",
};
// Health requires a fresh real base inventory of the restarted platform;
+166 -64
View File
@@ -14,9 +14,10 @@ use axum::{
response::{IntoResponse, Response},
routing::{get, post},
};
use chrono::{DateTime, Utc};
use futures_util::StreamExt;
use rmm_domain::{
agent_update::{ArtifactDescriptor, Platform, ReleaseEnvelope, ReleaseManifest},
agent_update::{ArtifactDescriptor, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseEnvelope, ReleaseManifest},
jobs::{ArtifactReference, encode, hash},
};
use serde::Deserialize;
@@ -41,11 +42,7 @@ fn invalid() -> Error {
Error(StatusCode::BAD_REQUEST, "INVALID_AGENT_RELEASE")
}
pub fn platform_name(platform: Platform) -> &'static str {
match platform {
Platform::LinuxX64 => "x86_64-unknown-linux-gnu",
Platform::WindowsX64 => "x86_64-pc-windows-msvc",
Platform::WindowsGnuX64 => "x86_64-pc-windows-gnu",
}
platform.target_triple()
}
pub fn protected_file(path: &FsPath, maximum: u64) -> Result<Vec<u8>, Error> {
let key_path =
@@ -123,11 +120,13 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
if !metadata.is_file() || metadata.permissions().mode() & 0o077 != 0 {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
let profile = std::env::var("RMM_PROFILE").unwrap_or_default();
Ok(UpdateArtifacts::new(
&std::env::var("RMM_PROFILE").unwrap_or_default(),
&profile,
match std::env::var_os("RMM_AGENT_UPDATE_ARTIFACT_DIR") {
Some(value) if FsPath::new(&value).is_absolute() => value.into(),
Some(_) => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
None if profile != "development" => return Err(fail("AGENT_UPDATE_NOT_CONFIGURED")),
None => path
.parent()
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))?
@@ -136,14 +135,7 @@ pub fn store() -> Result<UpdateArtifacts, Error> {
metadata.uid(),
)?)
}
fn verifier_platform(platform: Platform) -> rmm_updater::Platform {
match platform {
Platform::LinuxX64 => rmm_updater::Platform::LinuxX64,
Platform::WindowsX64 => rmm_updater::Platform::WindowsX64,
Platform::WindowsGnuX64 => rmm_updater::Platform::WindowsGnuX64,
}
}
/// Network input can choose only one of two statically named protected
/// Network input can choose only among statically named protected
/// configuration slots. It never supplies a path or introduces update trust.
fn keyring_path_with(
platform: Platform,
@@ -151,8 +143,21 @@ fn keyring_path_with(
) -> Result<std::path::PathBuf, Error> {
let name = match platform {
Platform::LinuxX64 => "RMM_AGENT_UPDATE_LINUX_KEYRING_FILE",
Platform::LinuxArm64 => "RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE",
Platform::WindowsX64 => "RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE",
Platform::WindowsGnuX64 => {
// The shared device gateway and both management APIs must select the same
// official trust. A legacy development key is usable only in isolated dev.
let official = "RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE";
if let Some(path) = lookup(official)? {
return FsPath::new(&path).is_absolute().then(|| path.into())
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
if lookup("RMM_PROFILE")?.as_deref() != Some("development") {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
"RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE"
}
};
if let Some(path) = lookup(name)? {
if path.is_empty() || !FsPath::new(&path).is_absolute() {
@@ -162,6 +167,9 @@ fn keyring_path_with(
}
// Exact legacy compatibility only when the platform-specific slot is
// absent. An invalid explicit slot must never silently choose other trust.
if matches!(platform, Platform::LinuxArm64 | Platform::WindowsGnuX64) {
return Err(fail("AGENT_UPDATE_NOT_CONFIGURED"));
}
lookup("RMM_AGENT_UPDATE_KEYRING_FILE")?
.map(Into::into)
.ok_or_else(|| fail("AGENT_UPDATE_NOT_CONFIGURED"))
@@ -170,31 +178,20 @@ pub fn verify_envelope(
envelope: &ReleaseEnvelope,
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
) -> Result<ReleaseManifest, Error> {
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
if platform == Platform::WindowsGnuX64
&& std::env::var("RMM_PROFILE").as_deref() != Ok("development")
{
return Err(fail("AGENT_UPDATE_DEVELOPMENT_CHANNEL_REQUIRED"));
}
verify_signed_envelope(envelope, platform, binding)
verify_envelope_at(envelope, binding, Utc::now())
}
// The public management process can copy an operator-selected release into an empty
// catalog. Network-supplied publications additionally go through the profile check above.
fn verify_signed_envelope(
fn verify_envelope_at(
envelope: &ReleaseEnvelope,
platform: Platform,
binding: Option<&rmm_domain::agent_update::UpdaterBinding>,
time: DateTime<Utc>,
) -> Result<ReleaseManifest, Error> {
let platform = envelope.decode().map_err(|_| invalid())?.manifest.platform;
let raw = keyring_bytes(platform)?;
verify_envelope_with_keyring(
envelope,
binding,
&raw,
chrono::Utc::now()
.timestamp()
.try_into()
.map_err(|_| invalid())?,
time.timestamp().try_into().map_err(|_| invalid())?,
)
}
fn keyring_bytes(platform: Platform) -> Result<Vec<u8>, Error> {
@@ -232,7 +229,7 @@ fn verify_envelope_with_keyring(
rmm_updater::TrustedUpdateKey::new(
raw.try_into()
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?,
verifier_platform(key.platform),
key.platform.into(),
key.first_sequence,
key.last_sequence,
key.revoked,
@@ -243,7 +240,7 @@ fn verify_envelope_with_keyring(
let keyring = rmm_updater::UpdateKeyring::new(config.generation, keys)
.map_err(|_| fail("AGENT_UPDATE_TRUST_INVALID"))?;
let context = rmm_updater::TrustedContext {
platform: verifier_platform(decoded.manifest.platform),
platform: decoded.manifest.platform.into(),
now_utc_seconds,
keyring_generation: config.generation,
protocol_major: 1,
@@ -268,6 +265,12 @@ fn verify_envelope_with_keyring(
}
Ok(decoded.manifest)
}
pub(crate) async fn ensure_customer_starters(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
) -> Result<(), Error> {
bootstrap::publish_starters(tx, tenant).await
}
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
router
.route(
@@ -418,15 +421,53 @@ pub async fn upload(
json!({"artifact_id":input.artifact_id,"sha256":input.sha256,"size_bytes":input.size_bytes}),
))
}
enum CatalogReleaseCheck {
Current,
InstalledHelper,
}
impl CatalogReleaseCheck {
fn verification_time(
self,
registered: DateTime<Utc>,
now: DateTime<Utc>,
) -> Result<DateTime<Utc>, Error> {
match self {
Self::Current => Ok(now),
Self::InstalledHelper if registered <= now => Ok(registered),
Self::InstalledHelper => Err(invalid()),
}
}
}
pub async fn checked_release(
tx: &mut Transaction<'_, Postgres>,
id: Uuid,
) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> {
let row = sqlx::query("SELECT envelope,envelope_sha256,manifest_sha256 FROM agent_update_releases WHERE release_id=$1")
checked_catalog_release(tx, id, CatalogReleaseCheck::Current).await
}
/// Used only to attest an enrolled, running helper against its registered release.
/// The immutable catalog timestamp proves that the release was valid when registered.
pub(crate) async fn checked_installed_helper_release(
tx: &mut Transaction<'_, Postgres>,
id: Uuid,
) -> Result<ReleaseManifest, Error> {
let (_, manifest) = checked_catalog_release(tx, id, CatalogReleaseCheck::InstalledHelper).await?;
Ok(manifest)
}
async fn checked_catalog_release(
tx: &mut Transaction<'_, Postgres>,
id: Uuid,
check: CatalogReleaseCheck,
) -> Result<(ReleaseEnvelope, ReleaseManifest), Error> {
let row = sqlx::query("SELECT envelope,envelope_sha256,manifest_sha256,created_at FROM agent_update_releases WHERE release_id=$1")
.bind(id).fetch_optional(&mut **tx).await?.ok_or_else(missing)?;
let raw: Vec<u8> = row.get("envelope");
let envelope: ReleaseEnvelope = serde_json::from_slice(&raw)?;
let manifest = verify_envelope(&envelope, None)?;
let time = check.verification_time(row.get("created_at"), Utc::now())?;
let manifest = verify_envelope_at(&envelope, None, time)?;
if encode(&envelope)? != raw
|| hash(&raw) != row.get::<String, _>("envelope_sha256")
|| hash(&envelope.decode().map_err(|_| invalid())?.payload_bytes)
@@ -567,7 +608,7 @@ async fn list(
pub struct Current {
platform: Platform,
}
async fn device(
pub(crate) async fn device(
s: &crate::State,
peer: crate::Peer,
headers: &HeaderMap,
@@ -586,11 +627,14 @@ async fn installed(
) -> Result<Response, Error> {
let (tenant, agent) = device(&s, peer, &headers).await?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let row = sqlx::query("SELECT reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
let row = sqlx::query("SELECT asset_id,enrollment_generation,assignment_version,capabilities,reported_agent_version,connection_generation,last_contact_at FROM agent_installations WHERE agent_id=$1 AND revoked_at IS NULL").bind(agent).fetch_one(&mut *tx).await?;
tx.commit().await?;
Ok((
[("cache-control", "private, no-store")],
Json(json!({"agent_id":agent,
Json(json!({"tenant_id":tenant,"asset_id":row.get::<Uuid,_>("asset_id"),"agent_id":agent,
"enrollment_generation":row.get::<i64,_>("enrollment_generation"),
"assignment_version":row.get::<i64,_>("assignment_version"),
"capabilities":row.get::<Value,_>("capabilities"),
"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
"connection_generation":row.get::<i64,_>("connection_generation"),
"last_contact_at":row.get::<Option<chrono::DateTime<chrono::Utc>>,_>("last_contact_at")})),
@@ -610,18 +654,21 @@ async fn check_device_platform(
.fetch_one(&mut **tx)
.await?;
let caps: Vec<String> = serde_json::from_value(caps)?;
let expected = match platform {
Platform::LinuxX64 => "linux.base/1",
Platform::WindowsX64 if caps.iter().any(|c| c == "agent.release.windows.gnu/1") => {
return Err(missing());
}
Platform::WindowsX64 => "windows.base/1",
Platform::WindowsGnuX64 => "agent.release.windows.gnu/1",
};
if !caps.iter().any(|c| c == expected) {
return Err(missing());
if device_supports_release(platform, &caps) {
Ok(())
} else {
Err(missing())
}
}
fn device_supports_release(platform: Platform, caps: &[String]) -> bool {
let has = |expected: &str| caps.iter().any(|capability| capability == expected);
match platform {
Platform::LinuxX64 => has("linux.base/1") && !has(LINUX_ARM64_RELEASE_CAPABILITY),
Platform::LinuxArm64 => has("linux.base/1") && has(LINUX_ARM64_RELEASE_CAPABILITY),
Platform::WindowsX64 => has("windows.base/1") && !has("agent.release.windows.gnu/1"),
Platform::WindowsGnuX64 => has("agent.release.windows.gnu/1"),
}
Ok(())
}
/// A published release grants access to its two fixed binaries for authenticated
@@ -736,7 +783,7 @@ async fn download(
return Err(invalid());
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL")
let row=sqlx::query("SELECT j.payload,p.payload AS plan_payload,p.plan_hash,z.principal AS approver,r.principal AS submitter,i.asset_id,i.enrollment_generation,i.assignment_version FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations z ON z.tenant_id=o.tenant_id AND z.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.job_id=$2 AND j.attempt_id=$3 AND j.state IN ('queued','accepted','running','verifying') AND r.approval_state='approved' AND z.revoked_at IS NULL AND p.expires_at>now() AND i.revoked_at IS NULL")
.bind(agent).bind(q.job_id).bind(q.attempt_id).fetch_optional(&mut *tx).await?.ok_or_else(missing)?;
let job: rmm_domain::jobs::JobPayload =
serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
@@ -749,8 +796,7 @@ async fn download(
let rmm_domain::jobs::Action::UpdateAgent { update } = &job.action else {
return Err(missing());
};
crate::root_policy::authorize(&mut tx, &plan.principal, &job).await?;
crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &job).await?;
crate::jobs::authorize_approved_job(&s, &mut tx, tenant, &plan, &job, &row).await?;
check_update(&mut tx, update).await?;
if job.tenant_id != tenant
|| job.agent_id != agent
@@ -1076,6 +1122,21 @@ mod tests {
FsPath::new("legacy-relative.json")
);
}
let dev_only = BTreeMap::from([
("RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE", "/trust/dev.json"),
("RMM_AGENT_UPDATE_KEYRING_FILE", "/trust/legacy.json"),
]);
assert!(choose(Platform::WindowsGnuX64, &dev_only).is_err());
let mut mixed = dev_only;
mixed.insert("RMM_PROFILE", "development");
assert_eq!(choose(Platform::WindowsGnuX64, &mixed).unwrap(), FsPath::new("/trust/dev.json"));
mixed.insert("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE", "/trust/official.json");
for profile in ["development", "production"] {
mixed.insert("RMM_PROFILE", profile);
assert_eq!(choose(Platform::WindowsGnuX64, &mixed).unwrap(), FsPath::new("/trust/official.json"));
}
mixed.insert("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE", "");
assert!(choose(Platform::WindowsGnuX64, &mixed).is_err());
let only_linux =
BTreeMap::from([("RMM_AGENT_UPDATE_LINUX_KEYRING_FILE", "/trust/linux.json")]);
assert!(choose(Platform::WindowsX64, &only_linux).is_err());
@@ -1156,6 +1217,49 @@ mod tests {
};
(envelope, keys)
};
let (official, official_keys) = make(Platform::WindowsGnuX64);
let (development, _) = make(Platform::WindowsGnuX64);
let official_ring = encode(&official_keys).unwrap();
assert!(verify_envelope_with_keyring(&official, None, &official_ring, 100).is_ok());
assert!(verify_envelope_with_keyring(&development, None, &official_ring, 100).is_err());
// At the expiry boundary, installed helpers still use the immutable
// registration time. Bootstrap and update checks use the current time.
let registered = DateTime::from_timestamp(100, 0).unwrap();
let now = DateTime::from_timestamp(200, 0).unwrap();
let check_catalog = |check: CatalogReleaseCheck,
registered: DateTime<Utc>,
envelope: &ReleaseEnvelope,
keyring: &[u8]| {
let at = check.verification_time(registered, now)?.timestamp() as u64;
verify_envelope_with_keyring(envelope, None, keyring, at)
};
let installed = CatalogReleaseCheck::InstalledHelper;
assert!(check_catalog(installed, registered, &official, &official_ring).is_ok());
assert!(
check_catalog(CatalogReleaseCheck::Current, registered, &official, &official_ring)
.is_err()
);
assert!(check_catalog(CatalogReleaseCheck::InstalledHelper, now, &official, &official_ring).is_err());
assert!(
CatalogReleaseCheck::InstalledHelper
.verification_time(now + chrono::Duration::seconds(1), now)
.is_err()
);
assert!(
check_catalog(CatalogReleaseCheck::InstalledHelper, registered, &development, &official_ring)
.is_err()
);
let mut revoked_official = official_keys;
revoked_official.keys[0].revoked = true;
assert!(
check_catalog(
CatalogReleaseCheck::InstalledHelper,
registered,
&official,
&encode(&revoked_official).unwrap()
)
.is_err()
);
let (linux, linux_keys) = make(Platform::LinuxX64);
let (windows, windows_keys) = make(Platform::WindowsX64);
let linux_raw = encode(&linux_keys).unwrap();
@@ -1235,19 +1339,17 @@ mod tests {
}
}
#[test]
fn plan_request_accepts_release_id_but_never_user_supplied_local_bindings() {
fn update_releases_are_not_device_job_plans() {
let mut value = json!({"tenant_id":"11111111-1111-4111-8111-111111111111","action":"update_agent","targets":{"asset_ids":["11111111-1111-4111-8111-111111111112"]},
"parameters":{"release_id":"11111111-1111-4111-8111-111111111113","execution_identity":"root","timeout_seconds":600,"max_output_bytes":65536},
"schedule":{"not_before":"2030-01-01T12:00:00Z","start_before":"2030-01-01T12:10:00Z","offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"codec only"});
let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap();
assert!(matches!(parsed, crate::jobs::PlanRequest::AgentUpdate(_)));
// The old synchronous resolver cannot manufacture local state.
assert!(
parsed
.resolve(Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap())
.is_err()
);
value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
assert!(serde_json::from_value::<crate::jobs::PlanRequest>(value).is_err());
let tenant = Uuid::parse_str(value["tenant_id"].as_str().unwrap()).unwrap();
for local_binding in [false, true] {
if local_binding {
value["parameters"]["predecessor"] = json!({"installed_record_sha256":"00".repeat(32)});
}
let parsed: crate::jobs::PlanRequest = serde_json::from_value(value.clone()).unwrap();
assert_eq!(parsed.resolve(tenant).err().unwrap().1, "SCRIPT_ACTION_REQUIRED");
}
}
}
+1
View File
@@ -66,6 +66,7 @@ pub(super) async fn summaries(
"plan_hash":row.get::<String,_>("plan_hash"), "requester":row.get::<String,_>("requester"),
"targets":row.get::<Value,_>("targets"), "created_at":row.get::<DateTime<Utc>,_>("created_at"),
"expires_at":row.get::<DateTime<Utc>,_>("expires_at"), "approval_state":row.get::<Option<String>,_>("approval_state"),
"decision":row.get::<Option<Value>,_>("decision"),
}));
}
Ok(items)
+26
View File
@@ -71,6 +71,13 @@ async fn inbox_count_cursor_history_and_customer_permissions() {
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,created_at,approval_state)
VALUES($1,$2,$3,'mcp:fixture',$4,'fixture',$5,$6)")
.bind(tenant).bind(op_id).bind(plan_id).bind(plan_id.to_string()).bind(stamp).bind(status).execute(&admin).await.unwrap();
if status == "rejected" {
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'plan_authorization',$4,$5)")
.bind(tenant).bind(Uuid::new_v4()).bind(format!("reviewer:{tenant}"))
.bind(json!({"operation_id":op_id,"plan_id":plan_id,"plan_hash":"fixture",
"decision":"reject","testsimulation":true}))
.bind(stamp + chrono::Duration::seconds(5)).execute(&admin).await.unwrap();
}
}
}
@@ -173,6 +180,25 @@ async fn inbox_count_cursor_history_and_customer_permissions() {
.collect();
assert_eq!(states.len(), 2);
assert!(states.contains(&"expired") && states.contains(&"rejected"));
let items = history["items"].as_array().unwrap();
let rejected = items.iter().find(|item| item["approval_state"] == "rejected").unwrap();
assert_eq!(rejected["decision"]["principal"], format!("reviewer:{a}"));
assert_eq!(rejected["decision"]["testsimulation"], true);
let at: DateTime<Utc> = serde_json::from_value(rejected["decision"]["at"].clone()).unwrap();
assert_eq!(at.timestamp_micros(), (stamp + chrono::Duration::seconds(5)).timestamp_micros());
assert!(items.iter().find(|item| item["approval_state"] == "expired").unwrap()["decision"].is_null());
// Filter the authorized storage rows before applying the page limit.
for (tenant, disclose_names, matches) in [(a, true, 1), (b, false, 0)] {
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await.unwrap();
let rows: Vec<(Uuid, DateTime<Utc>)> = sqlx::query_as(include_str!("../order_filter.sql"))
.bind(Utc::now()).bind(None::<DateTime<Utc>>).bind(Uuid::nil())
.bind(stamp - chrono::Duration::seconds(1)).bind(stamp + chrono::Duration::seconds(1))
.bind("kernel").bind("rejected").bind("Kunde").bind(None::<Uuid>).bind(disclose_names)
.bind(1_i64).fetch_all(&mut *tx).await.unwrap();
assert_eq!(rows.len(), matches);
tx.commit().await.unwrap();
}
let count = list(
&state,
&p,
+190 -6
View File
@@ -4,8 +4,9 @@
param(
[Parameter(Mandatory)][Uri]$BootstrapBase,
[Security.SecureString]$EnrollmentToken,
[switch]$EnableAdministratorScripts,
[ValidateSet('x86_64-pc-windows-msvc','x86_64-pc-windows-gnu')]
[string]$Platform = 'x86_64-pc-windows-msvc'
[string]$Platform = 'x86_64-pc-windows-gnu'
)
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
@@ -66,8 +67,191 @@ function Set-Text([string]$Path, [string]$Value) {
function Get-Hash([string]$Path) {
return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
# The network process stays LocalService. Only the pinned local helper consumes
# SYSTEM grants. Its private ledger persists across restarts and signed updates.
function Assert-AdminPath([string]$Path, [string]$StopAt) {
$item = Get-Item -LiteralPath $Path -Force
while ($item) {
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Unexpected reparse point: $($item.FullName)" }
$acl = Get-Acl -LiteralPath $item.FullName
if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -notin @($administrators.Value,$system.Value)) {
throw "Administrator-owned path required: $($item.FullName)"
}
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrators.Value,$system.Value) -and
([int64]$rule.FileSystemRights -band 0x500d0156)) { throw "Writable installation path: $($item.FullName)" }
}
if ($item.FullName -ieq $StopAt) { return }
$item = if ($item -is [IO.FileInfo]) { $item.Directory } else { $item.Parent }
}
throw 'Path outside the expected installation directory.'
}
function Publish-HelperText([string]$Path, [string]$Text) {
$pending = $Path + '.' + [Guid]::NewGuid()
try {
$f = [IO.File]::Open($pending, 'CreateNew')
try {
$bytes = $utf8.GetBytes($Text)
$f.Write($bytes, 0, $bytes.Length)
$f.Flush($true)
} finally { $f.Dispose() }
$acl = Get-Acl -LiteralPath $pending
$acl.SetOwner($administrators)
Set-Acl -LiteralPath $pending -AclObject $acl
[IO.File]::Move($pending, $Path)
} finally { if (Test-Path -LiteralPath $pending) { Remove-Item -LiteralPath $pending } }
}
function Install-ScriptHelper {
# Enrollment and ordinary updates cannot grant SYSTEM execution. This switch
# is a local administrator's choice for this particular installation.
if (!$EnableAdministratorScripts) { return }
$cfg = Join-Path $data 'config.json'
Assert-AdminPath $cfg $data
$guardPath = Join-Path $data 'release-job.lock'
Assert-AdminPath $guardPath $data
$gate = [IO.File]::Open($guardPath,'Open','ReadWrite','None')
try {
$config = [IO.File]::ReadAllText($cfg) | ConvertFrom-Json
if (!$config.PSObject.Properties['enable_jobs'] -or !$config.enable_jobs) { throw 'Local script execution is disabled.' }
$timePath = Join-Path $data 'job-time.json'
if ($config.localservice_time_policy -ine $timePath) { throw 'Expected the enrolled LocalService time policy.' }
if (($config.PSObject.Properties['windows_echo_probe_only'] -and $config.windows_echo_probe_only) -or
($config.PSObject.Properties['windows_update_helper'] -and $config.windows_update_helper)) {
throw 'The existing restricted execution profile must finish and be closed before provisioning.'
}
$alreadyConfigured = $config.PSObject.Properties['managed_script_helper'] -and $config.managed_script_helper
$records = Join-Path $data 'release-state'
if ((Test-Path (Join-Path $records 'release-transition.json')) -or (Test-Path (Join-Path $data 'release-transition.json'))) {
throw 'Agent update in progress. Retry the installer once it completes.'
}
$record = Join-Path $records 'installed-release.json'
if (!(Test-Path -LiteralPath $record)) { $record = Join-Path $data 'installed-release.json' }
Assert-AdminPath $record $data
$installed = [IO.File]::ReadAllText($record) | ConvertFrom-Json
$release = Get-Id $installed.release_id
$images = Join-Path $app ('releases\' + $release)
$agentExe = Join-Path $images 'rmm-agent-windows.exe'
$helperExe = Join-Path $images 'rmm-helper-windows.exe'
$worker = Join-Path $app 'rmm-updater-windows.exe'
$envelope = Join-Path $images 'envelope.json'
$ring = Join-Path $data 'release-keyring.json'
foreach ($path in @($agentExe,$helperExe,$worker,$envelope)) { Assert-AdminPath $path $app }
foreach ($path in @($ring,$timePath)) { Assert-AdminPath $path $data }
$service = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
$pull = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryReleasePull'"
if (!$service -or $service.StartName -ine 'NT AUTHORITY\LocalService' -or
$service.PathName -cne ('"' + $agentExe + '" --service --config "' + $cfg + '"') -or
!$pull -or $pull.StartName -ine 'LocalSystem' -or $pull.PathName -cne ('"' + $worker + '" --release-service')) {
throw 'Service registrations do not match the installed release.'
}
$verified = & $worker --verify-bootstrap $ring $envelope $agentExe $helperExe
if ($LASTEXITCODE -ne 0 -or ($verified | ConvertFrom-Json).release_id -cne $release) { throw 'Installed code pair failed signature verification.' }
foreach ($binary in @($worker,$helperExe)) {
$supported = & $binary --managed-script-helper-version
if ($LASTEXITCODE -ne 0 -or $supported -cne 'managed-script-helper/1') { throw 'Update the agent pair and stable updater before enabling administrator scripts.' }
}
$preservesPolicy = & $worker --managed-script-policy-version
if ($LASTEXITCODE -ne 0 -or $preservesPolicy -cne 'release-preserves-script-policy/1') {
throw 'Administrator scripts require the stable updater that preserves the local policy during release switches and rollbacks.'
}
$id = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$policy = [IO.File]::ReadAllText($timePath) | ConvertFrom-Json
if ($policy.tenant_id -cne $installed.tenant_id -or $policy.job_signing_public_key_hex -cnotmatch '^[0-9a-f]{64}$') {
throw 'Enrolled job trust and installed release belong to different configurations.'
}
$binding = [ordered]@{tenant_id=(Get-Id $policy.tenant_id);agent_id=(Get-Id $id.agent_id);asset_id=(Get-Id $id.asset_id)
enrollment_generation=1;assignment_version=1;public_key_hex=$policy.job_signing_public_key_hex}
$helperName = 'RmmDiscoverySystemHelper'
$helperCommand = '"' + $helperExe + '" --service'
$agentSid = [Security.Principal.NTAccount]::new('NT SERVICE',$serviceName).Translate([Security.Principal.SecurityIdentifier])
$root = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscoverySystem'
$stamp = Join-Path $root 'script-helper-enrollment.json'
$owner = [ordered]@{agent_id=$binding.agent_id;asset_id=$binding.asset_id;tenant_id=$binding.tenant_id} | ConvertTo-Json -Compress
$helper = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoverySystemHelper'"
if ($helper -and !$alreadyConfigured -and !(Test-Path -LiteralPath $stamp)) {
throw 'Existing local helper registration must be reconciled before provisioning.'
}
if (!(Test-Path -LiteralPath $root)) {
$stage = Join-Path $data ('script-helper-' + [Guid]::NewGuid())
[void][IO.Directory]::CreateDirectory($stage,(Get-DirectoryAcl $agentSid 'ReadAndExecute'))
try {
Publish-HelperText (Join-Path $stage 'script-helper-enrollment.json') $owner
[IO.Directory]::Move($stage,$root)
} finally { if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } }
}
Assert-AdminPath $root $root
if (Test-Path -LiteralPath $stamp) {
Assert-AdminPath $stamp $root
if ([IO.File]::ReadAllText($stamp) -cne $owner) { throw 'Local helper belongs to another enrollment.' }
} elseif (!$alreadyConfigured) { throw 'Existing helper state must be reconciled before migration.' }
if ($helper -and ($helper.StartName -ine 'LocalSystem' -or $helper.PathName -cne $helperCommand)) { throw 'Unexpected local helper registration.' }
if (!$helper) { New-Service -Name $helperName -BinaryPathName $helperCommand -StartupType Manual | Out-Null }
& (Join-Path $env:SystemRoot 'System32\sc.exe') sidtype $helperName unrestricted | Out-Null
if ($LASTEXITCODE -ne 0) { throw 'Could not set the local helper service SID.' }
$inputDto = [ordered]@{binding=$binding;release_id=$release;agent_sha256=(Get-Hash $agentExe)
helper_sha256=(Get-Hash $helperExe);max_runtime_seconds=3600;managed_scripts=$true}
$rendered = ($inputDto | ConvertTo-Json -Depth 6 -Compress) | & $helperExe --prepare-enrolled-windows-update
if ($LASTEXITCODE -ne 0) { throw 'Helper could not bind the signed code pair to the enrollment.' }
$pins = $rendered | ConvertFrom-Json
foreach ($kv in @(@('helper.json',$pins.helper_settings),@('agent-pin.json',$pins.agent_pin))) {
$path = Join-Path $root $kv[0]
if (Test-Path -LiteralPath $path) {
Assert-AdminPath $path $root
if ([IO.File]::ReadAllText($path) -cne $kv[1]) { throw 'An existing helper pin differs from this release or enrollment.' }
} else { Publish-HelperText $path $kv[1] }
}
$private = Join-Path $root 'state'
if (!(Test-Path -LiteralPath $private)) { [void][IO.Directory]::CreateDirectory($private,(Get-DirectoryAcl $null '')) }
Assert-AdminPath $private $root
$intents = Join-Path $root 'agent-intents'
if (!(Test-Path -LiteralPath $intents)) { [void][IO.Directory]::CreateDirectory($intents,(Get-DirectoryAcl $agentSid 'ReadAndExecute')) }
Assert-AdminPath $intents $root
foreach ($leaf in @('system-intents.sqlite','system-intents.sqlite-journal')) {
$path = Join-Path $intents $leaf
if (!(Test-Path -LiteralPath $path)) { [IO.File]::Open($path,'CreateNew').Dispose() }
if ((Get-Item -Force -LiteralPath $path).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Unexpected link in intent journal.' }
if (!$alreadyConfigured) {
$acl = [Security.AccessControl.FileSecurity]::new()
$acl.SetOwner($administrators)
$acl.SetAccessRuleProtection($true,$false)
foreach ($sid in @($system,$administrators)) { $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow')) }
$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($agentSid,[Security.AccessControl.FileSystemRights]0x12019f,'Allow'))
Set-Acl -LiteralPath $path -AclObject $acl
}
}
if (!$alreadyConfigured) {
Stop-Service $serviceName
$temp = $cfg + '.' + [Guid]::NewGuid()
try {
$config | Add-Member -NotePropertyName managed_script_helper -NotePropertyValue $true -Force
Set-Text $temp ($config | ConvertTo-Json -Depth 12 -Compress)
[IO.File]::Replace($temp,$cfg,[NullString]::Value)
} catch {
Start-Service $serviceName
throw
} finally {
if (Test-Path -LiteralPath $temp) { Remove-Item -LiteralPath $temp }
}
}
try {
Set-Service $helperName -StartupType Automatic
Start-Service $helperName
} finally { Start-Service $serviceName }
} finally { $gate.Dispose() }
}
function Start-ReleaseAfterFirstContact {
$receipt = Join-Path $state 'job-readiness.json'
# A previous installer can have stopped the enrolled agent just before
# committing its helper configuration. Resume the same local enrollment.
if ((Get-Service $serviceName).Status -eq 'Stopped') {
$agent = Get-CimInstance Win32_Service -Filter "Name='RmmDiscoveryWindows'"
if ($agent.StartName -ine 'NT AUTHORITY\LocalService') { throw 'Unexpected enrolled agent identity.' }
Start-Service $serviceName
}
$until = [DateTime]::UtcNow.AddSeconds(120)
while ([DateTime]::UtcNow -lt $until) {
if ((Get-Service $serviceName).Status -ne 'Running') { throw 'Agent stopped before first gateway contact. Inspect the installed service.' }
@@ -76,7 +260,7 @@ function Start-ReleaseAfterFirstContact {
$enrolled = [IO.File]::ReadAllText($identity) | ConvertFrom-Json
$hello = [IO.File]::ReadAllText($receipt) | ConvertFrom-Json
if ($hello.agent_id -ceq $enrolled.agent_id -and $hello.connection_generation -ge 1) {
Start-Service $releaseService
try { Install-ScriptHelper } finally { Start-Service $releaseService }
Remove-Item -LiteralPath $firstContact -Force
return
}
@@ -85,6 +269,9 @@ function Start-ReleaseAfterFirstContact {
}
throw 'First authenticated version report is pending. Rerun the installer to finish with this identity.'
}
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$origin = Get-Origin $BootstrapBase
$app = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'RustDiscovery'
$data = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'RustDiscovery'
@@ -95,7 +282,7 @@ $serviceName = 'RmmDiscoveryWindows'
$releaseService = 'RmmDiscoveryReleasePull'
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and (Test-Path -LiteralPath $identity -PathType Leaf)) {
if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact }
if (Test-Path -LiteralPath $firstContact -PathType Leaf) { Start-ReleaseAfterFirstContact } else { Install-ScriptHelper }
Write-Output "Rust Discovery is already enrolled. Agent service: $($service.Status)."
return
}
@@ -108,9 +295,6 @@ try { $token = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
if ($token -cnotmatch '^[0-9a-f]{64}$') { throw 'Invalid one-time enrollment token.' }
$query = '?platform=' + $platform
$utf8 = New-Object Text.UTF8Encoding($false)
$administrators = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$stage = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) ('RustDiscovery-install-' + [Guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($stage, (Get-DirectoryAcl $null ''))
$madeApp = $false
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# Usage: sudo sh linux.sh https://bootstrap.example
# Linux x86-64 / ARM64. Usage: sudo sh linux.sh https://bootstrap.example [--enable-admin-scripts]
set -eu
umask 077
file=$(mktemp)
+318 -18
View File
@@ -1,9 +1,11 @@
"""Bootstrap a Linux systemd client and maintain its signed release pair."""
import argparse
import contextlib
import datetime
import fcntl
import getpass
import hashlib
import io
import json
import os
from pathlib import Path
@@ -14,6 +16,7 @@ import shutil
import socket
import sqlite3
import ssl
import stat
import subprocess
import sys
import tempfile
@@ -26,7 +29,9 @@ ROOT = Path('/opt/rust-discovery-client')
STATE = Path('/var/lib/rmm-discovery')
SERVICE = 'rmm-discovery-agent.service'
TIMER = 'rmm-discovery-update.timer'
PLATFORM = 'x86_64-unknown-linux-gnu'
HELPER = 'rmm-discovery-managed-script-helper.service'
HELPER_SOCKET = Path('/run/rmm-discovery-script-helper/control.sock')
OLD_HELPER_CONFIG = Path('/etc/rmm-discovery-managed-scripts')
MAX_BINARY = 256 * 1024 * 1024
UNIT_DIR = Path('/etc/systemd/system')
@@ -36,6 +41,13 @@ def require(condition, message):
raise ValueError(message)
def release_platform():
machine = platform.machine()
require(platform.system() == 'Linux' and machine in ('x86_64', 'aarch64'),
'Linux x86-64 or ARM64 required')
return machine + '-unknown-linux-gnu'
def origin(value):
parsed = urlsplit(value)
require(parsed.scheme == 'https' and parsed.hostname and parsed.username is None
@@ -145,7 +157,9 @@ def pair(folder, doc, source, updater):
manifest = doc['manifest']
release_id = canonical_id(manifest['release_id'])
prefix = '/agent/v1/bootstrap/releases' if source else '/agent/v1/releases'
suffix = '?platform=' + PLATFORM if source else ''
target = release_platform()
require(manifest['platform'] == target, 'release architecture differs from this device')
suffix = '?platform=' + target if source else ''
save(folder / 'envelope.json', doc['release_envelope'])
for artifact, role in zip(manifest['artifacts'], ('agent', 'helper'), strict=True):
require(artifact['role'] == role, 'incorrect artifact role')
@@ -177,10 +191,15 @@ def installed():
return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout)
def healthy(version, baseline, duration=90):
def healthy(version, baseline, duration=90, pin=None):
until = time.monotonic() + duration
started = time.time()
certificate_pointer = STATE / 'certificates/current.json'
while time.monotonic() < until:
# The agent writes this pointer after obtaining its first device certificate.
if not certificate_pointer.is_file():
time.sleep(2)
continue
try:
record = installed()
contact = record.get('last_contact_at')
@@ -188,6 +207,8 @@ def healthy(version, baseline, duration=90):
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline
and (pin is None or {'root:run_script', 'helper.policy.sha256:' + pin['policy_sha256'],
'helper.binary.sha256:' + pin['helper_binary_sha256']}.issubset(record['capabilities']))
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
return True
except (subprocess.SubprocessError, ValueError, OSError):
@@ -200,6 +221,212 @@ def service(*args):
subprocess.run(['systemctl', *args], check=True, timeout=60)
def active_folder():
release = canonical_id(read(ROOT / 'current/manifest.json')['release_id'])
folder = ROOT / 'releases' / release
require((ROOT / 'current').resolve(strict=True) == folder and folder.resolve() == folder,
'unexpected active generation path')
return folder
@contextlib.contextmanager
def account_file(path, uid):
# Open only a checked inode a second time for TLS. No privileged open of a
# device or FIFO, and no path re-resolution after validation.
fd = os.open(path, os.O_PATH | os.O_NOFOLLOW)
try:
info = os.fstat(fd)
require(stat.S_ISREG(info.st_mode) and info.st_uid == uid and info.st_nlink == 1
and info.st_mode & 0o077 == 0 and 0 < info.st_size <= 65536,
'device credential metadata differs')
yield Path('/proc/self/fd') / str(fd)
finally:
os.close(fd)
def script_binding(account):
# The root helper trusts only the signing key from the original HTTPS
# bootstrap and the binding returned by the authenticated device gateway.
boot = read(ROOT / 'bootstrap.json')
certs = STATE / 'certificates'
with account_file(certs / 'current.json', account.pw_uid) as selector:
version = canonical_id(read(selector)['version'])
creds = certs / 'versions' / version
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.load_verify_locations(cafile=str(ROOT / 'gateway-ca.pem'))
with (account_file(creds / 'device.pem', account.pw_uid) as cert,
account_file(creds / 'device.key', account.pw_uid) as key):
context.load_cert_chain(str(cert), str(key))
response = io.BytesIO()
conf = read(ROOT / 'config.json')
retrieve(conf['gateway'], '/agent/v1/releases/installed', response, context=context)
own = json.loads(response.getvalue())
public_key = boot.get('job_signing_public_key_hex')
if public_key is None:
trust = io.BytesIO()
retrieve(conf['gateway'], '/agent/v1/releases/device-trust', trust, context=context)
public_key = json.loads(trust.getvalue())['job_signing_public_key_hex']
require(re.fullmatch('[0-9a-f]{64}', public_key), 'invalid job signing key')
require(own['tenant_id'] == conf['tenant'] == boot['tenant_id'], 'device binding tenant mismatch')
binding = {field: canonical_id(own[field]) for field in ('tenant_id', 'asset_id', 'agent_id')}
for field in ('enrollment_generation', 'assignment_version'):
require(type(own[field]) is int and own[field] > 0, 'invalid device generation')
binding[field] = own[field]
binding['public_key_hex'] = public_key
return binding
def script_settings(binding, account, digest):
return dict(profile='full_maintenance_v1', binding=binding, agent_uid=account.pw_uid,
socket_gid=account.pw_gid, socket=str(HELPER_SOCKET), state='/var/lib/rmm-discovery-helper',
allowed_services=[], allow_reboot=False, allow_root_scripts=True,
allowed_script_profiles=['full_maintenance_v1'], helper_binary_sha256=digest)
def prepare_script_helper(folder, binding, account):
manifest = json.loads(subprocess.check_output([
ROOT / 'updater', '--verify-bootstrap', ROOT / 'keyring.json', folder / 'envelope.json',
folder / 'agent', folder / 'helper'], timeout=120))
require(manifest == read(folder / 'manifest.json') and manifest['release_id'] == folder.name,
'helper generation differs from signed release')
digest = next(a['sha256'] for a in manifest['artifacts'] if a['role'] == 'helper')
settings = script_settings(binding, account, digest)
config = folder / 'script-helper.json'
if config.exists():
require(read(config) == settings, 'installed helper binding changed')
else:
save(config, settings, 0o600)
raw = subprocess.check_output([folder / 'helper', '--inspect-full-maintenance-profile'],
env={'PATH': '/usr/bin:/bin', 'RMM_HELPER_CONFIG': str(config)}, timeout=30)
pin = json.loads(raw)
require(pin['helper_binary_sha256'] == digest and re.fullmatch('[0-9a-f]{64}', pin['policy_sha256']),
'helper pin differs from signed release')
save(folder / 'script-pin.json', raw)
return pin
def helper_unit(executable, config=None):
command = f'Environment=RMM_HELPER_CONFIG={config}\n' if config else ''
return f"""[Unit]
Description=Rust Discovery helper for approved root scripts
After=time-sync.target
[Service]
User=root
Group=rmm-discovery
StateDirectory=rmm-discovery-helper
StateDirectoryMode=0700
RuntimeDirectory=rmm-discovery-script-helper
RuntimeDirectoryMode=0750
UMask=0077
{command}ExecStart={executable}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
""".encode()
def helper_unit_files(binding, account):
unit = UNIT_DIR / HELPER
dropdir = UNIT_DIR / (SERVICE + '.d')
dropdir.mkdir(mode=0o755, exist_ok=True)
require(not dropdir.is_symlink() and not dropdir.stat().st_mode & 0o022, 'unsafe service drop-in directory')
drop = dropdir / '50-managed-scripts.conf'
order = f'[Unit]\nAfter={HELPER}\n'.encode()
old_order = (f'[Unit]\nWants={HELPER}\nAfter={HELPER}\n'
f'\n[Service]\nEnvironment=RMM_FULL_MAINTENANCE_HELPER_SOCKET={HELPER_SOCKET}\n'
f'Environment=RMM_FULL_MAINTENANCE_POLICY_FILE={OLD_HELPER_CONFIG}/agent-pin.json\n').encode()
changed = []
for path, desired in (
(unit, helper_unit(f'/usr/bin/python3 -I {ROOT}/lifecycle.py run-helper')),
(drop, order),
):
if path.is_symlink():
raise ValueError('unexpected systemd symlink: ' + str(path))
if path.exists():
current = path.read_bytes()
if current == desired:
continue
old = old_order
if path == unit:
exe = re.search(rb'^ExecStart=(.+)$', current, re.M)
require(exe is not None, 'unrecognized helper service')
candidate = Path(os.fsdecode(exe[1]))
require(candidate == ROOT / 'releases' / canonical_id(candidate.parent.name) / 'helper',
'unexpected legacy helper image')
private = OLD_HELPER_CONFIG / 'helper.json'
old = helper_unit(candidate, private)
settings = read(private)
require(settings == script_settings(binding, account, settings['helper_binary_sha256']),
'existing helper belongs to a different binding or profile')
require(current == old, 'unrecognized managed service file: ' + str(path))
changed.append((path, desired))
return changed
def start_pair():
service('start', HELPER)
until = time.monotonic() + 15
while not HELPER_SOCKET.is_socket():
require(time.monotonic() < until, 'script helper socket unavailable')
time.sleep(.2)
service('start', SERVICE)
def helper_state():
probe = subprocess.run(['systemctl', 'is-enabled', HELPER], stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, timeout=10)
return probe.stdout.strip()
def provision_scripts(enable_admin_scripts):
with (ROOT / 'release.lock').open('rb') as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
pending = ROOT / 'pending.json'
if pending.exists():
revert(read(pending))
folder = active_folder()
intent = ROOT / 'script-helper-installing.json'
state = helper_state()
known = (UNIT_DIR / HELPER).exists() or OLD_HELPER_CONFIG.exists() or (folder / 'script-helper.json').exists()
if state != 'enabled':
new = enable_admin_scripts and not known and state in ('', 'not-found')
resume = (enable_admin_scripts and intent.is_file() and read(intent) == folder.name
and state in ('', 'not-found', 'disabled'))
if not (new or resume):
print('Keeping the local script helper activation policy: ' + (state or 'not installed'), file=sys.stderr)
return
else:
require((UNIT_DIR / HELPER).is_file(), 'refusing to replace an externally managed helper unit')
require(as_device('idle', stdout=subprocess.PIPE).stdout.strip() == b'idle', 'active job prevents helper switch')
account = pwd.getpwnam('rmm-discovery')
require(account.pw_uid > 0 and account.pw_gid > 0, 'dedicated service account required')
binding = script_binding(account)
changed = helper_unit_files(binding, account)
if state != 'enabled':
save(intent, folder.name)
pin = prepare_script_helper(folder, binding, account)
observed = installed()
if (not changed and 'root:run_script' in observed['capabilities']
and 'helper.binary.sha256:' + pin['helper_binary_sha256'] in observed['capabilities']
and 'helper.policy.sha256:' + pin['policy_sha256'] in observed['capabilities']):
intent.unlink(missing_ok=True)
return
service('stop', SERVICE)
if (UNIT_DIR / HELPER).exists():
service('stop', HELPER)
for path, raw in changed:
save(path, raw)
service('daemon-reload')
service('enable', HELPER)
start_pair()
require(healthy(read(folder / 'manifest.json')['version'], observed['connection_generation'], pin=pin),
'device has not confirmed the script helper')
intent.unlink(missing_ok=True)
def units():
program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py')
return {
@@ -243,6 +470,30 @@ WantedBy=timers.target
}
def provision_serial_credential():
# DMI serial files usually require root. Pass this one value to the agent
# through systemd's read-only per-service credentials directory.
source = Path('/sys/class/dmi/id/product_serial')
try:
with source.open('rb') as stream:
serial = stream.read(256).strip()
except OSError:
return
if not serial or len(serial) >= 255:
return
target = ROOT / 'bios-serial'
dropin = UNIT_DIR / (SERVICE + '.d') / '40-inventory-serial.conf'
content = f'[Service]\nLoadCredential=rmm-bios-serial:{target}\n'.encode()
require(not dropin.parent.is_symlink(), 'hardware credential directory conflict')
if dropin.exists() or dropin.is_symlink():
require(not dropin.is_symlink() and dropin.read_bytes() == content, 'hardware credential configuration conflict')
else:
dropin.parent.mkdir(mode=0o755, exist_ok=True)
save(target, serial, 0o600)
if not dropin.exists():
save(dropin, content)
def enable():
for name, data in units().items():
path = UNIT_DIR / name
@@ -250,6 +501,7 @@ def enable():
require(path.read_bytes() == data.encode(), 'service file conflict: ' + name)
else:
save(path, data.encode())
provision_serial_credential()
service('daemon-reload')
service('enable', '--now', SERVICE)
@@ -266,8 +518,8 @@ def save_token(base, token, gid):
os.chown(path, 0, gid)
def install(base, token_file):
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
def install(base, token_file, enable_admin_scripts=False):
target = release_platform()
base = origin(base)
if ROOT.exists():
config = read(ROOT / 'config.json')
@@ -277,7 +529,7 @@ def install(base, token_file):
token = enrollment_token(token_file)
with tempfile.TemporaryDirectory() as work:
metadata = Path(work) / 'bootstrap.json'
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, metadata)
remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, metadata)
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
# An operator rerunning the HTTPS installer can update the lifecycle
@@ -288,8 +540,12 @@ def install(base, token_file):
current = Path(__file__).read_bytes()
if harness.read_bytes() != current:
save(harness, current)
pending = ROOT / 'pending.json'
if pending.exists():
revert(read(pending), report_failure=False)
enable()
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
provision_scripts(enable_admin_scripts)
service('enable', '--now', TIMER)
(ROOT / 'first.token').unlink(missing_ok=True)
return
@@ -306,7 +562,7 @@ def install(base, token_file):
with tempfile.TemporaryDirectory(prefix='.rmm-', dir=ROOT.parent) as work:
staging = Path(work) / 'installation'
staging.mkdir()
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, staging / 'bootstrap.json')
remote((base, token), '/agent/v1/bootstrap/current?platform=' + target, staging / 'bootstrap.json')
doc = read(staging / 'bootstrap.json')
require(doc['schema_version'] == 1, 'unknown bootstrap profile')
save(staging / 'keyring.json', doc['keyring'])
@@ -314,7 +570,7 @@ def install(base, token_file):
save(staging / 'config.json', {'bootstrap': base, 'gateway': origin(doc['gateway_origin']),
'tenant': canonical_id(doc['tenant_id'])})
updater = staging / 'updater'
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + PLATFORM + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
remote((base, token), '/agent/v1/bootstrap/updater?platform=' + target + '&sha256=' + doc['updater']['sha256'], updater, doc['updater'])
updater.chmod(0o755)
releases = staging / 'releases'
releases.mkdir()
@@ -330,6 +586,7 @@ def install(base, token_file):
os.rename(staging, ROOT)
enable()
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
provision_scripts(enable_admin_scripts)
# OnBootSec may already be in the past on a running machine. The first
# timer check can run immediately once the device has reported its platform.
service('enable', '--now', TIMER)
@@ -349,20 +606,38 @@ def run_agent():
RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1',
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
exe = str(ROOT / 'current/agent')
folder = active_folder()
os.environ.pop('RMM_SCRIPT_HELPER_RELEASE', None)
if (folder / 'script-pin.json').is_file() and helper_state() in ('enabled', 'enabled-runtime'):
pins = {'RMM_FULL_MAINTENANCE_HELPER_SOCKET': str(HELPER_SOCKET),
'RMM_FULL_MAINTENANCE_POLICY_FILE': str(folder / 'script-pin.json')}
if all(os.environ.get(name, value) == value for name, value in pins.items()):
os.environ.update(pins, RMM_SCRIPT_HELPER_RELEASE=folder.name)
exe = str(folder / 'agent')
os.execv(exe, [exe])
def revert(intent):
def revert(intent, report_failure=True):
# Persist failed sequence before restoring. An interruption re-enters recovery.
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
enabled = intent.get('script_helper') and helper_state() in ('enabled', 'enabled-runtime')
if intent.get('script_helper'):
service('stop', SERVICE, HELPER)
link(ROOT, intent['previous'])
service('restart', SERVICE)
if enabled:
start_pair()
previous = active_folder()
require(healthy(read(previous / 'manifest.json')['version'], 0, pin=read(previous / 'script-pin.json')),
'predecessor has not yet confirmed the previous script helper')
else:
service('restart', SERVICE)
(ROOT / 'pending.json').unlink()
raise RuntimeError('release activation unconfirmed; predecessor selected')
if report_failure:
raise RuntimeError('release activation unconfirmed; predecessor selected')
def update():
target = release_platform()
with (ROOT / 'release.lock').open('rb') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
pending = ROOT / 'pending.json'
@@ -372,7 +647,7 @@ def update():
with tempfile.TemporaryDirectory(prefix='.incoming-', dir=ROOT / 'releases') as work:
staging = Path(work) / 'generation'
staging.mkdir()
remote(None, '/agent/v1/releases/current?platform=' + PLATFORM, staging / 'current.json')
remote(None, '/agent/v1/releases/current?platform=' + target, staging / 'current.json')
response = read(staging / 'current.json')
if response['status'] == 'not_configured':
return
@@ -401,10 +676,28 @@ def update():
(staging / 'current.json').unlink()
os.rename(staging, dest)
intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']}
active_config = active_folder() / 'script-helper.json'
pin = None
if active_config.exists() and helper_state() in ('enabled', 'enabled-runtime'):
settings = read(active_config)
account = pwd.getpwnam('rmm-discovery')
active_hash = next(a['sha256'] for a in active['artifacts'] if a['role'] == 'helper')
require(settings == script_settings(settings['binding'], account, active_hash),
'existing script helper policy changed')
pin = prepare_script_helper(dest, settings['binding'], account)
intent['script_helper'] = True
save(pending, intent)
link(ROOT, release)
service('restart', SERVICE)
if not healthy(manifest['version'], previous_health['connection_generation']):
try:
if pin:
service('stop', SERVICE, HELPER)
link(ROOT, release)
if pin:
start_pair()
else:
service('restart', SERVICE)
except (OSError, ValueError, subprocess.SubprocessError):
revert(intent)
if not healthy(manifest['version'], previous_health['connection_generation'], pin=pin):
revert(intent)
pending.unlink()
(ROOT / 'first.token').unlink(missing_ok=True)
@@ -412,18 +705,25 @@ def update():
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'fetch', 'idle'))
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'run-helper', 'fetch', 'idle'))
parser.add_argument('values', nargs='*')
parser.add_argument('--token-file')
parser.add_argument('--enable-admin-scripts', action='store_true',
help='enable this enrolled device to run individually approved root scripts')
args = parser.parse_args()
if args.action in ('install', 'update'):
require(os.geteuid() == 0, 'administrative installation required')
os.umask(0o022)
if args.action == 'install':
require(len(args.values) == 1, 'one HTTPS bootstrap origin required')
install(args.values[0], args.token_file)
install(args.values[0], args.token_file, args.enable_admin_scripts)
elif args.action == 'update':
update()
elif args.action == 'run-helper':
require(os.geteuid() == 0, 'privileged script helper service required')
folder = active_folder()
os.environ.setdefault('RMM_HELPER_CONFIG', str(folder / 'script-helper.json'))
os.execv(folder / 'helper', [str(folder / 'helper')])
elif args.action == 'run-agent':
run_agent()
elif args.action == 'fetch':
+10 -2
View File
@@ -3,6 +3,8 @@
use super::*;
mod starter;
pub(super) use starter::publish_missing as publish_starters;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Config {
@@ -23,9 +25,15 @@ struct TenantPins { current: Pin, previous: Vec<Previous> }
#[serde(deny_unknown_fields)]
pub(super) struct UpdaterQuery { platform: Platform, sha256: Option<String> }
fn official_windows(platform: Platform) -> bool {
platform == Platform::WindowsGnuX64
&& std::env::var_os("RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE").is_some()
}
async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Option<&str>) -> Result<Config, Error> {
let slot = match platform {
Platform::LinuxX64 => "RMM_AGENT_BOOTSTRAP_LINUX_FILE",
Platform::LinuxArm64 => "RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE",
Platform::WindowsX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_FILE",
Platform::WindowsGnuX64 => "RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE",
};
@@ -45,8 +53,8 @@ async fn config(s: &crate::State, platform: Platform, tenant: Uuid, wanted: Opti
config.updater_bytes = selected.bytes;
} else {
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let pin = sqlx::query("SELECT sha256,size_bytes FROM customer_starter_workers WHERE platform=$1")
.bind(platform_name(platform)).fetch_optional(&mut *tx).await?;
let pin = sqlx::query("SELECT sha256,size_bytes FROM customer_starter_workers WHERE platform=$1 AND official_windows=$2")
.bind(platform_name(platform)).bind(official_windows(platform)).fetch_optional(&mut *tx).await?;
tx.commit().await?;
if let Some(pin) = pin {
config.updater_sha256 = pin.get("sha256");
+13 -5
View File
@@ -10,11 +10,13 @@ struct Starter {
worker: Pin,
}
pub(super) async fn publish_missing(
pub(in crate::agent_updates) async fn publish_missing(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
) -> Result<(), Error> {
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE") else {
let Some(slot) = std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_FILE")
.or_else(|| std::env::var_os("RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE"))
else {
return Ok(());
};
let Some(config_dir) = FsPath::new(&slot).parent() else {
@@ -29,6 +31,7 @@ pub(super) async fn publish_missing(
}
for platform in [
Platform::LinuxX64,
Platform::LinuxArm64,
Platform::WindowsGnuX64,
Platform::WindowsX64,
] {
@@ -42,7 +45,11 @@ pub(super) async fn publish_missing(
if exists {
continue;
}
let path = distribution.join(format!("{name}.json"));
let path = if official_windows(platform) {
distribution.join(format!("{name}-official.json"))
} else {
distribution.join(format!("{name}.json"))
};
if !path
.try_exists()
.map_err(|_| fail("STARTER_CONFIGURATION"))?
@@ -64,7 +71,7 @@ pub(super) async fn publish_missing(
continue;
}
let package: Starter = serde_json::from_slice(&protected_file(&path, 65536)?)?;
let manifest = verify_signed_envelope(&package.envelope, platform, None)?;
let manifest = verify_envelope(&package.envelope, None)?;
if manifest.platform != platform {
return Err(invalid());
}
@@ -129,11 +136,12 @@ pub(super) async fn publish_missing(
.bind(tenant).bind(manifest.release_id).bind(name).bind(i64::try_from(manifest.release_sequence).map_err(|_|invalid())?)
.bind(hash(&package.envelope.decode().map_err(|_|invalid())?.payload_bytes)).bind(hash(&raw)).bind(raw)
.bind(a.artifact_id).bind(&a.sha256).bind(a.bytes as i64).bind(h.artifact_id).bind(&h.sha256).bind(h.bytes as i64).execute(&mut **tx).await?;
sqlx::query("INSERT INTO customer_starter_workers VALUES($1,$2,$3,$4)")
sqlx::query("INSERT INTO customer_starter_workers(tenant_id,platform,sha256,size_bytes,official_windows) VALUES($1,$2,$3,$4,$5)")
.bind(tenant)
.bind(name)
.bind(package.worker.sha256)
.bind(package.worker.bytes as i64)
.bind(official_windows(platform))
.execute(&mut **tx)
.await?;
}
+113 -6
View File
@@ -1,9 +1,9 @@
use crate::jobs::Error;
use axum::{
Json, Router,
extract::{Path, State},
extract::{Path, Query, State},
http::{HeaderMap, StatusCode},
routing::post,
routing::{delete, post},
};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -25,6 +25,11 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
"/api/v1/tenants/{tenant}/devices/{asset}/revocation",
post(revoke_device),
)
.route("/api/v1/tenants/{tenant}/devices/{asset}", delete(remove_device))
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/hypervisor",
post(assign_hypervisor),
)
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/archive",
post(archive_device),
@@ -33,7 +38,34 @@ pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
"/api/v1/tenants/{tenant}/operation-plans/{plan}/revocation",
post(revoke_plan),
)
.route("/api/v1/tenants/{tenant}/execution-stop", post(stop))
.route(
"/api/v1/tenants/{tenant}/execution-stop",
post(stop).get(stop_status),
)
}
async fn stop_status(
State(s): State<crate::State>,
h: HeaderMap,
Path(tenant): Path<Uuid>,
) -> Result<Json<Value>, Error> {
let principal = crate::jobs::principal(&s, &h, false).await?;
crate::jobs::scope(&principal, tenant, false)?;
if principal.session_hash.is_none() {
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
if !principal.permits_scope("operations:read")
|| !crate::permissions::allowed(&mut tx, &principal.name, "operations:read").await?
{
crate::permissions::require_principal(&mut tx, &principal, "tenant:stop").await?;
}
let stopped: bool = sqlx::query_scalar("SELECT changes_stopped FROM tenants WHERE tenant_id=$1")
.bind(tenant)
.fetch_optional(&mut *tx)
.await?
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
tx.commit().await?;
Ok(Json(json!({"tenant_id":tenant,"changes_stopped":stopped})))
}
async fn context<'a>(
s: &'a crate::State,
@@ -100,23 +132,98 @@ async fn archive_device(
tx.commit().await?;
Ok(Json(json!({"asset_id":asset, "archived":input.archived})))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pairing {
agent_id: Uuid,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct HypervisorAssignment {
// null clears the relation. A missing field is a malformed update.
#[serde(deserialize_with = "required_hypervisor_value")]
hypervisor_asset_id: Option<Uuid>,
}
fn required_hypervisor_value<'de, D: serde::Deserializer<'de>>(value: D) -> Result<Option<Uuid>, D::Error> {
Option::deserialize(value)
}
async fn assign_hypervisor(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pair): Query<Pairing>,
Json(input): Json<HypervisorAssignment>,
) -> Result<Json<Value>, Error> {
const EVENT: &str = "device_hypervisor_assigned";
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", EVENT).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
// Match the asset lock order for simultaneous edits of the same two devices.
let ids = [asset, input.hypervisor_asset_id.unwrap_or(asset)];
let rows: Vec<(Uuid, Option<Uuid>)> = sqlx::query_as(
"SELECT asset_id,hypervisor_asset_id FROM assets
WHERE tenant_id=$1 AND asset_id=ANY($2) ORDER BY asset_id FOR UPDATE",
)
.bind(tenant).bind(ids.as_slice()).fetch_all(&mut *tx).await?;
let previous = rows.into_iter().find(|(id, _)| *id == asset)
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?.1;
crate::devices::validate_vm_host_assignment(
&mut tx, tenant, asset, pair.agent_id, input.hypervisor_asset_id,
).await?;
if previous != input.hypervisor_asset_id {
sqlx::query("UPDATE assets SET hypervisor_asset_id=$3 WHERE tenant_id=$1 AND asset_id=$2")
.bind(tenant).bind(asset).bind(input.hypervisor_asset_id).execute(&mut *tx).await?;
audit(&mut tx, &p, EVENT, json!({"asset_id":asset,"agent_id":pair.agent_id,
"previous_hypervisor_asset_id":previous,"hypervisor_asset_id":input.hypervisor_asset_id})).await?;
}
tx.commit().await?;
Ok(Json(json!({"asset_id":asset,"hypervisor_asset_id":input.hypervisor_asset_id})))
}
async fn remove_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pairing): Query<Pairing>,
) -> Result<StatusCode, Error> {
let (p, mut tx) = context(&s, &h, tenant, "devices:revoke", "device_deleted").await?;
let status: String = sqlx::query_scalar("SELECT remove_revoked_device($1,$2,$3,$4)")
.bind(tenant).bind(asset).bind(pairing.agent_id).bind(&p.name)
.fetch_one(&mut *tx).await?;
match status.as_str() {
"deleted" => audit(&mut tx, &p, "device_deleted",
json!({"asset_id":asset, "agent_id":pairing.agent_id})).await?,
"absent" => (),
"active" => return Err(Error(StatusCode::CONFLICT, "DEVICE_REVOCATION_REQUIRED")),
"busy" => return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK")),
"forbidden" => return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN")),
_ => return Err(Error(StatusCode::INTERNAL_SERVER_ERROR, "DEVICE_DELETION_FAILED")),
}
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
pub async fn revoke_device(
State(s): State<crate::State>,
h: HeaderMap,
Path((t, asset)): Path<(Uuid, Uuid)>,
Query(selection): Query<crate::devices::DetailQuery>,
Json(i): Json<Reason>,
) -> Result<Json<Value>, Error> {
let (p, mut tx) = context(&s, &h, t, "devices:revoke", &i.reason).await?;
let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1").bind(asset).execute(&mut *tx).await?.rows_affected();
let n=sqlx::query("UPDATE agent_installations SET revoked_at=COALESCE(revoked_at,now()),connection_generation=connection_generation+1,previous_certificate_sha256=NULL,previous_certificate_until=NULL WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2)").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?.rows_affected();
if n == 0 {
return Err(Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
}
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).execute(&mut *tx).await?;
sqlx::query("UPDATE jobs SET cancel_requested=true WHERE asset_id=$1 AND ($2::uuid IS NULL OR agent_id=$2) AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown')").bind(asset).bind(selection.agent_id).execute(&mut *tx).await?;
audit(
&mut tx,
&p,
"device_revoked",
json!({"asset_id":asset,"reason":i.reason}),
json!({"asset_id":asset,"agent_id":selection.agent_id,"reason":i.reason}),
)
.await?;
tx.commit().await?;
+477
View File
@@ -0,0 +1,477 @@
use crate::{auth::Principal, jobs::Error};
use axum::{
Extension, Json, Router,
extract::{Path, Query, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
routing::{get, post},
};
use chrono::{DateTime, Utc};
use rmm_domain::{customer_transfer as wire, jobs::hash};
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::{Postgres, Row, Transaction};
use uuid::Uuid;
const NOT_FOUND: Error = Error(StatusCode::NOT_FOUND, "NOT_FOUND");
fn private_json(body: Value) -> Response {
([("cache-control", "private, no-store")], Json(body)).into_response()
}
pub(crate) fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
router
.route("/agent/v1/customer-transfer", get(device_offer))
.route(
"/agent/v1/customer-transfer/{transfer}/certificate",
post(device_certificate),
)
}
pub(crate) fn routes(router: Router<crate::State>) -> Router<crate::State> {
router
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer",
get(status).post(begin),
)
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/complete",
post(complete),
)
.route(
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/cancel",
post(cancel),
)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Pairing {
agent_id: Uuid,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Destination {
target_tenant_id: Uuid,
}
struct Transfer {
transfer_id: Uuid,
target_tenant_id: Uuid,
target_asset_id: Option<Uuid>,
target_agent_id: Option<Uuid>,
csr_sha256: Option<String>,
requested_by: String,
completed_at: Option<DateTime<Utc>>,
}
async fn source<'a>(
s: &'a crate::State,
headers: &HeaderMap,
tenant: Uuid,
write: bool,
) -> Result<(Principal, Transaction<'a, Postgres>), Error> {
let p = crate::jobs::principal(s, headers, write).await?;
crate::jobs::scope(&p, tenant, write)?;
if p.session_hash.is_none() {
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
crate::permissions::require_principal(&mut tx, &p, "devices:revoke").await?;
Ok((p, tx))
}
async fn select_tenant(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
.bind(tenant.to_string())
.execute(&mut **tx)
.await?;
Ok(())
}
async fn destination(
tx: &mut Transaction<'_, Postgres>,
p: &Principal,
target: Uuid,
) -> Result<(), Error> {
if target == p.tenant || !p.tenants.contains(&target) {
return Err(NOT_FOUND);
}
select_tenant(tx, target).await?;
crate::permissions::require_principal(tx, p, "inventory:read").await?;
crate::permissions::require_principal(tx, p, "devices:enroll").await
}
async fn transfer(
tx: &mut Transaction<'_, Postgres>,
agent: Uuid,
) -> Result<Option<Transfer>, Error> {
let row = sqlx::query(
"SELECT transfer_id,target_tenant_id,target_asset_id,target_agent_id,csr_sha256,requested_by,completed_at
FROM device_customer_transfers WHERE source_agent_id=$1 AND cancelled_at IS NULL",
)
.bind(agent)
.fetch_optional(&mut **tx)
.await?;
Ok(row.map(|row| Transfer {
transfer_id: row.get("transfer_id"),
target_tenant_id: row.get("target_tenant_id"),
target_asset_id: row.get("target_asset_id"),
target_agent_id: row.get("target_agent_id"),
csr_sha256: row.get("csr_sha256"),
requested_by: row.get("requested_by"),
completed_at: row.get("completed_at"),
}))
}
async fn target_hostname(
tx: &mut Transaction<'_, Postgres>,
t: &Transfer,
) -> Result<Option<String>, Error> {
let (Some(asset), Some(agent)) = (t.target_asset_id, t.target_agent_id) else {
return Ok(None);
};
Ok(sqlx::query_scalar(
"SELECT o.data->>'hostname' FROM agent_installations a
JOIN LATERAL (
SELECT data FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC LIMIT 1
) o ON true
WHERE a.asset_id=$1 AND a.agent_id=$2 AND a.revoked_at IS NULL
AND a.last_authenticated_at IS NOT NULL AND length(o.data->>'hostname')>0",
)
.bind(asset).bind(agent)
.fetch_optional(&mut **tx).await?)
}
async fn status(
State(s): State<crate::State>,
headers: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pair): Query<Pairing>,
) -> Result<Response, Error> {
let (p, mut tx) = source(&s, &headers, tenant, false).await?;
verify_pairing(&mut tx, asset, pair.agent_id).await?;
let Some(t) = transfer(&mut tx, pair.agent_id).await? else {
return Ok(private_json(json!({"transfer":null})));
};
destination(&mut tx, &p, t.target_tenant_id).await?;
let hostname = target_hostname(&mut tx, &t).await?;
let state = if t.completed_at.is_some() {
"completed"
} else if hostname.is_some() {
"ready"
} else if t.target_agent_id.is_some() {
"enrolled"
} else {
"pending"
};
tx.commit().await?;
Ok(private_json(json!({"transfer":{
"transfer_id":t.transfer_id, "state":state,
"target_tenant_id":t.target_tenant_id, "target_asset_id":t.target_asset_id,
"target_agent_id":t.target_agent_id, "target_hostname":hostname
}})))
}
async fn lock_source(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
asset: Uuid,
agent: Uuid,
) -> Result<bool, Error> {
crate::agent_service::control_lock(tx, tenant, agent).await?;
sqlx::query_scalar(
"SELECT i.revoked_at IS NULL AND i.last_authenticated_at IS NOT NULL AND a.archived_at IS NULL
FROM agent_installations i JOIN assets a USING (tenant_id,asset_id)
WHERE i.asset_id=$1 AND i.agent_id=$2 FOR UPDATE OF i",
)
.bind(asset)
.bind(agent)
.fetch_optional(&mut **tx)
.await?
.ok_or(NOT_FOUND)
}
async fn ensure_idle(tx: &mut Transaction<'_, Postgres>, agent: Uuid) -> Result<(), Error> {
let busy: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT FROM jobs WHERE agent_id=$1
AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))
OR EXISTS(SELECT FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
WHERE r.approval_state='pending_approval' AND p.expires_at>now()
AND convert_from(p.payload,'UTF8')::jsonb->'jobs'
@> jsonb_build_array(jsonb_build_object('payload',jsonb_build_object('agent_id',$1::uuid))))",
)
.bind(agent)
.fetch_one(&mut **tx)
.await?;
if busy {
return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK"));
}
Ok(())
}
async fn audit(
tx: &mut Transaction<'_, Postgres>,
p: &Principal,
event: &str,
details: Value,
) -> Result<(), Error> {
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,$4,$5,now())")
.bind(p.tenant).bind(Uuid::new_v4()).bind(&p.name).bind(event)
.bind(json!({"decision":details,"session_hash":p.session_hash,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}))
.execute(&mut **tx).await?;
Ok(())
}
async fn begin(
State(s): State<crate::State>,
headers: HeaderMap,
Path((tenant, asset)): Path<(Uuid, Uuid)>,
Query(pair): Query<Pairing>,
Json(input): Json<Destination>,
) -> Result<Response, Error> {
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
destination(&mut tx, &p, input.target_tenant_id).await?;
crate::agent_updates::ensure_customer_starters(&mut tx, input.target_tenant_id).await?;
select_tenant(&mut tx, tenant).await?;
if !lock_source(&mut tx, tenant, asset, pair.agent_id).await? {
return Err(Error(StatusCode::CONFLICT, "TRANSFER_SOURCE_INACTIVE"));
}
ensure_idle(&mut tx, pair.agent_id).await?;
let supported: bool =
sqlx::query_scalar("SELECT capabilities ? $2 FROM agent_installations WHERE agent_id=$1")
.bind(pair.agent_id)
.bind(wire::CAPABILITY)
.fetch_one(&mut *tx)
.await?;
if !supported {
return Err(Error(
StatusCode::CONFLICT,
"TRANSFER_AGENT_UPDATE_REQUIRED",
));
}
if transfer(&mut tx, pair.agent_id).await?.is_some() {
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_PENDING"));
}
let id = Uuid::new_v4();
sqlx::query(
"INSERT INTO device_customer_transfers(transfer_id,source_tenant_id,source_asset_id,source_agent_id,target_tenant_id,requested_by)
VALUES($1,$2,$3,$4,$5,$6)",
).bind(id).bind(tenant).bind(asset).bind(pair.agent_id).bind(input.target_tenant_id).bind(&p.name)
.execute(&mut *tx).await?;
audit(&mut tx, &p, "device_customer_transfer_prepared", json!({
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":input.target_tenant_id
})).await?;
tx.commit().await?;
Ok(private_json(json!({"transfer_id":id,"state":"pending"})))
}
async fn verify_pairing(
tx: &mut Transaction<'_, Postgres>,
asset: Uuid,
agent: Uuid,
) -> Result<(), Error> {
sqlx::query_scalar::<_, Uuid>(
"SELECT agent_id FROM agent_installations WHERE asset_id=$1 AND agent_id=$2",
)
.bind(asset)
.bind(agent)
.fetch_optional(&mut **tx)
.await?
.ok_or(NOT_FOUND)?;
Ok(())
}
async fn cancel(
State(s): State<crate::State>,
headers: HeaderMap,
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
Query(pair): Query<Pairing>,
) -> Result<StatusCode, Error> {
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
let changed = sqlx::query(
"UPDATE device_customer_transfers SET cancelled_at=now()
WHERE transfer_id=$1 AND source_agent_id=$2 AND target_agent_id IS NULL AND cancelled_at IS NULL",
).bind(id).bind(pair.agent_id).execute(&mut *tx).await?.rows_affected();
if changed == 0 {
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_STARTED"));
}
audit(
&mut tx,
&p,
"device_customer_transfer_cancelled",
json!({
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id
}),
)
.await?;
tx.commit().await?;
Ok(StatusCode::NO_CONTENT)
}
async fn complete(
State(s): State<crate::State>,
headers: HeaderMap,
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
Query(pair): Query<Pairing>,
) -> Result<Response, Error> {
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
let t = transfer(&mut tx, pair.agent_id)
.await?
.filter(|t| t.transfer_id == id)
.ok_or(NOT_FOUND)?;
destination(&mut tx, &p, t.target_tenant_id).await?;
if t.completed_at.is_some() {
return Ok(private_json(json!({"state":"completed"})));
}
if target_hostname(&mut tx, &t).await?.is_none() {
return Err(Error(StatusCode::CONFLICT, "TRANSFER_TARGET_NOT_READY"));
}
select_tenant(&mut tx, tenant).await?;
ensure_idle(&mut tx, pair.agent_id).await?;
sqlx::query(
"UPDATE agent_installations SET revoked_at=now(), connection_generation=connection_generation+1,
previous_certificate_sha256=NULL,previous_certificate_until=NULL
WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
)
.bind(asset).bind(pair.agent_id).execute(&mut *tx).await?;
sqlx::query("UPDATE device_customer_transfers SET completed_at=now() WHERE transfer_id=$1")
.bind(id)
.execute(&mut *tx)
.await?;
audit(&mut tx, &p, "device_customer_transfer_completed", json!({
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":t.target_tenant_id,
"target_asset_id":t.target_asset_id,"target_agent_id":t.target_agent_id
})).await?;
tx.commit().await?;
Ok(private_json(json!({"state":"completed"})))
}
async fn device_offer(
State(s): State<crate::State>,
Extension(peer): Extension<crate::Peer>,
headers: HeaderMap,
) -> Result<Response, Error> {
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
let offer = transfer(&mut tx, agent)
.await?
.filter(|t| t.completed_at.is_none())
.map(|t| offer(tenant, agent, &t));
tx.commit().await?;
Ok(private_json(json!({"offer":offer})))
}
fn offer(tenant: Uuid, agent: Uuid, t: &Transfer) -> wire::Offer {
wire::Offer {
transfer_id: t.transfer_id,
source_tenant_id: tenant,
source_agent_id: agent,
target_tenant_id: t.target_tenant_id,
}
}
async fn device_certificate(
State(s): State<crate::State>,
Extension(peer): Extension<crate::Peer>,
headers: HeaderMap,
Path(id): Path<Uuid>,
Json(input): Json<wire::CertificateRequest>,
) -> Result<Response, Error> {
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
let invalid = || Error(StatusCode::BAD_REQUEST, "INVALID_CSR");
if input.csr_pem.len() > 8192 {
return Err(invalid());
}
let csr = openssl::x509::X509Req::from_pem(input.csr_pem.as_bytes()).map_err(|_| invalid())?;
let public = csr.public_key().map_err(|_| invalid())?;
if !csr.verify(&public).map_err(|_| invalid())? {
return Err(invalid());
}
let digest = hash(&public.public_key_to_der().map_err(|_| invalid())?);
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
crate::agent_service::control_lock(&mut tx, tenant, agent).await?;
let (asset, generation): (Uuid, i64) = sqlx::query_as(
"SELECT asset_id,connection_generation FROM agent_installations
WHERE agent_id=$1 AND revoked_at IS NULL FOR UPDATE",
)
.bind(agent)
.fetch_optional(&mut *tx)
.await?
.ok_or(NOT_FOUND)?;
let t = transfer(&mut tx, agent)
.await?
.filter(|t| t.transfer_id == id && t.completed_at.is_none())
.ok_or(NOT_FOUND)?;
ensure_idle(&mut tx, agent).await?;
if t.target_agent_id.is_none() {
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
crate::permissions::require(&mut tx, &t.requested_by, "devices:revoke").await?;
}
select_tenant(&mut tx, t.target_tenant_id).await?;
let (new_asset, new_agent, certificate_pem) = if let (Some(target_asset), Some(target_agent)) =
(t.target_asset_id, t.target_agent_id)
{
if t.csr_sha256.as_deref() != Some(&digest) {
return Err(Error(StatusCode::CONFLICT, "TRANSFER_KEY_MISMATCH"));
}
let pem: String = sqlx::query_scalar(
"SELECT certificate_pem FROM agent_installations WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
).bind(target_asset).bind(target_agent).fetch_optional(&mut *tx).await?.ok_or(NOT_FOUND)?;
sqlx::query(
"UPDATE agent_installations SET connection_generation=GREATEST(connection_generation,$2)
WHERE agent_id=$1 AND last_authenticated_at IS NULL",
).bind(target_agent).bind(generation).execute(&mut *tx).await?;
(target_asset, target_agent, pem)
} else {
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
crate::permissions::require(&mut tx, &t.requested_by, "devices:enroll").await?;
let new_asset = Uuid::new_v4();
let new_agent = Uuid::new_v4();
let certificate =
crate::tls::issue(&s, &input.csr_pem, new_agent).map_err(|_| invalid())?;
let pem = String::from_utf8(certificate.to_pem().map_err(anyhow::Error::from)?)
.map_err(anyhow::Error::from)?;
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(t.target_tenant_id)
.bind(new_asset)
.execute(&mut *tx)
.await?;
sqlx::query(
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation)
VALUES($1,$2,$3,$4,$5,$6)",
).bind(t.target_tenant_id).bind(new_asset).bind(new_agent)
.bind(hash(&certificate.to_der().map_err(anyhow::Error::from)?)).bind(&pem).bind(generation)
.execute(&mut *tx).await?;
select_tenant(&mut tx, tenant).await?;
sqlx::query(
"UPDATE device_customer_transfers SET target_asset_id=$2,target_agent_id=$3,csr_sha256=$4
WHERE transfer_id=$1 AND source_asset_id=$5",
).bind(id).bind(new_asset).bind(new_agent).bind(digest).bind(asset).execute(&mut *tx).await?;
(new_asset, new_agent, pem)
};
let binding = wire::Binding {
offer: offer(tenant, agent, &t),
asset_id: new_asset,
agent_id: new_agent,
certificate_sha256: hash(certificate_pem.as_bytes()),
};
let signature_hex = hex::encode(s.job_signer.sign(&binding.signing_bytes()?)?);
tx.commit().await?;
Ok((
[("cache-control", "private, no-store")],
Json(wire::CertificateResponse {
certificate_pem,
receipt: wire::Receipt {
binding,
signature_hex,
},
}),
)
.into_response())
}
+2 -1
View File
@@ -2,7 +2,8 @@ WITH classified AS (
SELECT a.tenant_id,a.asset_id,a.agent_id,a.created_at,a.revoked_at,a.last_contact_at,
a.last_authenticated_at,a.last_authenticated_certificate_sha256,a.certificate_sha256,
a.enrollment_generation,a.assignment_version,a.capabilities,a.reported_agent_version,
asset.archived_at,t.name AS customer_name,
a.system_usage,a.system_usage_observed_at,
asset.archived_at,asset.hypervisor_asset_id,t.name AS customer_name,
CASE
WHEN a.revoked_at IS NOT NULL THEN 'revoked'
WHEN asset.archived_at IS NOT NULL THEN 'archived'
+284 -12
View File
@@ -10,9 +10,11 @@ use axum::{
http::{HeaderMap, HeaderValue, StatusCode},
};
use chrono::{DateTime, Utc};
use rmm_domain::inventory_document::DeviceType;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::{Postgres, Row, Transaction, postgres::PgRow};
use std::collections::HashMap;
use uuid::Uuid;
#[derive(Default, Deserialize, Serialize, schemars::JsonSchema, Clone, Copy)]
@@ -120,10 +122,7 @@ pub async fn list(
};
tenants.sort_unstable();
tenants.dedup();
let hostname = q.q.as_deref().unwrap_or("").trim();
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
}
let hostname = hostname_filter(q.q.as_deref())?;
let binding = json!([tenant, tenants, q.view, q.status, hostname]);
let scope = format!(
"device-fleet:{}",
@@ -179,6 +178,7 @@ pub async fn list(
}
.rows(&mut tx)
.await?;
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
tx.commit().await?;
for row in rows {
if items.len() == capacity {
@@ -186,7 +186,7 @@ pub async fn list(
break;
}
last = Some((customer, row.get::<Uuid, _>("agent_id")));
items.push(project(&row, page.as_of, tenant.is_some()));
items.push(project(&row, page.as_of, tenant.is_some(), &hosts));
}
if truncated {
break;
@@ -235,12 +235,22 @@ pub async fn detail(
.await?
.pop()
.ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
let mut item = project(&row, now, true);
let hosts = assigned_hosts(&mut tx, tenant, now, std::slice::from_ref(&row)).await?;
let mut item = project(&row, now, true, &hosts);
item["volumes"] = volumes(&item["inventory"]);
item["recent_jobs"] = if p.permits_scope("operations:read")
&& crate::permissions::allowed(&mut tx, &p.name, "operations:read").await?
{
sqlx::query_scalar::<_,Value>("SELECT jsonb_build_object('job_id',j.job_id,'operation_id',j.operation_id,'state',j.state,'created_at',r.created_at) FROM jobs j JOIN approval_requests r USING(tenant_id,operation_id) WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3 ORDER BY r.created_at DESC,j.job_id LIMIT 20")
sqlx::query_scalar::<_, Value>(
"SELECT jsonb_build_object(
'job_id', j.job_id, 'operation_id', j.operation_id, 'state', j.state, 'created_at', r.created_at,
'title', coalesce(nullif(plan_view.payload#>>'{script_revision,name}', ''), nullif(btrim(plan_view.payload->>'reason'), '')),
'action', convert_from(j.payload, 'UTF8')::jsonb#>>'{action,action}')
FROM jobs j JOIN approval_requests r USING (tenant_id, operation_id)
JOIN operation_plans p USING (tenant_id, plan_id)
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
WHERE j.tenant_id=$1 AND j.asset_id=$2 AND j.agent_id=$3
ORDER BY r.created_at DESC, j.job_id LIMIT 20")
.bind(tenant).bind(asset).bind(row.get::<Uuid,_>("agent_id")).fetch_all(&mut *tx).await?.into()
} else {
Value::Null
@@ -280,7 +290,146 @@ fn volumes(data: &Value) -> Value {
}
items.into()
}
fn device_type(hardware: &Value) -> Option<DeviceType> {
DeviceType::deserialize(&hardware["device_type"]).ok()
}
fn inventory_device_type(data: &Value) -> Option<DeviceType> {
device_type(observed(data, "linux.hardware"))
.or_else(|| device_type(observed(data, "windows.hardware")))
}
fn hostname_filter(query: Option<&str>) -> Result<&str, Error> {
let hostname = query.unwrap_or("").trim();
if hostname.len() > 255 || hostname.chars().any(char::is_control) {
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
}
Ok(hostname)
}
#[derive(Serialize)]
struct Host {
asset_id: Uuid,
agent_id: Uuid,
hostname: String,
}
async fn hypervisors(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
as_of: DateTime<Utc>,
ids: Option<&[Uuid]>,
hostname: &str,
limit: i64,
) -> Result<Vec<Host>, Error> {
let rows: Vec<(Uuid, Uuid, String)> = sqlx::query_as(include_str!("hypervisors.sql"))
.bind(tenant)
.bind(as_of)
.bind(ids)
.bind(hostname)
.bind(limit)
.fetch_all(&mut **tx)
.await?;
Ok(rows.into_iter().map(|(asset_id, agent_id, hostname)| Host {
asset_id, agent_id, hostname,
}).collect())
}
async fn assigned_hosts(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
as_of: DateTime<Utc>,
rows: &[PgRow],
) -> Result<HashMap<Uuid, Host>, Error> {
let mut ids: Vec<Uuid> = rows.iter().filter_map(|row| row.get("hypervisor_asset_id")).collect();
ids.sort_unstable();
ids.dedup();
if ids.is_empty() {
return Ok(HashMap::new());
}
Ok(hypervisors(tx, tenant, as_of, Some(&ids), "", ids.len() as i64)
.await?.into_iter().map(|host| (host.asset_id, host)).collect())
}
fn hypervisor_display(data: &Value, assigned: Option<&Host>) -> Value {
if inventory_device_type(data) != Some(DeviceType::Virtual) {
return Value::Null;
}
if let Some(host) = assigned {
return json!({"kind":"device","asset_id":host.asset_id,
"agent_id":host.agent_id,"hostname":host.hostname});
}
let linux = observed(data, "linux.hardware");
let windows = observed(data, "windows.hardware");
let manufacturer = linux["manufacturer"].as_str()
.filter(|value| !value.trim().is_empty())
.or_else(|| linux["readable_dmi"]["sys_vendor"].as_str())
.or_else(|| windows["manufacturer"].as_str());
if manufacturer.is_some_and(|name| matches!(name.trim().to_ascii_lowercase().as_str(),
"hetzner" | "hetzner cloud" | "hetzner online" | "hetzner online gmbh")) {
return json!({"kind":"placeholder","provider":"hetzner","hostname":"Hetzner Cloud"});
}
Value::Null
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HypervisorFilter {
q: Option<String>,
}
pub async fn hypervisor_options(
State(s): State<crate::State>,
h: HeaderMap,
Path(tenant): Path<Uuid>,
Query(query): Query<HypervisorFilter>,
) -> Result<Json<Value>, Error> {
let p = crate::jobs::principal(&s, &h, false).await?;
crate::jobs::scope(&p, tenant, false)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
let mut hosts = hypervisors(&mut tx, tenant, Utc::now(), None,
hostname_filter(query.q.as_deref())?, 51).await?;
let truncated = hosts.len() > 50;
hosts.truncate(50);
tx.commit().await?;
Ok(Json(json!({"items":hosts,"truncated":truncated})))
}
pub(crate) async fn validate_vm_host_assignment(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
asset: Uuid,
agent: Uuid,
host: Option<Uuid>,
) -> Result<(), Error> {
let now = Utc::now();
let row = Selection {
tenant, asset: Some(asset), agent: Some(agent), view: Some(View::Current),
status: None, hostname: "", last: Uuid::nil(), as_of: now, limit: 1,
}.rows(tx).await?.pop().ok_or(Error(StatusCode::NOT_FOUND, "NOT_FOUND"))?;
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
if inventory_device_type(&data) != Some(DeviceType::Virtual) {
return Err(Error(StatusCode::CONFLICT, "HYPERVISOR_REQUIRES_VM"));
}
if let Some(host) = host {
if asset == host {
return Err(Error(StatusCode::CONFLICT, "INVALID_HYPERVISOR"));
}
if hypervisors(tx, tenant, now, Some(&[host]), "", 1).await?.is_empty() {
return Err(Error(StatusCode::NOT_FOUND, "HYPERVISOR_UNAVAILABLE"));
}
}
Ok(())
}
fn os_label(data: &Value) -> Option<String> {
let linux_hardware = observed(data, "linux.hardware");
if linux_hardware["proxmox_ve"].as_bool() == Some(true)
&& device_type(linux_hardware) == Some(DeviceType::Hypervisor)
{
return Some("Proxmox VE".to_owned());
}
let raw = data["os"].as_str()?;
if let Some(pretty) = observed(data, "linux.os")["release"]["PRETTY_NAME"].as_str() {
return Some(pretty.to_owned());
@@ -328,10 +477,24 @@ fn os_label(data: &Value) -> Option<String> {
Some("Linux".to_owned())
}
}
fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
fn project(row: &PgRow, now: DateTime<Utc>, full: bool, hosts: &HashMap<Uuid, Host>) -> Value {
let data = row.get::<Option<Value>, _>("data").unwrap_or(Value::Null);
let cpu = observed(&data, "linux.cpu");
let windows = observed(&data, "windows.hardware");
let linux_memory = observed(&data, "linux.memory");
let usage = row
.get::<Option<Value>, _>("system_usage")
.unwrap_or(Value::Null);
let usage_at: Option<DateTime<Utc>> = row.get("system_usage_observed_at");
let inventory_at: Option<DateTime<Utc>> = row.get("observed_at");
let cpu_observed_at = usage["cpu_usage_observed_at"].as_str();
let cpu_usage = cpu_observed_at.and_then(|_| usage["cpu_usage_percent"].as_f64());
let ram_available = usage["ram_available_bytes"].as_u64();
let ram_total = usage["ram_total_bytes"]
.as_u64()
.or_else(|| linux_memory["total_bytes"].as_u64())
.or_else(|| windows["memory_total_bytes"].as_u64());
let device_type = inventory_device_type(&data);
let last = row.get::<Option<DateTime<Utc>>, _>("last_contact_at");
let revoked = row.get::<Option<DateTime<Utc>>, _>("revoked_at");
let presence = match (revoked, last.map(|t| (now - t).num_seconds())) {
@@ -346,17 +509,30 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> Value {
"agent_id":row.get::<Uuid,_>("agent_id"),"asset_id":row.get::<Uuid,_>("asset_id"),
"status":row.get::<String,_>("status"),"lifecycle":row.get::<String,_>("lifecycle"),
"archived_at":row.get::<Option<DateTime<Utc>>,_>("archived_at"),"revoked_at":revoked,
"hostname":data["hostname"].as_str(),"os":os_label(&data),
"hostname":data["hostname"].as_str(),"device_type":device_type,"os":os_label(&data),
"disk_free_bytes":data["root_available_bytes"].as_u64(),"disk_total_bytes":data["root_total_bytes"].as_u64(),
"cpu_model":cpu["model"].as_str().or_else(||windows["cpu_model"].as_str()),
"cpu_logical_count":cpu["logical_processors"].as_u64().or_else(||windows["logical_processors_visible"].as_u64()),
"ram_total_bytes":observed(&data,"linux.memory")["total_bytes"].as_u64().or_else(||windows["memory_total_bytes"].as_u64()),
"cpu_usage_percent":cpu_usage,
"cpu_usage_observed_at":cpu_observed_at,
"ram_total_bytes":ram_total,
"ram_available_bytes":ram_available.or_else(|| linux_memory["available_bytes"].as_u64().or_else(||windows["memory_available_bytes"].as_u64())
.filter(|available| ram_total.is_some_and(|total| *available <= total))),
"ram_observed_at":if ram_available.is_some() {usage_at} else {inventory_at},
"last_contact_at":last,"agent_version":row.get::<Option<String>,_>("reported_agent_version"),
"presence":presence,"observed_at":row.get::<Option<DateTime<Utc>>,_>("observed_at"),
"presence":presence,"observed_at":inventory_at,
"received_at":row.get::<Option<DateTime<Utc>>,_>("received_at"),
"source_id":row.get::<Option<String>,_>("source_id"),"quality":if data.is_null(){"unknown"}else{"valid"},
"completeness":"partial","health":"unknown"
});
if device_type == Some(DeviceType::Virtual) && row.get::<String, _>("lifecycle") == "current" {
let assigned_id: Option<Uuid> = row.get("hypervisor_asset_id");
let assigned = assigned_id.and_then(|id| hosts.get(&id));
item["hypervisor"] = hypervisor_display(&data, assigned);
if full {
item["assigned_hypervisor_asset_id"] = json!(assigned_id);
}
}
if full {
item["inventory"] = data;
item["capabilities"] = row.get("capabilities");
@@ -402,6 +578,102 @@ mod tests {
assert!(os_label(&Value::Null).is_none());
}
#[test]
fn proxmox_os_label_requires_a_valid_hypervisor_observation() {
let mut snapshot = json!({
"os": "Debian",
"observations": [{"scope":"linux.hardware","quality":"valid",
"data":{"device_type":"hypervisor","proxmox_ve":true}}]
});
assert_eq!(os_label(&snapshot).as_deref(), Some("Proxmox VE"));
snapshot["observations"][0]["data"]["device_type"] = json!("virtual");
assert_eq!(os_label(&snapshot).as_deref(), Some("Debian"));
snapshot["observations"][0]["quality"] = json!("error");
assert_eq!(device_type(observed(&snapshot, "linux.hardware")), None);
assert_eq!(device_type(&json!({"device_type":"desktop"})), None);
}
#[test]
fn hetzner_placeholder_requires_a_valid_guest_and_yields_to_a_registered_host() {
let mut data = json!({"observations":[{"scope":"linux.hardware","quality":"valid",
"data":{"device_type":"virtual","readable_dmi":{"sys_vendor":" Hetzner "}}}]});
assert_eq!(hypervisor_display(&data, None)["kind"], "placeholder");
let host = Host { asset_id: Uuid::new_v4(), agent_id: Uuid::new_v4(), hostname: "pve01".into() };
assert_eq!(hypervisor_display(&data, Some(&host))["asset_id"], json!(host.asset_id));
data["observations"][0]["data"]["device_type"] = json!("physical");
assert!(hypervisor_display(&data, None).is_null());
data["observations"][0]["data"]["device_type"] = json!("virtual");
data["observations"][0]["quality"] = json!("error");
assert!(hypervisor_display(&data, None).is_null());
data["observations"][0] = json!({"scope":"windows.hardware","quality":"valid",
"data":{"device_type":"virtual","manufacturer":"HETZNER ONLINE GMBH"}});
assert_eq!(hypervisor_display(&data, None)["hostname"], "Hetzner Cloud");
data["observations"][0]["data"]["manufacturer"] = json!("Other company");
assert!(hypervisor_display(&data, None).is_null());
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn host_links_resolve_outside_the_page_and_stay_inside_the_customer() {
let admin = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await.unwrap();
let app = sqlx::PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await.unwrap();
let tenant = Uuid::new_v4();
let other = Uuid::new_v4();
let mut ids = [Uuid::new_v4(), Uuid::new_v4()];
ids.sort_unstable();
let [vm, host] = ids;
let foreign_host = Uuid::new_v4();
for customer in [tenant, other] {
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'Hypervisor test')")
.bind(customer).execute(&admin).await.unwrap();
}
for (customer, id, name, kind) in [
(tenant, vm, "guest", "virtual"),
(tenant, host, "hypervisor-1", "hypervisor"),
(other, foreign_host, "hypervisor-2", "hypervisor"),
] {
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(customer).bind(id).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,last_contact_at,last_authenticated_at,last_authenticated_certificate_sha256) VALUES($1,$2,$2,$3,now(),now(),$3)")
.bind(customer).bind(id).bind(rmm_domain::jobs::hash(format!("{customer}:{id}").as_bytes()))
.execute(&admin).await.unwrap();
let data = json!({"hostname":name,"os":"Ubuntu","root_available_bytes":10,"root_total_bytes":20,
"observations":[{"scope":"linux.hardware","quality":"valid",
"data":{"device_type":kind,"manufacturer":"Hetzner"}}]});
sqlx::query("INSERT INTO observations(tenant_id,agent_id,message_id,boot_id,sequence,observed_at,source_id,quality,completeness,snapshot_id,data,payload_sha256) VALUES($1,$2,$3,$4,1,now(),'linux.base','valid','partial',$5,$6,$7)")
.bind(customer).bind(id).bind(Uuid::new_v4()).bind(Uuid::new_v4())
.bind(Uuid::new_v4()).bind(data).bind("0".repeat(64)).execute(&admin).await.unwrap();
}
let mut tx = rmm_persistence::tenant_tx(&app, tenant).await.unwrap();
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(foreign_host)).await.is_err());
assert!(validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(vm)).await.is_err());
validate_vm_host_assignment(&mut tx, tenant, vm, vm, Some(host)).await.unwrap();
sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
.bind(vm).bind(host).execute(&mut *tx).await.unwrap();
let q = Selection { tenant, asset: None, agent: None, view: Some(View::Current), status: None,
hostname: "", last: Uuid::nil(), as_of: Utc::now(), limit: 1 };
let page = q.rows(&mut tx).await.unwrap();
assert_eq!(page[0].get::<Uuid,_>("asset_id"), vm);
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["hostname"], "hypervisor-1");
let options = hypervisors(&mut tx, tenant, q.as_of, None, "HYPERVISOR", 51).await.unwrap();
assert_eq!(options.len(), 1);
assert_eq!(options[0].asset_id, host);
sqlx::query("UPDATE assets SET archived_at=now() WHERE asset_id=$1")
.bind(host).execute(&mut *tx).await.unwrap();
let hosts = assigned_hosts(&mut tx, tenant, q.as_of, &page).await.unwrap();
assert_eq!(project(&page[0], q.as_of, false, &hosts)["hypervisor"]["kind"], "placeholder");
let result = sqlx::query("UPDATE assets SET hypervisor_asset_id=$2 WHERE asset_id=$1")
.bind(vm).bind(foreign_host).execute(&mut *tx).await.unwrap_err();
assert_eq!(result.as_database_error().unwrap().code().as_deref(), Some("23503"));
tx.rollback().await.unwrap();
}
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn visibility_is_filtered_before_the_cursor_limit() {
@@ -444,7 +716,7 @@ mod tests {
limit: 1,
};
let row = q.rows(&mut tx).await.unwrap().pop().unwrap();
let summary = project(&row, q.as_of, false);
let summary = project(&row, q.as_of, false, &HashMap::new());
assert_eq!(summary["status"], "offline");
assert_eq!(summary["ram_total_bytes"], 1024);
assert_eq!(summary["cpu_model"], "Test CPU");
+29
View File
@@ -0,0 +1,29 @@
SELECT asset.asset_id, host.agent_id, inventory.data->>'hostname' AS hostname
FROM assets asset
JOIN LATERAL (
SELECT a.agent_id, a.revoked_at
FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id AND a.created_at<=$2
AND a.last_authenticated_at IS NOT NULL AND a.last_contact_at IS NOT NULL
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
LIMIT 1
) host ON host.revoked_at IS NULL
JOIN LATERAL (
SELECT data FROM observations
WHERE tenant_id=asset.tenant_id AND agent_id=host.agent_id AND received_at<=$2
AND source_id IN ('linux.base','windows.base')
ORDER BY observed_at DESC, received_at DESC, sequence DESC
LIMIT 1
) inventory ON true
WHERE asset.tenant_id=$1 AND asset.archived_at IS NULL
AND ($3::uuid[] IS NULL OR asset.asset_id=ANY($3))
AND nullif(btrim(inventory.data->>'hostname'),'') IS NOT NULL
AND ($4='' OR strpos(lower(inventory.data->>'hostname'), lower($4))>0)
AND EXISTS (
SELECT FROM jsonb_array_elements(CASE WHEN jsonb_typeof(inventory.data->'observations')='array'
THEN inventory.data->'observations' ELSE '[]'::jsonb END) o
WHERE o->>'scope' IN ('linux.hardware','windows.hardware')
AND o->>'quality'='valid' AND o#>>'{data,device_type}'='hypervisor'
)
ORDER BY lower(inventory.data->>'hostname'), asset.asset_id
LIMIT $5
+100 -69
View File
@@ -528,7 +528,25 @@ pub async fn permit(
denial_code: code.into(),
unreserved_request: None,
};
let row=sqlx::query("SELECT j.*,a.authorization_id,a.revoked_at,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,r.approval_state,i.enrollment_generation,i.assignment_version,i.asset_id AS bound_asset,i.capabilities,i.revoked_at AS device_revoked,i.connection_generation,t.changes_stopped FROM jobs j JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id JOIN tenants t ON t.tenant_id=j.tenant_id WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j").bind(Uuid::parse_str(&r.job_id)?).bind(Uuid::parse_str(&r.attempt_id)?).bind(agent).fetch_optional(&mut *tx).await?;
let row = sqlx::query(
"SELECT j.*, a.authorization_id, a.revoked_at, a.principal AS approver, r.principal AS submitter,
p.plan_hash, p.payload AS plan_payload, r.approval_state,
i.enrollment_generation, i.assignment_version, i.asset_id AS bound_asset,
i.capabilities, i.revoked_at AS device_revoked, i.connection_generation, t.changes_stopped
FROM jobs j
JOIN operations o USING (tenant_id,operation_id)
JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id
JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id
JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id
JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id
JOIN tenants t ON t.tenant_id=j.tenant_id
WHERE j.job_id=$1 AND j.attempt_id=$2 AND j.agent_id=$3 FOR UPDATE OF j",
)
.bind(Uuid::parse_str(&r.job_id)?)
.bind(Uuid::parse_str(&r.attempt_id)?)
.bind(agent)
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
return Ok(denied("NOT_FOUND"));
};
@@ -571,8 +589,6 @@ pub async fn permit(
|| row
.get::<Option<chrono::DateTime<Utc>>, _>("device_revoked")
.is_some()
|| !crate::jobs::requester_enabled(state, &mut tx, &plan.principal, tenant).await?
|| !crate::jobs::requester_enabled(state, &mut tx, &row.get::<String, _>("approver"), tenant).await?
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
@@ -609,14 +625,7 @@ pub async fn permit(
.bind(agent)
.fetch_one(&mut *tx)
.await?;
if !helper_ready
|| crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
.await
.is_err()
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
.await
.is_err()
{
if !helper_ready {
return Ok(denied(if payload.execution_identity == "system" {
"SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED"
} else {
@@ -684,23 +693,6 @@ pub async fn permit(
{
return Ok(denied("ARTIFACT_BINDING_MISMATCH"));
}
let approver: String = row.get("approver");
if matches!(payload.action, Action::QueryLogs { .. })
&& !crate::permissions::allowed(&mut tx, &plan.principal, "logs:read").await?
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
if !crate::permissions::allowed(&mut tx, &approver, "plans:approve").await?
|| !crate::permissions::allowed(&mut tx, &plan.principal, "operations:submit").await?
|| (matches!(payload.action, Action::RunScript { .. })
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "scripts:execute").await?
|| !crate::permissions::allowed(&mut tx, &approver, "scripts:execute").await?))
|| (matches!(payload.action, Action::UpdateAgent { .. })
&& (!crate::permissions::allowed(&mut tx, &plan.principal, "updates:apply").await?
|| !crate::permissions::allowed(&mut tx, &approver, "updates:apply").await?))
{
return Ok(denied("AUTHORIZATION_REVOKED"));
}
let limits: (i32, i32) =
sqlx::query_as("SELECT starts_per_hour,max_parallel FROM tenant_limits")
.fetch_one(&mut *tx)
@@ -743,6 +735,21 @@ pub async fn permit(
if locked {
return Ok(denied("RESOURCE_LOCKED"));
}
let log_sensitive = crate::root_policy::stored_log_sensitivity(&payload);
if let Err(error) =
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
{
if error.0.is_server_error() {
anyhow::bail!("job authorization unavailable");
}
let code = match (error.1, payload.execution_identity.as_str()) {
("AUTHORIZATION_REVOKED" | "FORBIDDEN", _) => "AUTHORIZATION_REVOKED",
(_, "system") => "SYSTEM_SCOPE_OR_HELPER_SYNC_REQUIRED",
(_, "root") => "ROOT_SCOPE_OR_HELPER_SYNC_REQUIRED",
_ => "AUTHORIZATION_REVOKED",
};
return Ok(denied(code));
}
let grant = ExecutionPermitPayload {
agent_update_plan_id: matches!(payload.action, Action::UpdateAgent { .. })
.then_some(plan.plan_id),
@@ -769,8 +776,9 @@ pub async fn permit(
let bytes = encode(&grant)?;
let signature = state.job_signer.sign(&bytes)?;
sqlx::query("INSERT INTO execution_permits(tenant_id,grant_id,job_id,attempt_id,payload,signature) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(grant.grant_id).bind(grant.job_id).bind(grant.attempt_id).bind(&bytes).bind(&signature).execute(&mut *tx).await?;
sqlx::query("UPDATE jobs SET start_reserved=true WHERE job_id=$1")
sqlx::query("UPDATE jobs SET start_reserved=true, log_sensitive=$2 WHERE job_id=$1")
.bind(grant.job_id)
.bind(log_sensitive)
.execute(&mut *tx)
.await?;
sqlx::query("INSERT INTO audit_events VALUES($1,$2,'job-service','start_reserved',$3,now())")
@@ -804,54 +812,77 @@ pub async fn next(
if let Some(r)=sqlx::query("SELECT job_id,attempt_id FROM jobs WHERE agent_id=$1 AND cancel_requested AND state IN ('accepted','running','verifying','awaiting_reboot') ORDER BY job_id LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?{
tx.commit().await?;return Ok(Some(Payload::CancelRequest(CancelRequest{job_id:r.get::<Uuid,_>("job_id").to_string(),attempt_id:r.get::<Uuid,_>("attempt_id").to_string(),reason:"operator_cancel_requested".into()})))
}
let row=sqlx::query("SELECT j.job_id,j.attempt_id,j.payload,j.payload_hash,a.authorization_id,a.principal AS approver,p.plan_hash,p.payload AS plan_payload,i.capabilities FROM outbox b JOIN jobs j USING(tenant_id,job_id,attempt_id) JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id JOIN operation_plans p ON p.tenant_id=j.tenant_id AND p.plan_id=r.plan_id JOIN tenants t ON t.tenant_id=j.tenant_id JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id WHERE j.agent_id=$1 AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now() AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now()) ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1").bind(agent).fetch_optional(&mut *tx).await?;
let Some(row) = row else {
tx.commit().await?;
return Ok(None);
};
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
if payload.action.windows_msi().is_some()
|| matches!(payload.action, Action::UpdateAgent { .. })
{
// A revoked participant can leave a queued job behind. Skip that job
// without leasing it so later eligible work on the same device can proceed.
let mut after = None;
let row = loop {
let row = sqlx::query(
"SELECT j.job_id, j.attempt_id, j.payload, j.payload_hash, a.authorization_id,
a.principal AS approver, r.principal AS submitter, p.plan_hash,
p.payload AS plan_payload, i.capabilities
FROM outbox b
JOIN jobs j USING (tenant_id,job_id,attempt_id)
JOIN operations o ON o.tenant_id=j.tenant_id AND o.operation_id=j.operation_id
JOIN authorizations a ON a.tenant_id=o.tenant_id AND a.authorization_id=o.authorization_id
JOIN approval_requests r ON r.tenant_id=j.tenant_id AND r.operation_id=j.operation_id
JOIN operation_plans p ON p.tenant_id=r.tenant_id AND p.plan_id=r.plan_id
JOIN tenants t ON t.tenant_id=j.tenant_id
JOIN agent_installations i ON i.tenant_id=j.tenant_id AND i.agent_id=j.agent_id
WHERE j.agent_id=$1 AND ($2::uuid IS NULL OR j.job_id>$2)
AND j.state='queued' AND NOT j.cancel_requested AND NOT t.changes_stopped
AND a.revoked_at IS NULL AND r.approval_state='approved' AND p.expires_at>now()
AND b.acknowledged_at IS NULL AND (b.lease_until IS NULL OR b.lease_until<now())
ORDER BY j.job_id FOR UPDATE OF b SKIP LOCKED LIMIT 1",
)
.bind(agent)
.bind(after)
.fetch_optional(&mut *tx)
.await?;
let Some(row) = row else {
tx.commit().await?;
return Ok(None);
};
after = Some(row.get::<Uuid, _>("job_id"));
let raw: Vec<u8> = row.get("plan_payload");
let plan: PlanPayload = serde_json::from_slice(&raw)?;
if hash(&raw) != row.get::<String, _>("plan_hash")
|| crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err()
|| (matches!(payload.action, Action::UpdateAgent { .. })
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err())
|| crate::catalog::check(&mut tx, &payload.action)
.await
.is_err()
if hash(&raw) != row.get::<String, _>("plan_hash") {
continue;
}
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
let caps: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
if payload.action.windows_msi().is_some()
|| matches!(payload.action, Action::UpdateAgent { .. })
{
tx.commit().await?;
return Ok(None);
if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err()
|| (matches!(payload.action, Action::UpdateAgent { .. })
&& crate::agent_updates::validate_job_binding(&plan, &payload).is_err())
|| crate::catalog::check(&mut tx, &payload.action)
.await
.is_err()
{
continue;
}
}
}
if !payload
.action
.available_for(&payload.execution_identity, &caps)
|| !payload
if !payload
.action
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
{
tx.commit().await?;
return Ok(None);
}
if crate::root_policy::needs_helper(&payload.execution_identity) {
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
if crate::root_policy::authorize(&mut tx, &plan.principal, &payload)
.await
.is_err()
|| crate::root_policy::authorize(&mut tx, &row.get::<String, _>("approver"), &payload)
.await
.is_err()
.available_for(&payload.execution_identity, &caps)
|| !payload
.action
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
{
tx.commit().await?;
return Ok(None);
continue;
}
}
if let Err(error) =
crate::jobs::authorize_approved_job(state, &mut tx, tenant, &plan, &payload, &row).await
{
if error.0.is_server_error() {
anyhow::bail!("job authorization unavailable");
}
continue;
}
break row;
};
sqlx::query("UPDATE outbox SET lease_until=now()+interval '30 seconds' WHERE job_id=$1")
.bind(row.get::<Uuid, _>("job_id"))
.execute(&mut *tx)
+368 -426
View File
File diff suppressed because it is too large Load Diff
+45 -5
View File
@@ -316,6 +316,8 @@ async fn consume(pool: &PgPool, account: &Account, step: i64) -> Result<(), Stat
#[cfg(test)]
mod tests {
mod job_participants;
use super::*;
use chrono::Utc;
use serde_json::json;
@@ -441,7 +443,8 @@ mod tests {
let fingerprint = hash(asset.as_bytes());
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,last_contact_at,last_authenticated_certificate_sha256,last_authenticated_at) VALUES($1,$2,$3,$4,now(),$4,now())")
.bind(b).bind(Uuid::new_v4()).bind(asset).bind(fingerprint).execute(&admin).await.unwrap();
let mut config = sample(&issuer, a, &hex::encode([1; 64]));
let password = "test pairing removal";
let mut config = sample(&issuer, a, &hex::encode(derive_password(password.as_bytes(), &[7; 32]).unwrap()));
let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
auth.local = Some(configured(&config));
let key_dir = std::env::temp_dir().join(id.to_string());
@@ -456,14 +459,16 @@ mod tests {
.unwrap(),
),
};
let router = crate::jobs::routes(
let router = crate::controls::routes(crate::jobs::routes(
Router::new()
.route("/api/v1/tenants", get(crate::api::tenants))
.route(
"/api/v1/tenants/{tenant}/devices/{asset}",
get(crate::devices::detail),
),
)
))
.route("/auth/local/login", axum::routing::post(crate::auth::local_login))
.route("/auth/session", get(crate::auth::session))
.layer(middleware::from_fn(crate::auth::context))
.with_state(state.clone());
let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
@@ -481,12 +486,13 @@ mod tests {
assert_eq!(directory["items"].as_array().unwrap().len(), 1);
assert_eq!(directory["items"][0]["tenant_id"], a.to_string());
let now = Utc::now();
let forbidden_plan = json!({"tenant_id":b,"action":"refresh_inventory","targets":{"asset_ids":[asset]},
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"scope":"base"},
let forbidden_plan = json!({"tenant_id":b,"action":"run_script","targets":{"asset_ids":[asset]},
"parameters":{"execution_identity":"agent_service","timeout_seconds":60,"max_output_bytes":4096,"variants":[{"os_family":"linux","interpreter":"posix_sh","encoding":"utf-8","script_utf8":":\n"}]},
"schedule":{"not_before":now,"start_before":now+chrono::Duration::minutes(5),"offline_policy":"wait_until_deadline"},
"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"test customer authorization"});
for request in [
client.get(format!("{base}/{b}/devices/{asset}")),
client.delete(format!("{base}/{b}/devices/{asset}?agent_id={id}")),
client
.post(format!("{base}/{b}/operation-plans"))
.json(&forbidden_plan),
@@ -509,6 +515,40 @@ mod tests {
.await
.unwrap();
assert_eq!(created, 0);
let pair = format!("{base}/{a}/devices/{asset}?agent_id={id}");
let same_customer = client.delete(&pair).bearer_auth(&token).send().await.unwrap();
assert_eq!(same_customer.status(), StatusCode::FORBIDDEN);
let api = base.strip_suffix("/api/v1/tenants").unwrap();
let origin = &state.auth.origin;
let credentials = input(password, &configured(&config).users[0].secret);
let logged_in = client.post(format!("{api}/auth/local/login")).header("origin", origin)
.json(&json!({"username":credentials.username,"password":credentials.password,"totp_code":credentials.totp_code}))
.send().await.unwrap().error_for_status().unwrap();
let cookie = logged_in.headers()["set-cookie"].to_str().unwrap().split(';').next().unwrap();
let session = client.get(format!("{api}/auth/session")).header("cookie", cookie)
.send().await.unwrap().json::<Value>().await.unwrap();
let deletion = || client.delete(&pair).header("origin", origin).header("cookie", cookie);
let csrf = session["csrf_token"].as_str().unwrap();
assert_eq!(deletion().header("x-csrf-token", csrf).send().await.unwrap().status(), StatusCode::FORBIDDEN);
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'devices:revoke') WHERE tenant_id=$1 AND principal=$2")
.bind(a).bind(&issuer).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(a).bind(asset).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$3,$4)")
.bind(a).bind(id).bind(asset).bind(hash(id.as_bytes())).execute(&admin).await.unwrap();
assert_eq!(deletion().send().await.unwrap().status(), StatusCode::FORBIDDEN);
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::CONFLICT);
let revoked = client.post(format!("{base}/{a}/devices/{asset}/revocation?agent_id={id}"))
.header("origin", origin).header("cookie",cookie).header("x-csrf-token",csrf)
.json(&json!({"reason":"isolated retirement"})).send().await.unwrap();
assert_eq!(revoked.status(), StatusCode::OK);
for _ in 0..2 {
assert_eq!(deletion().header("x-csrf-token",csrf).send().await.unwrap().status(), StatusCode::NO_CONTENT);
}
let records: i64 = sqlx::query_scalar("SELECT count(*) FROM audit_events WHERE tenant_id=$1 AND event_type='device_deleted' AND data#>>'{decision,agent_id}'=$2")
.bind(a).bind(id.to_string()).fetch_one(&admin).await.unwrap();
assert_eq!(records, 1);
server.abort();
config["users"][0]["disabled"] = json!(true);
let mut disabled = crate::auth::Auth::from_env("development").await.unwrap();
@@ -0,0 +1,277 @@
use super::*;
use crate::auth::Principal;
use crate::jobs::{PlanInput, Rollout, Schedule, Submit, Targets};
use rmm_domain::jobs::{Action, PlanPayload, encode};
use rmm_protocol::{Envelope, ExecutionPermitRequest, Payload};
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn separate_roles_and_submitter_revocation_at_approval_and_start() {
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
let tenant = Uuid::new_v4();
let agent = Uuid::new_v4();
let planner_name = format!("local:{}", Uuid::new_v4());
let approver_name = format!("local:{}", Uuid::new_v4());
let scopes = ["operations:submit", "operations:read", "scripts:execute"];
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,$2)")
.bind(tenant)
.bind(format!("Participants {tenant}"))
.execute(&admin)
.await
.unwrap();
for (actor, permissions) in [
(&planner_name, vec!["operations:plan", "scripts:execute"]),
(
&approver_name,
[scopes.as_slice(), &["plans:approve", "tokens:manage"]].concat(),
),
] {
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',$3)")
.bind(tenant).bind(actor).bind(permissions).execute(&admin).await.unwrap();
}
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(tenant)
.bind(agent)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256,capabilities,connection_generation) VALUES($1,$2,$2,$3,$4,1)")
.bind(tenant).bind(agent).bind(hash(agent.as_bytes())).bind(json!(["linux.base/1","run_script"]))
.execute(&admin).await.unwrap();
let mut accounts = sample(&planner_name, tenant, &"0".repeat(128));
let mut reviewer = sample(&approver_name, tenant, &"0".repeat(128))["users"][0].clone();
reviewer["username"] = json!("reviewer");
accounts["users"].as_array_mut().unwrap().push(reviewer);
let mut auth = crate::auth::Auth::from_env("development").await.unwrap();
auth.local = Some(configured(&accounts));
let key_dir = std::env::temp_dir().join(format!("rmm-roles-{tenant}"));
let state = crate::State {
auth: Arc::new(auth),
pool: pool.clone(),
signer: None,
viewer_a: [0; 32],
viewer_b: [1; 32],
job_signer: Arc::new(
crate::job_signer::JobSigner::load_or_create(&key_dir.join("test.key")).unwrap(),
),
};
let planner = Principal {
tenant,
tenants: vec![tenant],
name: planner_name,
operator: true,
scopes: None,
session_hash: None,
csrf: None,
testsimulation: true,
identity: None,
};
let approver = Principal {
name: approver_name,
..planner.clone()
};
for stage in [
"revoked_before_approval",
"revoked_before_start",
"scope_removed",
"allowed",
] {
let token_id = Uuid::new_v4();
let raw = format!("rmm_mcp_{}AAAAAAAAAAA", token_id.simple());
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
sqlx::query("SELECT issue_customer_token($1,$2,'submit fixture',$3,$4,now()+interval '1 hour',false,$5)")
.bind(&approver.name).bind(token_id).bind(hash(raw.as_bytes())).bind(scopes.as_slice())
.bind(vec![tenant]).execute(&mut *tx).await.unwrap();
tx.commit().await.unwrap();
let submitter = crate::mcp_tokens::authenticate(&state, &raw, Some(tenant))
.await
.unwrap();
let now = Utc::now();
let input = PlanInput {
targets: Targets {
asset_ids: vec![agent],
},
action: Action::RunScript {
interpreter: "posix_sh".into(),
script_utf8: ":\n".into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: None,
},
execution_identity: "agent_service".into(),
max_runtime_seconds: 30,
max_output_bytes: 1024,
script_variants: vec![],
artifact_ids: vec![],
schedule: Schedule {
not_before: now,
start_before: now + chrono::Duration::hours(1),
},
rollout: Rollout {
max_parallel: 1,
halt_after_failures: 1,
},
reason: stage.into(),
};
let saved = crate::jobs::plan(&state, &planner, tenant, input)
.await
.unwrap();
let plan: PlanPayload = serde_json::from_value(saved["payload"].clone()).unwrap();
let order = crate::jobs::submit(
&state,
&submitter,
tenant,
plan.plan_id,
Submit {
idempotency_key: stage.into(),
},
)
.await
.unwrap();
let op: Uuid = serde_json::from_value(order["operation_id"].clone()).unwrap();
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
let stored_submitter: String =
sqlx::query_scalar("SELECT principal FROM approval_requests WHERE operation_id=$1")
.bind(op)
.fetch_one(&mut *tx)
.await
.unwrap();
assert_eq!(stored_submitter, submitter.name);
if stage == "revoked_before_approval" {
assert!(revoke(&mut tx, &approver, token_id).await);
assert_eq!(
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
.await
.unwrap_err()
.1,
"AUTHORIZATION_REVOKED"
);
let (status, jobs, permits): (String, i64, i64) = sqlx::query_as(
"SELECT approval_state,(SELECT count(*) FROM jobs WHERE operation_id=$1),(SELECT count(*) FROM execution_permits WHERE job_id=$2) FROM approval_requests WHERE operation_id=$1"
).bind(op).bind(plan.jobs[0].payload.job_id).fetch_one(&mut *tx).await.unwrap();
assert_eq!((status.as_str(), jobs, permits), ("pending_approval", 0, 0));
tx.commit().await.unwrap();
continue;
}
crate::jobs::recheck_approval(&state, &mut tx, &plan, &stored_submitter, &approver)
.await
.unwrap();
tx.commit().await.unwrap();
// Isolated ledger fixture for the normal gateway entry point. No client is connected.
let job = &plan.jobs[0];
let id = Uuid::new_v4();
sqlx::query("UPDATE approval_requests SET approval_state='approved' WHERE operation_id=$1")
.bind(op)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$3,$4,$5,$6,'fixture','dev_test_browser_simulation',true,1)")
.bind(tenant).bind(id).bind(op).bind(plan.plan_id).bind(saved["plan_hash"].as_str().unwrap()).bind(&approver.name)
.execute(&admin).await.unwrap();
sqlx::query("INSERT INTO operations VALUES($1,$2,$3)")
.bind(tenant)
.bind(op)
.bind(id)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,journal_proof) VALUES($1,$2,$3,$4,$5,$5,$6,$7,'queued','device_execution','fixture')")
.bind(tenant).bind(job.payload.job_id).bind(job.payload.attempt_id).bind(op).bind(agent)
.bind(encode(&job.payload).unwrap()).bind(&job.job_payload_hash).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO outbox(tenant_id,job_id,attempt_id) VALUES($1,$2,$3)")
.bind(tenant)
.bind(job.payload.job_id)
.bind(job.payload.attempt_id)
.execute(&admin)
.await
.unwrap();
if stage == "revoked_before_start" {
let mut tx = rmm_persistence::tenant_tx(&pool, tenant).await.unwrap();
assert!(revoke(&mut tx, &approver, token_id).await);
tx.commit().await.unwrap();
} else if stage == "scope_removed" {
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'scripts:execute') WHERE tenant_id=$1 AND principal=$2")
.bind(tenant).bind(&submitter.name).execute(&admin).await.unwrap();
}
let offer = crate::job_gateway::next(&state, tenant, agent, 1)
.await
.unwrap();
if stage == "allowed" {
assert!(
matches!(offer, Some(Payload::JobOffer(o)) if o.job_id == job.payload.job_id.to_string())
);
} else {
assert!(offer.is_none());
let leased: bool =
sqlx::query_scalar("SELECT lease_until IS NOT NULL FROM outbox WHERE job_id=$1")
.bind(job.payload.job_id)
.fetch_one(&admin)
.await
.unwrap();
assert!(!leased);
}
// Also model acceptance before the same revocation, so the start gate is exercised independently.
sqlx::query("UPDATE jobs SET state='accepted' WHERE job_id=$1")
.bind(job.payload.job_id)
.execute(&admin)
.await
.unwrap();
let envelope = Envelope {
connection_generation: 1,
..Default::default()
};
let request = ExecutionPermitRequest {
job_id: job.payload.job_id.to_string(),
attempt_id: job.payload.attempt_id.to_string(),
job_payload_hash: job.job_payload_hash.clone(),
assignment_version: job.payload.assignment_version,
};
let permit = crate::job_gateway::permit(&state, tenant, agent, &envelope, &request)
.await
.unwrap();
let (reserved, count): (bool, i64) = sqlx::query_as("SELECT start_reserved,(SELECT count(*) FROM execution_permits WHERE job_id=$1) FROM jobs WHERE job_id=$1")
.bind(job.payload.job_id).fetch_one(&admin).await.unwrap();
if stage == "allowed" {
assert_eq!(permit.denial_code, "");
assert!(!permit.signature.is_empty());
assert_eq!((reserved, count), (true, 1));
} else {
assert_eq!(permit.denial_code, "AUTHORIZATION_REVOKED");
assert!(permit.payload_bytes.is_empty() && permit.signature.is_empty());
assert_eq!((reserved, count), (false, 0));
// A still-queued denied fixture must not prevent delivery of the next allowed job.
sqlx::query("UPDATE jobs SET state='queued' WHERE job_id=$1")
.bind(job.payload.job_id)
.execute(&admin)
.await
.unwrap();
}
}
std::fs::remove_dir_all(key_dir).unwrap();
}
async fn revoke(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
approver: &Principal,
id: Uuid,
) -> bool {
sqlx::query_scalar("SELECT revoke_mcp_token($1,$2,$3,$4)")
.bind(&approver.name)
.bind(id)
.bind(Uuid::new_v4())
.bind(&approver.tenants)
.fetch_one(&mut **tx)
.await
.unwrap()
}
+5 -2
View File
@@ -13,6 +13,7 @@ mod auth;
mod local_auth;
mod mcp_tokens;
mod customers;
mod customer_transfer;
mod catalog;
mod checkpoint_repair;
mod controls;
@@ -27,6 +28,7 @@ mod oidc;
mod pagination;
mod permissions;
mod root_policy;
mod managed_scripts;
mod scheduler;
mod script_library;
mod synchronization;
@@ -173,7 +175,7 @@ async fn main() -> Result<()> {
}
let mut routes = Router::new().route("/healthz", get(|| async { "ok" }));
if role.gateway() {
routes = agent_updates::gateway_routes(routes);
routes = customer_transfer::gateway_routes(agent_updates::gateway_routes(routes));
routes = agent_update_health::gateway_routes(routes);
routes = agent_time::gateway_routes(routes);
routes = routes
@@ -215,12 +217,13 @@ async fn main() -> Result<()> {
.route("/api/v1/tenants/{tenant}", axum::routing::patch(customers::rename))
.route("/api/v1/devices", get(devices::all))
.route("/api/v1/tenants/{tenant}/devices", get(devices::page))
.route("/api/v1/tenants/{tenant}/hypervisors", get(devices::hypervisor_options))
.route("/api/v1/tenants/{tenant}/devices/{asset}", get(devices::detail));
routes = mcp_tokens::routes(routes);
routes = routes.route("/auth/local/login", post(auth::local_login));
routes = jobs::routes(routes);
routes = script_library::routes(routes);
routes = controls::routes(routes);
routes = customer_transfer::routes(controls::routes(routes));
routes = catalog::routes(routes);
routes = agent_updates::routes(routes);
routes = routes
+468
View File
@@ -0,0 +1,468 @@
//! Permanent authorization ceilings for installed, pinned script helpers.
//! Plan submission, interactive approval and signed start grants are unchanged.
use crate::{jobs::Error, root_policy::RootScope, windows_policy::SystemScope};
use axum::http::StatusCode;
use rmm_domain::{
agent_update::{ArtifactRole, LINUX_ARM64_RELEASE_CAPABILITY, Platform, ReleaseManifest, digest},
jobs::{Action, FULL_MAINTENANCE_CAPABILITY, JobPayload},
};
use serde::Deserialize;
use sqlx::{Postgres, Transaction};
use std::{fs, os::unix::fs::MetadataExt, path::Path};
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Policy {
schema_version: u8,
linux: Vec<RootScope>,
windows: Vec<SystemScope>,
#[serde(default)]
release_anchors: Vec<ReleaseAnchor>,
}
/// Operator-pinned canonical bytes of an already authorized local policy.
/// A signed pair changes only the two image digests and the Windows release directory.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ReleaseAnchor {
agent_id: Uuid,
release_id: Uuid,
agent_sha256: String,
helper_sha256: String,
policy_json: String,
}
impl ReleaseAnchor {
fn policy_for(&self, manifest: &ReleaseManifest) -> Option<String> {
if self.policy_json.len() > 8192
|| self.release_id.is_nil()
|| !digest(&self.agent_sha256)
|| !digest(&self.helper_sha256)
|| self.agent_sha256 == self.helper_sha256
{
return None;
}
let next = |role| {
manifest
.artifacts
.iter()
.find(|a| a.role == role)
.map(|a| a.sha256.as_str())
};
let mut raw = self.policy_json.clone();
let mut replace = |from: String, to: String, count| {
if raw.matches(&from).count() != count {
return None;
}
raw = raw.replace(&from, &to);
Some(())
};
let field = |name: &str, value: &str| format!(r#""{name}":"{value}""#);
match manifest.platform {
Platform::LinuxX64 | Platform::LinuxArm64 => replace(
field("helper_binary_sha256", &self.helper_sha256),
field("helper_binary_sha256", next(ArtifactRole::Helper)?),
1,
)?,
Platform::WindowsGnuX64 => {
replace(
field("binary_sha256", &self.agent_sha256),
field("binary_sha256", next(ArtifactRole::Agent)?),
1,
)?;
replace(
field("binary_sha256", &self.helper_sha256),
field("binary_sha256", next(ArtifactRole::Helper)?),
1,
)?;
let directory = |release| format!(r"\\releases\\{release}\\");
replace(
directory(self.release_id),
directory(manifest.release_id),
2,
)?;
}
_ => return None,
}
Some(rmm_domain::jobs::hash(raw.as_bytes()))
}
}
fn invalid() -> Error {
Error(StatusCode::CONFLICT, "MANAGED_SCRIPT_POLICY_INVALID")
}
// Only a managed device scope can opt in. The authenticated principal remains
// the token ID for authorization, the plan record and audit.
const SCOPED_MCP: &str = "mcp:scoped";
#[derive(Clone, Copy)]
enum HelperBinding {
LocalPins,
VerifiedInstalledRelease,
}
impl Policy {
fn permits(
&self,
principal: &str,
job: &JobPayload,
caps: &[String],
binding: HelperBinding,
) -> bool {
if principal == SCOPED_MCP
|| !matches!(job.action, Action::RunScript { .. })
|| !job.action.full_maintenance()
|| !job.action.validate()
|| !job.action.available_for(&job.execution_identity, caps)
|| !job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
{
return false;
}
let permits_subject = |subject: &str| match job.execution_identity.as_str() {
"root" => self
.linux
.iter()
.any(|scope| scope.permits(subject, job, caps, None)),
"system" => self
.windows
.iter()
.any(|scope| scope.permits(subject, job, caps, false, true, false)),
_ => false,
};
permits_subject(principal)
|| (matches!(binding, HelperBinding::VerifiedInstalledRelease)
&& principal.strip_prefix("mcp:").is_some_and(|id| {
Uuid::parse_str(id).is_ok_and(|uuid| !uuid.is_nil() && uuid.to_string() == id)
})
&& permits_subject(SCOPED_MCP))
}
}
fn binding_error() -> Error {
Error(StatusCode::CONFLICT, "SCRIPT_HELPER_BINDING_INVALID")
}
// Multiple helper roles may coexist on older clients. For the release-managed
// script profile we require exactly one unambiguous release, policy and binary.
fn single_value<'a>(caps: &'a [String], prefix: &str) -> Result<&'a str, Error> {
let mut values = caps.iter().filter_map(|c| c.strip_prefix(prefix));
let value = values.next().ok_or_else(binding_error)?;
if value.is_empty() || values.next().is_some() {
return Err(binding_error());
}
Ok(value)
}
fn check_pair(
manifest: &ReleaseManifest,
version: Option<&str>,
identity: &str,
caps: &[String],
) -> Result<(), Error> {
let platform = match identity {
"root" if caps.iter().any(|cap| cap == LINUX_ARM64_RELEASE_CAPABILITY) => {
Platform::LinuxArm64
}
"root" => Platform::LinuxX64,
"system" => Platform::WindowsGnuX64,
_ => return Err(binding_error()),
};
let binary = single_value(caps, "helper.binary.sha256:")?;
if version != Some(manifest.version.as_str())
|| platform != manifest.platform
|| !digest(single_value(caps, "helper.policy.sha256:")?)
|| !manifest
.artifacts
.iter()
.any(|a| a.role == ArtifactRole::Helper && a.sha256 == binary)
{
return Err(binding_error());
}
Ok(())
}
pub(crate) async fn permits(
tx: &mut Transaction<'_, Postgres>,
principal: &str,
job: &JobPayload,
caps: &[String],
) -> Result<bool, Error> {
if !job.action.full_maintenance() {
return Ok(false);
}
let Some(path) = std::env::var_os("RMM_MANAGED_SCRIPT_POLICY_FILE") else {
return Ok(false);
};
let key = std::env::var_os("RMM_JOB_KEY_FILE").ok_or_else(invalid)?;
let signer = fs::symlink_metadata(key).map_err(|_| invalid())?;
if !signer.is_file() {
return Err(invalid());
}
let bytes = crate::windows_policy::protected_bytes(Path::new(&path), signer.uid())
.map_err(|_| invalid())?;
let policy: Policy = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
if policy.schema_version != 1
|| policy.linux.len() + policy.windows.len() > 64
|| policy.release_anchors.len() > 64
|| policy
.release_anchors
.iter()
.any(|a| a.policy_json.len() > 8192)
|| !policy.windows.iter().all(SystemScope::valid)
{
return Err(invalid());
}
if !caps
.iter()
.any(|cap| cap.starts_with("script.helper.release:"))
{
return Ok(policy.permits(principal, job, caps, HelperBinding::LocalPins));
}
{
let release = Uuid::parse_str(single_value(caps, "script.helper.release:")?)
.map_err(|_| binding_error())?;
if !caps.iter().any(|cap| cap == FULL_MAINTENANCE_CAPABILITY) {
return Err(binding_error());
}
let version: Option<String> = sqlx::query_scalar(
"SELECT reported_agent_version FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL",
)
.bind(job.tenant_id)
.bind(job.agent_id)
.bind(job.asset_id)
.fetch_optional(&mut **tx)
.await?
.flatten();
let manifest = crate::agent_updates::checked_installed_helper_release(tx, release)
.await
.map_err(|err| {
if err.0.is_server_error() {
err
} else {
binding_error()
}
})?;
check_pair(&manifest, version.as_deref(), &job.execution_identity, caps)?;
if policy.permits(
principal,
job,
caps,
HelperBinding::VerifiedInstalledRelease,
) {
return Ok(true);
}
let current_policy = single_value(caps, "helper.policy.sha256:")?;
for anchor in policy
.release_anchors
.iter()
.filter(|a| a.agent_id == job.agent_id)
{
if anchor.policy_for(&manifest).as_deref() != Some(current_policy) {
continue;
}
let original = rmm_domain::jobs::hash(anchor.policy_json.as_bytes());
let mut pinned = caps.to_owned();
pinned.retain(|c| {
!c.starts_with("helper.binary.sha256:") && !c.starts_with("helper.policy.sha256:")
});
pinned.push(format!("helper.binary.sha256:{}", anchor.helper_sha256));
pinned.push(format!("helper.policy.sha256:{original}"));
if policy.permits(
principal,
job,
&pinned,
HelperBinding::VerifiedInstalledRelease,
) {
return Ok(true);
}
}
}
Err(Error(StatusCode::FORBIDDEN, "SCRIPT_HELPER_SCOPE_DENIED"))
}
#[cfg(test)]
mod tests {
use super::*;
use rmm_domain::agent_update::ArtifactDescriptor;
use serde_json::json;
#[test]
fn scoped_mcp_requires_a_device_opt_in_and_the_same_pinned_script_scope() {
let token = "mcp:12345678-abcd-4321-b123-123456789abc";
let verified = HelperBinding::VerifiedInstalledRelease;
let local = HelperBinding::LocalPins;
for (platform, identity, interpreter, script) in [
("linux", "root", "posix_sh", "true\n"),
("windows", "system", "powershell", "Write-Output 'ok'\r\n"),
] {
let mut job = JobPayload {
schema_version: 1,
tenant_id: Uuid::new_v4(),
asset_id: Uuid::new_v4(),
agent_id: Uuid::new_v4(),
enrollment_generation: 1,
assignment_version: 1,
job_id: Uuid::new_v4(),
attempt_id: Uuid::new_v4(),
action: Action::RunScript {
interpreter: interpreter.into(),
script_utf8: script.into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: None,
privileged_script_profile: Some(
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
),
},
execution_identity: identity.into(),
not_before: chrono::Utc::now(),
start_before: chrono::Utc::now() + chrono::Duration::minutes(5),
max_runtime_seconds: 30,
max_output_bytes: 4096,
};
let binary = "ab".repeat(32);
let local_policy = "cd".repeat(32);
let mut caps = vec![
format!("{platform}.base/1"),
format!("helper.{identity}.v1"),
format!("{identity}:run_script"),
"run_script".into(),
"rmm.sync.v1".into(),
FULL_MAINTENANCE_CAPABILITY.into(),
format!("helper.policy.sha256:{local_policy}"),
format!("helper.binary.sha256:{binary}"),
];
let mut scope = json!({
"tenant_id": job.tenant_id, "asset_id": job.asset_id, "agent_id": job.agent_id,
"enrollment_generation": 1, "assignment_version": 1, "principals": ["local:reviewer"],
"helper_policy_sha256": local_policy, "helper_binary_sha256": binary,
"acceptance_evidence_id": Uuid::new_v4(), "allowed_services": [],
"allowed_script_profiles": ["full_maintenance_v1"]
});
if platform == "linux" {
scope["allow_root_scripts"] = json!(true);
scope["allow_reboot"] = json!(false);
} else {
scope["max_runtime_seconds"] = json!(30);
scope["allowed_script_sha256"] = json!([rmm_domain::jobs::hash(script.as_bytes())]);
caps.push("script.powershell/1".into());
}
let mut config = json!({"schema_version": 1, "linux": [], "windows": []});
config[platform] = json!([scope]);
let policy: Policy = serde_json::from_value(config.clone()).unwrap();
assert!(policy.permits("local:reviewer", &job, &caps, verified));
assert!(!policy.permits(token, &job, &caps, verified));
config[platform][0]["principals"] = json!(["local:reviewer", SCOPED_MCP]);
let policy: Policy = serde_json::from_value(config).unwrap();
assert!(policy.permits(token, &job, &caps, verified), "{platform}");
assert!(!policy.permits(token, &job, &caps, local));
assert!(policy.permits("local:reviewer", &job, &caps, local));
assert!(policy.permits("local:reviewer", &job, &caps, verified));
for other in [
SCOPED_MCP,
"local:other",
"mcp:not-a-uuid",
"mcp:00000000-0000-0000-0000-000000000000",
"mcp:12345678ABCD4321B123123456789ABC",
] {
assert!(
!policy.permits(other, &job, &caps, verified),
"{platform}: {other}"
);
}
let mut without_binary = caps.clone();
without_binary.retain(|cap| !cap.starts_with("helper.binary.sha256:"));
assert!(!policy.permits(token, &job, &without_binary, verified));
job.assignment_version += 1;
assert!(!policy.permits(token, &job, &caps, verified));
if platform == "windows" {
job.assignment_version -= 1;
if let Action::RunScript { arguments, .. } = &mut job.action {
arguments.push("other".into());
}
assert!(!policy.permits(token, &job, &caps, verified));
if let Action::RunScript {
script_utf8,
arguments,
..
} = &mut job.action
{
arguments.clear();
*script_utf8 = "Write-Output 'changed'\r\n".into();
}
assert!(!policy.permits(token, &job, &caps, verified));
}
}
}
#[test]
fn signed_helper_is_bound_to_platform_reported_version_and_unambiguous_local_pins() {
let binary = "ab".repeat(32);
let policy = "cd".repeat(32);
let artifact = |role, sha256| ArtifactDescriptor {
role,
sha256,
artifact_id: Uuid::new_v4(),
bytes: 4096,
};
let m = ReleaseManifest {
schema_version: 1,
release_id: Uuid::new_v4(),
release_sequence: 7,
version: "0.1.12".into(),
platform: Platform::WindowsGnuX64,
published_at: 10,
expires_at: 500,
protocol_major: 1,
state_schema: 1,
minimum_updater_version: 2,
artifacts: [
artifact(ArtifactRole::Agent, "ef".repeat(32)),
artifact(ArtifactRole::Helper, binary.clone()),
],
};
// Rollover may substitute signed image pins and their release directory only.
let previous = Uuid::new_v4();
let original_agent = "12".repeat(32);
let original_helper = "34".repeat(32);
let windows = |release: Uuid, agent: &str, helper: &str, runtime: u32| {
format!(
r#"{{"agent":{{"binary":"C:\\releases\\{release}\\agent.exe","binary_sha256":"{agent}"}},"helper":{{"binary":"C:\\releases\\{release}\\helper.exe","binary_sha256":"{helper}"}},"max_runtime_seconds":{runtime}}}"#
)
};
let mut anchor = ReleaseAnchor {
agent_id: Uuid::new_v4(),
release_id: previous,
policy_json: windows(previous, &original_agent, &original_helper, 30),
agent_sha256: original_agent,
helper_sha256: original_helper,
};
let next_agent = &m.artifacts[0].sha256;
let expected = |limit| {
rmm_domain::jobs::hash(windows(m.release_id, next_agent, &binary, limit).as_bytes())
};
assert_eq!(anchor.policy_for(&m), Some(expected(30)));
assert_ne!(anchor.policy_for(&m), Some(expected(120)));
anchor
.policy_json
.push_str(&format!(r#","binary_sha256":"{}""#, anchor.helper_sha256));
assert!(anchor.policy_for(&m).is_none());
let mut caps = vec![
format!("helper.binary.sha256:{binary}"),
format!("helper.policy.sha256:{policy}"),
];
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_ok());
assert!(check_pair(&m, Some("0.1.11"), "system", &caps).is_err());
assert!(check_pair(&m, Some("0.1.12"), "root", &caps).is_err());
caps.push(format!("helper.binary.sha256:{binary}"));
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
caps.remove(0);
caps[1] = format!("helper.binary.sha256:{policy}");
assert!(check_pair(&m, Some("0.1.12"), "system", &caps).is_err());
}
}
+38 -7
View File
@@ -58,6 +58,7 @@ struct Device {
#[serde(deny_unknown_fields)]
struct Plan {
tenant_id: Uuid,
#[schemars(with = "crate::jobs::WebPlanInput")]
input: crate::jobs::PlanRequest,
}
#[derive(Deserialize, schemars::JsonSchema)]
@@ -126,7 +127,7 @@ fn tools() -> Vec<Tool> {
),
tool::<PlanScript>(
"scripts.plan",
"Plan the selected immutable script revision against fixed assets. Submit the returned plan for WebUI approval via operations.submit.",
"Plan the selected immutable script revision against fixed assets. Set input.execution_identity to select agent_service, root on Linux or system on Windows. Omitting it uses the revision default. Submit the plan for WebUI approval via operations.submit.",
),
tool::<Devices>(
"updates.list_releases",
@@ -138,11 +139,11 @@ fn tools() -> Vec<Tool> {
),
tool::<crate::monitoring::LogQuery>(
"logs.query",
"Read stored bounded log evidence, or request a live query as a pending approval operation.",
"Read stored bounded log evidence. Use a script job for a fresh collection.",
),
tool::<Plan>(
"operations.plan",
"Persist immutable exact job plan. No executable jobs are created.",
"Plan a run_script operation for selected devices. The stored script and target list require interactive approval.",
),
tool::<Submit>(
"operations.submit",
@@ -156,10 +157,6 @@ fn tools() -> Vec<Tool> {
"jobs.cancel",
"Request cancellation, not rollback or proof of termination.",
),
tool::<Tenant>(
"sessions.request",
"Unsupported until after MVP; never opens a shell.",
),
]
}
fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, crate::jobs::Error> {
@@ -400,3 +397,37 @@ pub fn routes(r: Router<crate::State>, state: crate::State) -> Router<crate::Sta
r.nest_service("/mcp", service)
.route_layer(middleware::from_fn_with_state(state, guard))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plan_tool_advertises_the_script_wire_contract() {
let tools = tools();
let plan = tools
.iter()
.find(|tool| tool.name == "operations.plan")
.unwrap();
let schema = serde_json::to_string(&plan.input_schema).unwrap();
for field in [
"run_script",
"script_utf8",
"variants",
"execution_identity",
] {
assert!(schema.contains(field), "{field}");
}
for retired in [
"update_agent",
"reboot",
"query_logs",
"apt_manifest",
"windows_msi_manifest",
"dependency_group",
] {
assert!(!schema.contains(retired), "{retired}");
}
assert!(tools.iter().all(|tool| tool.name != "sessions.request"));
}
}
+4 -2
View File
@@ -17,9 +17,10 @@ use std::collections::BTreeSet;
use uuid::Uuid;
const PREFIX: &str = "rmm_mcp_";
const SCOPES: [&str; 11] = [
const SCOPES: [&str; 12] = [
"inventory:read",
"logs:read",
"logs:read_sensitive",
"operations:read",
"operations:plan",
"operations:submit",
@@ -371,7 +372,7 @@ async fn authenticate_pool(
name: principal,
operator: effective
.iter()
.any(|scope| !READ_SCOPES.contains(&scope.as_str())),
.any(|scope| !READ_SCOPES.contains(&scope.as_str()) && scope != "logs:read_sensitive"),
session_hash: None,
csrf: None,
scopes: Some(effective),
@@ -427,6 +428,7 @@ async fn enabled(pool: &PgPool, principal: &str, tenant: Uuid) -> bool {
#[cfg(test)]
mod tests {
use super::*;
mod stored_logs;
#[test]
fn mcp_token_selection_is_explicit_and_bounded() {
@@ -0,0 +1,138 @@
use super::*;
use crate::monitoring::{LogQuery, query};
use std::sync::Arc;
#[tokio::test]
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
async fn stored_results_require_current_log_rights_on_both_read_paths() {
let admin = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_ADMIN_URL").unwrap())
.await
.unwrap();
let pool = PgPool::connect(&std::env::var("RMM_TEST_REPAIR_APP_URL").unwrap())
.await
.unwrap();
let tenant = Uuid::parse_str(rmm_domain::TENANT_A).unwrap();
let foreign = Uuid::parse_str(rmm_domain::TENANT_B).unwrap();
let asset = Uuid::new_v4();
let actor = format!("local:{}", Uuid::new_v4());
let temp = std::env::temp_dir().join(format!("stored-logs-{asset}"));
let state = crate::State {
pool,
signer: None,
viewer_a: [0; 32],
viewer_b: [1; 32],
auth: Arc::new(crate::auth::Auth::from_env("development").await.unwrap()),
job_signer: Arc::new(
crate::job_signer::JobSigner::load_or_create(&temp.join("key.pem")).unwrap(),
),
};
sqlx::query("INSERT INTO memberships(tenant_id,principal,kind,permissions) VALUES($1,$2,'human',ARRAY['tokens:manage','operations:read','logs:read','logs:read_sensitive'])")
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
let mut readers = Vec::new();
for scopes in [
vec!["operations:read"],
vec!["operations:read", "logs:read"],
vec!["operations:read", "logs:read", "logs:read_sensitive"],
] {
let (_, token) = mint(&state.pool, tenant, &actor, &scopes).await;
let p = authenticate_pool(&state.pool, &token, Some(tenant))
.await
.unwrap();
assert!(!p.operator);
readers.push(p);
}
// Terminal history with inert synthetic bytes, no gateway, outbox or permits.
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
.bind(tenant)
.bind(asset)
.execute(&admin)
.await
.unwrap();
sqlx::query("INSERT INTO agent_installations(tenant_id,agent_id,asset_id,certificate_sha256) VALUES($1,$2,$2,$3)").bind(tenant).bind(asset).bind(hash(asset.as_bytes())).execute(&admin).await.unwrap();
let operation = Uuid::new_v4();
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,'{}','fixture',now())").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO approval_requests(tenant_id,operation_id,plan_id,principal,idempotency_key,request_hash,approval_state) VALUES($1,$2,$2,$3,'fixture','fixture','approved')").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO authorizations(tenant_id,authorization_id,operation_id,plan_id,plan_hash,principal,session_hash,approval_origin,testsimulation,policy_version) VALUES($1,$2,$2,$2,'fixture',$3,'fixture','dev_test_browser_simulation',true,1)").bind(tenant).bind(operation).bind(&actor).execute(&admin).await.unwrap();
sqlx::query("INSERT INTO operations VALUES($1,$2,$2)")
.bind(tenant)
.bind(operation)
.execute(&admin)
.await
.unwrap();
let until = Utc::now();
let since = until - Duration::minutes(5);
let query_for = |unit: &str| LogQuery {
tenant_id: tenant,
asset_id: asset,
since: since - Duration::seconds(1),
until: until + Duration::seconds(1),
unit: unit.into(),
max_lines: 10,
live: false,
idempotency_key: None,
};
let stored = json!({"exit_code":0,"stdout":[65],"stderr":[66],"evidence":{"fixture":true},"error_code":"fixture"});
let restricted = json!({"exit_code":0,"output_restricted":true});
let mut secure_job = Uuid::nil();
for (unit, classification) in [
("ordinary.service", Some(false)),
("custom-audit.service", Some(true)),
("legacy.service", None),
] {
let job = Uuid::new_v4();
let bytes = serde_json::to_vec(&json!({"action":{"action":"query_logs","unit":unit,"since":since,"until":until,"max_lines":10}})).unwrap();
sqlx::query("INSERT INTO jobs(tenant_id,job_id,attempt_id,operation_id,agent_id,asset_id,payload,payload_hash,state,resource,result,log_sensitive) VALUES($1,$2,$2,$3,$4,$4,$5,'fixture','succeeded','device_execution',$6,$7)")
.bind(tenant).bind(job).bind(operation).bind(asset).bind(bytes).bind(&stored).bind(classification).execute(&admin).await.unwrap();
for (index, p) in readers.iter().enumerate() {
let permitted = index == 2 || (index == 1 && classification == Some(false));
let detail = crate::jobs::job(&state, p, tenant, job).await.unwrap();
assert_eq!(detail["state"], "succeeded");
assert_eq!(
&detail["result"],
if permitted { &stored } else { &restricted }
);
let logs = query(&state, p, query_for(unit)).await;
if permitted {
assert_eq!(logs.unwrap()["items"][0]["result"], stored);
} else {
assert_eq!(logs.unwrap_err().0, StatusCode::FORBIDDEN);
}
}
if classification == Some(true) {
secure_job = job;
}
}
// Keep the previously authenticated reader and remove just the issuer's
// extra permission. The next read must consult current tenant membership.
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read_sensitive') WHERE tenant_id=$1 AND principal=$2")
.bind(tenant).bind(&actor).execute(&admin).await.unwrap();
let reader = &readers[2];
assert_eq!(
crate::jobs::job(&state, reader, tenant, secure_job)
.await
.unwrap()["result"],
restricted
);
assert_eq!(
query(&state, reader, query_for("custom-audit.service"))
.await
.unwrap_err()
.0,
StatusCode::FORBIDDEN
);
assert_eq!(
crate::jobs::job(&state, reader, foreign, secure_job)
.await
.unwrap_err()
.0,
StatusCode::NOT_FOUND
);
let mut other = query_for("custom-audit.service");
other.tenant_id = foreign;
assert_eq!(
query(&state, reader, other).await.unwrap_err().0,
StatusCode::NOT_FOUND
);
std::fs::remove_dir_all(temp).unwrap();
}
+66 -113
View File
@@ -34,15 +34,45 @@ pub struct LogQuery {
pub since: DateTime<Utc>,
pub until: DateTime<Utc>,
pub max_lines: u32,
#[serde(default)]
#[schemars(skip)]
pub live: bool,
#[schemars(skip)]
pub idempotency_key: Option<String>,
}
/// Both result endpoints use the reader's current token scope and tenant membership.
pub(crate) struct LogReadAccess {
ordinary: bool,
sensitive: bool,
}
impl LogReadAccess {
pub(crate) async fn for_principal(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
p: &crate::auth::Principal,
) -> Result<Self, crate::jobs::Error> {
let ordinary = p.permits_scope("logs:read")
&& crate::permissions::allowed(tx, &p.name, "logs:read").await?;
let sensitive = ordinary
&& p.permits_scope("logs:read_sensitive")
&& crate::permissions::allowed(tx, &p.name, "logs:read_sensitive").await?;
Ok(Self {
ordinary,
sensitive,
})
}
pub(crate) fn permits(&self, stored_sensitivity: Option<bool>) -> bool {
self.ordinary && (stored_sensitivity == Some(false) || self.sensitive)
}
}
pub async fn query(
s: &crate::State,
p: &crate::auth::Principal,
i: LogQuery,
) -> Result<Value, crate::jobs::Error> {
crate::jobs::scope(p, i.tenant_id, true)?;
crate::jobs::scope(p, i.tenant_id, i.live)?;
let action = rmm_domain::jobs::Action::QueryLogs {
unit: i.unit.clone(),
since: i.since,
@@ -56,92 +86,16 @@ pub async fn query(
));
}
if i.live {
let request_hash = rmm_domain::jobs::hash(&serde_json::to_vec(&i)?);
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
let key = i
.idempotency_key
.as_ref()
.filter(|k| !k.is_empty() && k.len() <= 128)
.ok_or(crate::jobs::Error(
StatusCode::BAD_REQUEST,
"VALIDATION_ERROR",
))?;
if let Some(row)=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(key).fetch_optional(&mut *dedup).await?{
if row.get::<String,_>("request_hash")!=request_hash{return Err(crate::jobs::Error(StatusCode::CONFLICT,"IDEMPOTENCY_CONFLICT"))}
let plan=row.get("plan_id");let key=key.clone();dedup.commit().await?;
return crate::jobs::submit(s,p,i.tenant_id,plan,crate::jobs::Submit{idempotency_key:key}).await;
}
dedup.commit().await?;
let key = i.idempotency_key.ok_or(crate::jobs::Error(
StatusCode::BAD_REQUEST,
"VALIDATION_ERROR",
))?;
let plan = crate::jobs::plan(
s,
p,
i.tenant_id,
crate::jobs::PlanInput {
targets: crate::jobs::Targets {
asset_ids: vec![i.asset_id],
},
action,
script_variants: vec![],
execution_identity: "agent_service".into(),
schedule: crate::jobs::Schedule {
not_before: Utc::now(),
start_before: Utc::now() + chrono::Duration::hours(1),
},
max_runtime_seconds: 30,
max_output_bytes: 262144,
rollout: crate::jobs::Rollout {
max_parallel: 1,
halt_after_failures: 1,
},
reason: format!("Requested live logs for {}", i.unit),
artifact_ids: vec![],
},
)
.await?;
let id = plan["plan_id"]
.as_str()
.and_then(|v| Uuid::parse_str(v).ok())
.ok_or(crate::jobs::Error(
StatusCode::INTERNAL_SERVER_ERROR,
"VALIDATION_ERROR",
))?;
let mut dedup = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
sqlx::query(
"INSERT INTO live_query_requests VALUES($1,$2,$3,$4,$5) ON CONFLICT DO NOTHING",
)
.bind(i.tenant_id)
.bind(&p.name)
.bind(&key)
.bind(&request_hash)
.bind(id)
.execute(&mut *dedup)
.await?;
let canonical=sqlx::query("SELECT request_hash,plan_id FROM live_query_requests WHERE principal=$1 AND idempotency_key=$2").bind(&p.name).bind(&key).fetch_one(&mut *dedup).await?;
if canonical.get::<String, _>("request_hash") != request_hash {
return Err(crate::jobs::Error(
StatusCode::CONFLICT,
"IDEMPOTENCY_CONFLICT",
));
}
let id = canonical.get("plan_id");
dedup.commit().await?;
return crate::jobs::submit(
s,
p,
i.tenant_id,
id,
crate::jobs::Submit {
idempotency_key: key,
},
)
.await;
return Err(crate::jobs::Error(
StatusCode::CONFLICT,
"SCRIPT_ACTION_REQUIRED",
));
}
let mut tx = rmm_persistence::tenant_tx(&s.pool, i.tenant_id).await?;
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
let access = LogReadAccess::for_principal(&mut tx, p).await?;
if !access.ordinary {
return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
}
let exists: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM assets WHERE asset_id=$1)")
.bind(i.asset_id)
.fetch_one(&mut *tx)
@@ -149,38 +103,37 @@ pub async fn query(
if !exists {
return Err(crate::jobs::Error(StatusCode::NOT_FOUND, "NOT_FOUND"));
}
let rows=sqlx::query("SELECT j.job_id,j.payload,j.result FROM jobs j WHERE j.asset_id=$1 AND j.state='succeeded' AND j.result IS NOT NULL ORDER BY job_id LIMIT 100").bind(i.asset_id).fetch_all(&mut *tx).await?;
let rows = sqlx::query(
"SELECT job_id, result, log_sensitive, action->>'since' AS observed_from, action->>'until' AS observed_until
FROM jobs CROSS JOIN LATERAL (SELECT convert_from(payload, 'UTF8')::jsonb->'action' AS action) AS log
WHERE asset_id=$1 AND state='succeeded' AND result IS NOT NULL AND action->>'action'='query_logs'
AND action->>'unit'=$2 AND (action->>'since')::timestamptz >= $3 AND (action->>'until')::timestamptz <= $4
ORDER BY job_id LIMIT 101",
).bind(i.asset_id).bind(&i.unit).bind(i.since).bind(i.until).fetch_all(&mut *tx).await?;
let mut items = Vec::new();
let mut size = 0;
let mut lines = 0usize;
let mut truncated = false;
for r in rows {
let payload: rmm_domain::jobs::JobPayload =
serde_json::from_slice(&r.get::<Vec<u8>, _>("payload"))?;
if let rmm_domain::jobs::Action::QueryLogs {
unit, since, until, ..
} = payload.action
&& unit == i.unit
&& since >= i.since
&& until <= i.until
{
let result: Value = r.get("result");
let len = result.to_string().len();
let stdout = result.get("stdout").and_then(Value::as_array);
let count = stdout
.map(|bytes| {
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
})
.unwrap_or(0);
if size + len > 262144 || lines + count > i.max_lines as usize {
truncated = true;
break;
}
size += len;
lines += count;
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":unit,"observed_from":since,"observed_until":until,"result":result}));
let mut truncated = rows.len() > 100;
for r in rows.into_iter().take(100) {
if !access.permits(r.get("log_sensitive")) {
return Err(crate::jobs::Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
}
let result: Value = r.get("result");
let len = result.to_string().len();
let stdout = result.get("stdout").and_then(Value::as_array);
let count = stdout
.map(|bytes| {
bytes.iter().filter(|v| v.as_u64() == Some(10)).count()
+ usize::from(bytes.last().is_some_and(|v| v.as_u64() != Some(10)))
})
.unwrap_or(0);
if size + len > 262144 || lines + count > i.max_lines as usize {
truncated = true;
break;
}
size += len;
lines += count;
items.push(json!({"job_id":r.get::<Uuid,_>("job_id"),"source_id":i.unit,"observed_from":r.get::<String,_>("observed_from"),"observed_until":r.get::<String,_>("observed_until"),"result":result}));
}
tx.commit().await?;
Ok(
+41
View File
@@ -0,0 +1,41 @@
SELECT r.operation_id, r.created_at
FROM approval_requests r JOIN operation_plans p USING (tenant_id, plan_id)
CROSS JOIN LATERAL (SELECT convert_from(p.payload, 'UTF8')::jsonb AS payload) AS plan_view
LEFT JOIN LATERAL (
SELECT count(*) AS total, count(*) FILTER (WHERE state = 'unknown') AS unresolved,
count(*) FILTER (WHERE state = 'succeeded') AS succeeded,
count(*) FILTER (WHERE state = 'cancelled') AS cancelled,
count(*) FILTER (WHERE state IN ('succeeded','failed','cancelled','expired','closed_unknown')) AS terminal,
count(*) FILTER (WHERE state IN ('running','verifying','awaiting_reboot')) AS active
FROM jobs j WHERE j.tenant_id = r.tenant_id AND j.operation_id = r.operation_id
AND $7::text IS NOT NULL AND r.approval_state = 'approved'
) execution ON true
WHERE r.created_at <= $1
AND ($2::timestamptz IS NULL OR (r.created_at, r.operation_id) < ($2, $3))
AND ($4::timestamptz IS NULL OR r.created_at >= $4)
AND ($5::timestamptz IS NULL OR r.created_at < $5)
AND ($6::text IS NULL OR
strpos(lower(coalesce(plan_view.payload#>>'{script_revision,name}', '')), lower($6)) > 0 OR
strpos(lower(coalesce(plan_view.payload->>'reason', '')), lower($6)) > 0)
AND ($7::text IS NULL OR $7 = CASE
WHEN r.approval_state = 'pending_approval' AND p.expires_at <= now() THEN 'expired'
WHEN r.approval_state <> 'approved' OR execution.total = 0 THEN r.approval_state
WHEN execution.unresolved > 0 THEN 'needs_attention'
WHEN execution.succeeded = execution.total THEN 'succeeded'
WHEN execution.terminal = execution.total THEN CASE
WHEN execution.succeeded > 0 THEN 'partially_succeeded'
WHEN execution.cancelled = execution.total THEN 'cancelled' ELSE 'failed' END
WHEN execution.active > 0 THEN 'running' ELSE 'queued'
END)
AND ($8::text IS NULL OR EXISTS (
SELECT 1 FROM jsonb_array_elements(plan_view.payload->'jobs') AS job
LEFT JOIN LATERAL (
SELECT o.data->>'hostname' AS hostname FROM observations o
WHERE $10 AND o.tenant_id = r.tenant_id AND o.agent_id = (job#>>'{payload,agent_id}')::uuid
AND o.source_id IN ('linux.base','windows.base')
ORDER BY o.observed_at DESC, o.received_at DESC, o.sequence DESC LIMIT 1
) inventory ON true
WHERE job#>>'{payload,asset_id}' = $9::uuid::text
OR strpos(lower(coalesce(inventory.hostname, '')), lower($8)) > 0
))
ORDER BY r.created_at DESC, r.operation_id DESC LIMIT $11
+23
View File
@@ -13,9 +13,32 @@ SELECT p.tenant_id, p.name AS customer_name, p.plan_id, p.plan_hash,
p.payload#>>'{jobs,0,payload,action,action}' AS action,
CASE WHEN r.approval_state='pending_approval' AND p.expires_at <= now()
THEN 'expired' ELSE r.approval_state END AS approval_state,
CASE
WHEN decision.event_id IS NOT NULL THEN jsonb_build_object(
'principal', decision.principal, 'at', decision.created_at,
'testsimulation', decision.data->'testsimulation' = 'true'::jsonb)
WHEN r.approval_state = 'approved' AND approved.authorization_id IS NOT NULL THEN jsonb_build_object(
'principal', approved.principal, 'at', approved.created_at,
'testsimulation', approved.testsimulation)
END AS decision,
coalesce(targets.items, '[]'::jsonb) AS targets
FROM selected p
LEFT JOIN approval_requests r USING (tenant_id,plan_id)
LEFT JOIN authorizations approved ON approved.tenant_id = p.tenant_id
AND approved.operation_id = r.operation_id AND approved.plan_id = p.plan_id
LEFT JOIN LATERAL (
SELECT e.event_id, e.principal, e.created_at, e.data
FROM audit_events e
WHERE e.tenant_id = p.tenant_id AND e.data->>'operation_id' = r.operation_id::text
AND e.data->>'plan_id' = p.plan_id::text
AND e.event_type IN ('plan_revoked', 'plan_authorization')
AND ((r.approval_state = 'revoked' AND e.event_type = 'plan_revoked')
OR (e.event_type = 'plan_authorization'
AND e.data->>'plan_hash' = p.plan_hash
AND e.data->>'decision' = CASE r.approval_state WHEN 'approved' THEN 'approve' WHEN 'rejected' THEN 'reject' END))
ORDER BY e.created_at, e.event_id
LIMIT 1
) decision ON true
LEFT JOIN LATERAL (
SELECT jsonb_agg(jsonb_build_object(
'asset_id', j#>>'{payload,asset_id}', 'agent_id', j#>>'{payload,agent_id}',
+57 -21
View File
@@ -20,7 +20,7 @@ pub struct RootPolicy {
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RootScope {
pub(crate) struct RootScope {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
@@ -85,6 +85,15 @@ fn parse_log_units(raw: Option<&str>) -> Result<Option<Vec<String>>, Error> {
}
Ok(Some(units))
}
fn configured_sensitive_units() -> Result<Option<Vec<String>>, Error> {
match std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS") {
Ok(raw) => parse_log_units(Some(&raw)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => {
Err(Error(StatusCode::CONFLICT, "ROOT_LOG_ALLOWLIST_INVALID"))
}
}
}
impl RootLogPolicy {
fn valid(&self) -> bool {
self.schema_version == 1
@@ -92,17 +101,45 @@ impl RootLogPolicy {
&& valid_log_units(&self.sensitive_units)
}
}
impl RootPolicy {
fn sensitive_log_unit(&self, job: &JobPayload, unit: &str, extra: Option<&[String]>) -> bool {
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
|| (unit.starts_with("sshd@") && unit.ends_with(".service"))
|| extra.is_some_and(|units| units.iter().any(|u| u == unit))
// Classification is shared across matching target scopes, not just
// the first scope/actor that grants a unit. Another scope cannot
// silently declassify a sensitive source.
|| self.scopes.iter().any(|scope| scope.matches_target(job)
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit)))
}
fn sensitive_log_unit(
policy: Option<&RootPolicy>,
job: &JobPayload,
unit: &str,
extra: Option<&[String]>,
) -> bool {
matches!(unit, "ssh.service" | "sshd.service" | "auditd.service" | "systemd-logind.service")
|| (unit.starts_with("sshd@") && unit.ends_with(".service"))
|| extra.is_some_and(|units| units.iter().any(|u| u == unit))
// Any matching scope can classify the source, regardless of principal.
|| policy.is_some_and(|p| p.scopes.iter().any(|scope| scope.matches_target(job)
&& scope.root_logs.as_ref().is_some_and(|logs| logs.sensitive_units.iter().any(|u| u == unit))))
}
/// Record the source classification alongside the grant. Readers in a separate
/// API profile cannot reconstruct an expired or replaced gateway policy.
pub(crate) fn stored_log_sensitivity(job: &JobPayload) -> Option<bool> {
let Action::QueryLogs { unit, .. } = &job.action else {
return None;
};
let Ok(extra) = configured_sensitive_units() else {
return Some(true);
};
let policy = if std::env::var_os("RMM_DEV_ROOT_POLICY_FILE").is_some()
|| std::env::var("RMM_DEV_ROOT_ENABLED").as_deref() == Ok("true")
{
let Ok(policy) = load() else {
return Some(true);
};
Some(policy)
} else {
None
};
Some(sensitive_log_unit(
policy.as_ref(),
job,
unit,
extra.as_deref(),
))
}
fn required_permissions(job: &JobPayload, sensitive_log: bool) -> Vec<&'static str> {
let mut permissions = vec!["root:execute"];
@@ -158,7 +195,7 @@ impl RootScope {
&& self.enrollment_generation == job.enrollment_generation
&& self.assignment_version == job.assignment_version
}
fn permits(
pub(crate) fn permits(
&self,
principal: &str,
job: &JobPayload,
@@ -338,6 +375,11 @@ pub async fn authorize(
for permission in required_permissions(job, false) {
crate::permissions::require(tx, principal, permission).await?;
}
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let caps: Vec<String> = serde_json::from_value(caps)?;
if crate::managed_scripts::permits(tx, principal, job, &caps).await? {
return Ok(());
}
let policy = load()?;
let global_log_units = if matches!(job.action, Action::QueryLogs { .. }) {
parse_log_units(std::env::var("RMM_ROOT_LOG_UNITS").ok().as_deref())?
@@ -345,19 +387,13 @@ pub async fn authorize(
None
};
if let Action::QueryLogs { unit, .. } = &job.action {
let sensitive_units = parse_log_units(
std::env::var("RMM_ROOT_SENSITIVE_LOG_UNITS")
.ok()
.as_deref(),
)?;
if policy.sensitive_log_unit(job, unit, sensitive_units.as_deref()) {
let sensitive_units = configured_sensitive_units()?;
if sensitive_log_unit(Some(&policy), job, unit, sensitive_units.as_deref()) {
// Re-read current membership on every planning/approval/start call.
// No policy flag, viewer role, capability or test profile grants it.
crate::permissions::require(tx, principal, "logs:read_sensitive").await?;
}
}
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND enrollment_generation=$3 AND assignment_version=$4").bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let caps: Vec<String> = serde_json::from_value(caps)?;
if !policy
.scopes
.iter()
+71 -3
View File
@@ -38,6 +38,7 @@ pub struct Selection {
pub reason: String,
pub max_runtime_seconds: u32,
pub max_output_bytes: u32,
pub execution_identity: Option<String>,
}
fn script(interpreter: &str, identity: &str, body: String) -> Result<Action, Error> {
@@ -169,7 +170,9 @@ pub async fn plan(
version: row.get("version"),
script_sha256: hash(body.as_bytes()),
};
let identity: String = row.get("execution_identity");
let identity = input
.execution_identity
.unwrap_or_else(|| row.get("execution_identity"));
let action = script(row.get("interpreter"), &identity, body)?;
let plan = PlanInput {
targets: input.targets,
@@ -183,7 +186,7 @@ pub async fn plan(
reason: input.reason,
artifact_ids: vec![],
};
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
jobs::plan_resolved(s, p, tenant, plan, Some(reference)).await
}
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
@@ -259,7 +262,71 @@ 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(), 16);
for (name, interpreter, identity, version) in [
("Linux neu starten", "posix_sh", "root", 1),
("Windows neu starten", "powershell", "system", 2),
] {
let revision = items.iter().find(|r| r["name"] == name && r["version"] == version).unwrap();
assert_eq!(revision["interpreter"], interpreter);
assert_eq!(revision["execution_identity"], identity);
assert_eq!(
revision["script_sha256"],
hash(revision["script_utf8"].as_str().unwrap().as_bytes())
);
}
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,
execution_identity: None,
};
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(
@@ -343,6 +410,7 @@ pub(crate) mod tests {
reason: "isolated library contract".into(),
max_runtime_seconds: 60,
max_output_bytes: 4096,
execution_identity: None,
};
assert_eq!(
plan(s, p, tenant, id, selection(windows))
+5 -3
View File
@@ -51,8 +51,8 @@ fn regular(file: &File, owner: u32, expected_size: u64) -> Result<fs::Metadata>
impl UpdateArtifacts {
pub fn new(profile: &str, root: PathBuf, owner: u32) -> Result<Self> {
ensure!(
profile == "development",
"update object adapter is development-only"
matches!(profile, "development" | "production") && root.is_absolute(),
"release store requires a configured profile and absolute path"
);
Self::private_directory(root, owner)
}
@@ -246,7 +246,9 @@ mod tests {
fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
let owner = fs::metadata(&root).unwrap().uid();
let store = UpdateArtifacts::new("development", root.clone(), owner).unwrap();
assert!(UpdateArtifacts::new("production", root.clone(), owner).is_err());
assert!(UpdateArtifacts::new("production", root.clone(), owner).is_ok());
assert!(UpdateArtifacts::new("unknown", root.clone(), owner).is_err());
assert!(UpdateArtifacts::new("production", PathBuf::from("relative"), owner).is_err());
let tenant = Uuid::new_v4();
let bytes = vec![37_u8; 300_007];
let hash = rmm_domain::jobs::hash(&bytes);
+5 -2
View File
@@ -6,8 +6,10 @@ use axum::{
extract::{Path, Query, State},
http::{HeaderMap, StatusCode},
};
#[cfg(test)]
use rmm_domain::jobs::Action;
use rmm_domain::{
jobs::{Action, ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash},
jobs::{ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash},
windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe},
};
use serde_json::{Value, json};
@@ -72,7 +74,8 @@ pub async fn references(
checked(tx, m).await?;
Ok(vec![reference(m)])
}
pub async fn automatic_artifacts(
#[cfg(test)]
pub(crate) async fn automatic_artifacts(
tx: &mut Transaction<'_, Postgres>,
tenant: Uuid,
action: &Action,
+73 -13
View File
@@ -25,7 +25,7 @@ struct SystemPolicy {
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SystemScope {
pub(crate) struct SystemScope {
tenant_id: Uuid,
asset_id: Uuid,
agent_id: Uuid,
@@ -38,6 +38,8 @@ struct SystemScope {
acceptance_evidence_id: Uuid,
allowed_services: Vec<String>,
#[serde(default, deserialize_with = "strict_optional_hashes")]
allowed_script_sha256: Option<Vec<String>>,
#[serde(default, deserialize_with = "strict_optional_hashes")]
allowed_msi_recipe_sha256: Option<Vec<String>>,
max_runtime_seconds: u32,
#[serde(
@@ -76,7 +78,7 @@ fn fixture_service(name: &str) -> bool {
.all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
}
impl SystemScope {
fn valid(&self) -> bool {
pub(crate) fn valid(&self) -> bool {
!self.tenant_id.is_nil()
&& !self.asset_id.is_nil()
&& !self.agent_id.is_nil()
@@ -97,6 +99,15 @@ impl SystemScope {
.collect::<std::collections::BTreeSet<_>>()
.len()
== self.principals.len()
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
hashes.len() <= 64
&& hashes.iter().all(|h| digest(h))
&& hashes
.iter()
.collect::<std::collections::BTreeSet<_>>()
.len()
== hashes.len()
})
&& self.allowed_services.len() <= 16
&& self
.allowed_services
@@ -127,7 +138,7 @@ impl SystemScope {
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds)
&& (1..=120).contains(&self.max_runtime_seconds)
}
fn permits(
pub(crate) fn permits(
&self,
principal: &str,
job: &JobPayload,
@@ -178,8 +189,16 @@ impl SystemScope {
&& has("system:set_service_state")
&& has("set_service_state")
}
Action::RunScript { .. } => {
Action::RunScript {
script_utf8,
arguments,
..
} => {
allow_scripts
&& self.allowed_script_sha256.as_ref().is_none_or(|hashes| {
arguments.is_empty()
&& hashes.contains(&rmm_domain::jobs::hash(script_utf8.as_bytes()))
})
&& job.action.full_maintenance()
&& (self.allowed_script_profiles.as_ref().is_some_and(|v| {
v.contains(
@@ -293,7 +312,7 @@ fn protected_parent_chain(path: &Path, owner: u32) -> Result<(), Error> {
}
Ok(())
}
fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
pub(crate) fn protected_bytes(path: &Path, owner: u32) -> Result<Vec<u8>, Error> {
no_symlink_components(path)?;
protected_parent_chain(path, owner)?;
let before = fs::symlink_metadata(path).map_err(|_| disabled())?;
@@ -374,9 +393,12 @@ pub async fn authorize(
if matches!(job.action, Action::RunScript { .. }) {
crate::permissions::require(tx, principal, "scripts:execute").await?;
}
let policy = load()?;
let caps:serde_json::Value=sqlx::query_scalar("SELECT capabilities FROM agent_installations WHERE tenant_id=$1 AND agent_id=$2 AND asset_id=$3 AND revoked_at IS NULL AND enrollment_generation=$4 AND assignment_version=$5").bind(job.tenant_id).bind(job.agent_id).bind(job.asset_id).bind(i64::try_from(job.enrollment_generation).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).bind(i64::try_from(job.assignment_version).map_err(|_|Error(StatusCode::CONFLICT,"BINDING_MISMATCH"))?).fetch_optional(&mut **tx).await?.ok_or(Error(StatusCode::CONFLICT,"AUTHORIZATION_REVOKED"))?;
let capabilities: Vec<String> = serde_json::from_value(caps)?;
if crate::managed_scripts::permits(tx, principal, job, &capabilities).await? {
return Ok(());
}
let policy = load()?;
if !policy.permits(principal, job, &capabilities, Utc::now()) {
return Err(Error(
StatusCode::FORBIDDEN,
@@ -566,6 +588,27 @@ mod tests {
policy.schema_version = 3;
assert!(policy.permits("selected", &job, &caps, Utc::now()));
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 = Some(vec![]);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 =
Some(vec![rmm_domain::jobs::hash(b"Write-Output 'hi'\r\n")]);
assert!(policy.permits("selected", &job, &caps, Utc::now()));
let mut changed = job.clone();
if let Action::RunScript { arguments, .. } = &mut changed.action {
arguments.push("unexpected".into());
}
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
if let Action::RunScript {
arguments,
script_utf8,
..
} = &mut changed.action
{
arguments.clear();
script_utf8.push(' ');
}
assert!(!policy.permits("selected", &changed, &caps, Utc::now()));
policy.scopes[0].allowed_script_sha256 = None;
let general = job.action.clone();
job.action = Action::RunScript {
interpreter: "powershell".into(),
@@ -597,13 +640,25 @@ mod tests {
}
#[test]
fn windows_update_window_accepts_only_the_two_fixed_scripts() {
use rmm_domain::jobs::{PrivilegedScriptProfile, WindowsExecutionProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY, WINDOWS_UPDATE_SCRIPT_UTF8};
use rmm_domain::jobs::{
PrivilegedScriptProfile, WINDOWS_UPDATE_IDENTITY_PROBE, WINDOWS_UPDATE_LONG_CAPABILITY,
WINDOWS_UPDATE_SCRIPT_UTF8, WindowsExecutionProfile,
};
let (mut policy, mut job, mut caps) = fixture();
policy.schema_version = 3;
let scope = &mut policy.scopes[0];
scope.allowed_services.clear();
scope.windows_update_max_runtime_seconds = Some(3600);
caps.extend(["run_script", "system:run_script", "script.powershell/1", "script.powershell.process_remote_signed/1", WINDOWS_UPDATE_LONG_CAPABILITY].map(str::to_owned));
caps.extend(
[
"run_script",
"system:run_script",
"script.powershell/1",
"script.powershell.process_remote_signed/1",
WINDOWS_UPDATE_LONG_CAPABILITY,
]
.map(str::to_owned),
);
for (script, seconds, expected) in [
(WINDOWS_UPDATE_SCRIPT_UTF8, 3600, true),
(WINDOWS_UPDATE_IDENTITY_PROBE, 30, true),
@@ -611,13 +666,18 @@ mod tests {
("Write-Output 12", 30, false),
] {
job.action = Action::RunScript {
interpreter:"powershell".into(), script_utf8:script.into(),
arguments:vec![], expected_stdout:None,
windows_execution_profile:Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile:Some(PrivilegedScriptProfile::FullMaintenanceV1),
interpreter: "powershell".into(),
script_utf8: script.into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
};
job.max_runtime_seconds = seconds;
assert_eq!(policy.permits("selected", &job, &caps, Utc::now()), expected);
assert_eq!(
policy.permits("selected", &job, &caps, Utc::now()),
expected
);
}
}
#[test]
+1 -1
View File
@@ -11,7 +11,7 @@ hex.workspace = true
serde_json.workspace = true
uuid.workspace = true
ed25519-dalek = "=2.2.0"
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
rmm-domain = { path = "../domain" }
rmm-agent-core = { path = "../agent-core" }
rmm-updater = { path = "../updater" }
+3 -11
View File
@@ -218,11 +218,7 @@ fn current_keyring(file: &UpdateKeyringFile) -> Result<UpdateKeyring> {
.map_err(|_| anyhow::anyhow!("UPDATE_HISTORY_KEY_SIZE"))?;
keys.push(TrustedUpdateKey::new(
public,
match key.platform {
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
},
key.platform.into(),
key.first_sequence,
key.last_sequence,
key.revoked,
@@ -307,11 +303,7 @@ fn verify_record_release(
.release_envelope
.decode()
.map_err(anyhow::Error::msg)?;
let platform = match record.platform {
Platform::LinuxX64 => ReleasePlatform::LinuxX64,
Platform::WindowsX64 => ReleasePlatform::WindowsX64,
Platform::WindowsGnuX64 => ReleasePlatform::WindowsGnuX64,
};
let platform = ReleasePlatform::from(record.platform);
let envelope: &ReleaseEnvelope = &record.release_envelope;
verify_release(
SignedRelease {
@@ -403,7 +395,7 @@ fn verify_update(
ensure!(
job.execution_identity
== match record.platform {
Platform::LinuxX64 => "root",
Platform::LinuxX64 | Platform::LinuxArm64 => "root",
Platform::WindowsX64 | Platform::WindowsGnuX64 => "system",
}
&& update.release_envelope == record.release_envelope
+1 -1
View File
@@ -16,7 +16,7 @@ serde.workspace = true
serde_json.workspace = true
uuid.workspace = true
libc = "0.2.177"
rusqlite = { version = "0.32.1", features = ["bundled"] }
rusqlite.workspace = true
ed25519-dalek = "=2.2.0"
base64 = "=0.22.1"
rmm-domain = { path = "../domain" }
+1 -1
View File
@@ -45,7 +45,7 @@ mod linux {
let args: Vec<_> = std::env::args_os().skip(1).collect();
if args.first().is_some_and(|arg| arg == "--verify-bootstrap") {
let release =
rmm_updater::verify_bootstrap_files(rmm_updater::Platform::LinuxX64, &args[1..])?;
rmm_updater::verify_bootstrap_files(rmm_domain::agent_update::Platform::NATIVE_LINUX.into(), &args[1..])?;
println!("{}", serde_json::to_string(release.manifest())?);
return Ok(());
}
+2 -7
View File
@@ -4,7 +4,7 @@ use crate::{
VerifiedRelease,
};
use anyhow::{Context, Result, ensure};
use rmm_domain::agent_update::{Platform as WirePlatform, ReleaseEnvelope, UpdateKeyringFile};
use rmm_domain::agent_update::{ReleaseEnvelope, UpdateKeyringFile};
use std::{
ffi::OsString,
fs::File,
@@ -31,18 +31,13 @@ pub fn verify_bootstrap_files(platform: Platform, args: &[OsString]) -> Result<V
.keys
.into_iter()
.map(|key| {
let platform = match key.platform {
WirePlatform::LinuxX64 => Platform::LinuxX64,
WirePlatform::WindowsX64 => Platform::WindowsX64,
WirePlatform::WindowsGnuX64 => Platform::WindowsGnuX64,
};
let raw = hex::decode(key.public_key_hex)?
.try_into()
.ok()
.context("Ed25519 public key length")?;
TrustedUpdateKey::new(
raw,
platform,
key.platform.into(),
key.first_sequence,
key.last_sequence,
key.revoked,
+1 -1
View File
@@ -1,7 +1,7 @@
//! Pure release verification. This crate does not install, stage, start services,
//! grant approval, persist antirollback state, or trust keys from the network.
//!
//! See docs/agent-updater-proposal.md for the separate, unfinished integration.
//! The release catalog and deployment workflow are described in `docs/development.md`.
mod bootstrap;
mod manifest;
+14
View File
@@ -16,12 +16,26 @@ pub const RELEASE_SIGNATURE_DOMAIN: &[u8] = b"rmm.agent-release.v1\0";
pub enum Platform {
#[serde(rename = "x86_64-unknown-linux-gnu")]
LinuxX64,
#[serde(rename = "aarch64-unknown-linux-gnu")]
LinuxArm64,
#[serde(rename = "x86_64-pc-windows-msvc")]
WindowsX64,
#[serde(rename = "x86_64-pc-windows-gnu")]
WindowsGnuX64,
}
impl From<rmm_domain::agent_update::Platform> for Platform {
fn from(platform: rmm_domain::agent_update::Platform) -> Self {
use rmm_domain::agent_update::Platform as WirePlatform;
match platform {
WirePlatform::LinuxX64 => Self::LinuxX64,
WirePlatform::LinuxArm64 => Self::LinuxArm64,
WirePlatform::WindowsX64 => Self::WindowsX64,
WirePlatform::WindowsGnuX64 => Self::WindowsGnuX64,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactRole {
+28 -2
View File
@@ -66,11 +66,18 @@ fn manifest() -> ReleaseManifest {
}
fn verify_bytes(payload: &[u8], context: &TrustedContext) -> anyhow::Result<VerifiedRelease> {
verify_bytes_with_key(payload, context, key(false, 1, 20))
}
fn verify_bytes_with_key(
payload: &[u8],
context: &TrustedContext,
pinned: TrustedUpdateKey,
) -> anyhow::Result<VerifiedRelease> {
let signer = SigningKey::from_bytes(&[41; 32]);
let mut message = RELEASE_SIGNATURE_DOMAIN.to_vec();
message.extend_from_slice(payload);
let signature = signer.sign(&message).to_bytes();
let pinned = key(false, 1, 20);
let key_id = pinned.key_id().to_owned();
verify_release(
SignedRelease {
@@ -166,7 +173,7 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
payload.replacen("{", "{\"schema_version\":1,", 1),
payload.replacen("\"bytes\":11", "\"bytes\":11,\"path\":\"/etc/passwd\"", 1),
payload.replacen("\"release_sequence\":4", "\"release_sequence\":4.0", 1),
payload.replacen("x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu", 1),
payload.replacen("x86_64-unknown-linux-gnu", "riscv64gc-unknown-linux-gnu", 1),
] {
assert!(verify_bytes(changed.as_bytes(), &context()).is_err());
}
@@ -174,6 +181,25 @@ fn signed_noncanonical_unknown_duplicate_and_oversize_payloads_are_rejected() {
assert!(verify_bytes(b"", &context()).is_err());
}
#[test]
fn arm64_release_requires_arm64_context_and_key() {
let mut target = manifest();
target.platform = Platform::LinuxArm64;
let mut context = context();
assert!(verify(&target, &context).is_err());
context.platform = Platform::LinuxArm64;
assert!(verify(&target, &context).is_err());
let arm64_key = TrustedUpdateKey::new(
SigningKey::from_bytes(&[41; 32]).verifying_key().to_bytes(),
Platform::LinuxArm64,
1,
20,
false,
).unwrap();
let payload = serde_json::to_vec(&target).unwrap();
assert!(verify_bytes_with_key(&payload, &context, arm64_key).is_ok());
}
#[test]
fn incompatible_clock_platform_state_protocol_and_trust_contexts_are_rejected() {
let mut ctx = context();
+11 -44
View File
@@ -1,54 +1,21 @@
# Isolated local browser integration — no VM execution
# WebUI im Browser prüfen
`run_pending.py` uses existing test bootstrap helpers to enroll a real mTLS device
fixture on the local dev backend, never a forged database agent identity. It sends
a ClientHello advertising `run_script` only to exercise plan validation; it does
not implement an executor, ask for a permit, authorize or report an execution.
The browser sends a durable pending request via the actual UI. The fixture is
revoked afterwards; its pending request and enrollment history are retained.
An artifact-count guard checks that jobs/outbox/grants did not increase.
## Oberflächentests mit Testdaten
Requirements: initialized/running dev Docker backend on loopback 18443, built UI
served from `web/dist`, public CA `devstate/pki/ca.pem`, private existing browser
login `devstate/browser-login.json` (owned, mode 0600). Credential values are never
CLI arguments, printed or copied into source. No VM credentials are used.
Project-local tools (commands for reproducing setup; actual execution occurred in
the implementation session):
Die Playwright-Spezifikationen für Auftragsdialog, Genehmigungseingang, Kunden und MCP-Tokens starten einen lokalen Testserver und liefern kontrollierte API-Antworten. Sie prüfen die Oberfläche ohne Zugangsdaten und ohne Aufträge auf realen Geräten. Die Befehle beginnen im Repository-Stamm.
```sh
cd web
npm ci --ignore-scripts
PLAYWRIGHT_BROWSERS_PATH="$PWD/node_modules/.cache/playwright-browsers" npx playwright install chromium
mkdir -p node_modules/.cache/nss-tools
cd node_modules/.cache/nss-tools
apt-get download libnss3-tools
dpkg-deb -x libnss3-tools*.deb root
npm ci
export PLAYWRIGHT_BROWSERS_PATH="$PWD/node_modules/.cache/playwright-browsers"
npx playwright install chromium
npm run test:browser -- approval-inbox.spec.ts customer-management.spec.ts mcp-token-management.spec.ts order-composer.spec.ts
```
No package installed globally. The runner uses installed `certutil` if available,
otherwise the locally extracted binary. It imports the **public** CA into isolated
`web/node_modules/.cache/browser-home/.pki/nssdb`, with browser HOME restricted to
that directory. Existing global browser/user trust and hosts files are untouched.
DNS overrides map only fixed test names to 127.0.0.1; TLS/SNI still verifies the
original DNS name. No certificate bypass flag or ignoreHTTPS option exists.
Die [Playwright-Konfiguration](../../web/playwright.config.ts) verwendet einen Worker und den projektspezifischen Reporter. Bei Tests mit Zugangsdaten die vorgegebenen Einstellungen für Reporter, Trace, Video und Screenshots verwenden. Private Browserdaten und Fehlerartefakte liegen im lokalen Cache.
From repository root:
## Abnahme auf Testgeräten
```sh
python3 deploy/browser/run_pending.py
```
Für den fachlichen Ende-zu-Ende-Nachweis auf einem Testgerät den gespeicherten Plan prüfen, die persönliche WebUI-Entscheidung abwarten und das Ergebnis des gebundenen Versuchs auswerten. Bei einem Neustart zusätzlich Bootwechsel, erneuten authentisierten Kontakt und Erfolg des Folgeauftrags erfassen. Die Nachweise für Linux und Windows enthalten Plan-, Auftrags- und Versuchskennungen. [Produktabnahme](../../docs/mvp-completion-plan.md)
Real Playwright tests verify normal trusted HTTPS plus rejection of wrong DNS name
and an untrusted CA. The positive UI case only plans/submits and never clicks
approval. CSRF is tested by deleting the token from an actual logout UI request;
403 and continued session visibility are required, followed by valid logout.
No direct API/DB approval path is used. Reporter suppresses raw errors, action logs,
stdout/stderr; traces/screenshots/video are off. Failure artifacts remain private
and must not be published. Sanitized evidence records booleans/statuses only, no
hostnames/keys/passwords. Bounded retries are not automatic: a failing run fails;
a separate rerun must reauthenticate and creates a new explicit pending plan.
`RMM_E2E_MODE=execute` is an additional separate opt-in for the prepared positive
approval/result test, to use only after a real authorized agent path is ready.
This pending-only run is neither native VM evidence nor positive approval proof.
Ein simulierter Testprincipal ist ausschließlich im getrennten dev/test-Profil zulässig. Dessen WebUI und Audit kennzeichnen die Simulation. Den internen Entwicklungszugang und dessen eigene TLS-Vertrauensstellung beschreibt die [Betriebsanleitung](../../docs/operations-access.md).

Some files were not shown because too many files have changed in this diff Show More