Compare commits
62
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb2376443c | ||
|
|
f2a2d44d84 | ||
|
|
7215ea9733 | ||
|
|
b5907d681d | ||
|
|
4b3d0136e9 | ||
|
|
bfdc3da8af | ||
|
|
6d15f1b3f5 | ||
|
|
8b5365f4bc | ||
|
|
247646a2ba | ||
|
|
11a67ca9a4 | ||
|
|
f1538143cf | ||
|
|
c599baa494 | ||
|
|
6963ad332c | ||
|
|
f37b6dc4f7 | ||
|
|
92e2050935 | ||
|
|
c4e064773b | ||
|
|
5bf844d850 | ||
|
|
e5006b3ecb | ||
|
|
1d58f2e704 | ||
|
|
bb4e7cbad7 | ||
|
|
acbff0060d | ||
|
|
7dccb204ec | ||
|
|
fa71f44c36 | ||
|
|
5889964ea1 | ||
|
|
55fad07327 | ||
|
|
4afa6e4a12 | ||
|
|
fb07e4b548 | ||
|
|
0f70d8d8f5 | ||
|
|
cd80bfc704 | ||
|
|
adc04f0148 | ||
|
|
c692316abe | ||
|
|
ab20cb0778 | ||
|
|
53c713aa3a | ||
|
|
9c7ccbb59b | ||
|
|
0b07baf7be | ||
|
|
07154833b3 | ||
|
|
374b7e42d6 | ||
|
|
663e846415 | ||
|
|
7ddd579888 | ||
|
|
b8e4b32a33 | ||
|
|
17f2e6dc91 | ||
|
|
6d4f53dcae | ||
|
|
a0b3aa46f5 | ||
|
|
72d95dee11 | ||
|
|
0f15f91f65 | ||
|
|
db2f5b407d | ||
|
|
3e6ce7f07c | ||
|
|
7cec566dfe | ||
|
|
9e913b7a51 | ||
|
|
97ef5783c1 | ||
|
|
f8e5865412 | ||
|
|
61688bcd4b | ||
|
|
14a271f61a | ||
|
|
5b6e9c9cdb | ||
|
|
c0754f1d0d | ||
|
|
973e131c86 | ||
|
|
ea87d8141c | ||
|
|
2712c4f80e | ||
|
|
8e770c6378 | ||
|
|
f6e658ce35 | ||
|
|
a397dd7ae4 | ||
|
|
984c730f5d |
@@ -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
+47
-128
@@ -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",
|
||||
@@ -2239,7 +2213,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmm-agent-windows"
|
||||
version = "0.1.0"
|
||||
version = "0.1.16"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
@@ -2315,7 +2289,9 @@ name = "rmm-persistence"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"sqlx",
|
||||
"sqlx-core",
|
||||
"sqlx-macros",
|
||||
"sqlx-postgres",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
@@ -2538,17 +2514,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 +2857,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 +2868,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 +2886,7 @@ checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
|
||||
dependencies = [
|
||||
"sqlx-core",
|
||||
"sqlx-macros",
|
||||
"sqlx-mysql",
|
||||
"sqlx-postgres",
|
||||
"sqlx-sqlite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2966,58 +2957,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 +3002,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
@@ -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"] }
|
||||
|
||||
@@ -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
@@ -19,7 +19,7 @@ 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
|
||||
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 })
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 ¤t {
|
||||
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
|
||||
@@ -1170,6 +1171,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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -4,6 +4,7 @@ use crate::{
|
||||
actions::{ServiceUnit, reboot_required},
|
||||
process,
|
||||
};
|
||||
use rmm_domain::inventory_document::DeviceType;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
ffi::{CStr, CString},
|
||||
@@ -257,6 +258,8 @@ 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,
|
||||
}
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct LinuxInventory {
|
||||
@@ -1116,7 +1119,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 +1164,21 @@ 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);
|
||||
if readable_dmi.is_empty() && device_type.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,
|
||||
},
|
||||
)
|
||||
.partial("NO_SMART_OR_ENCRYPTION_PROOF")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1362,6 +1400,26 @@ mod tests {
|
||||
assert_eq!(request.since_filter, "@100.123457");
|
||||
assert_eq!(request.until_filter, "@101.987654");
|
||||
}
|
||||
#[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);
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! uninstall commands; registry entries are evidence, not verified MSI state.
|
||||
use anyhow::{Result, ensure};
|
||||
use chrono::Utc;
|
||||
use rmm_domain::inventory_document::DeviceType;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
mem::{size_of, zeroed},
|
||||
@@ -64,6 +65,82 @@ fn text(key: HKEY, name: &str) -> Result<Option<String>> {
|
||||
Ok(Some(String::from_utf16(&data[..count - 1])?))
|
||||
}
|
||||
|
||||
#[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() -> Option<DeviceType> {
|
||||
let hyper_v_host = open(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
r"SYSTEM\CurrentControlSet\Services\vmms",
|
||||
KEY_WOW64_64KEY,
|
||||
)
|
||||
.is_ok();
|
||||
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())
|
||||
};
|
||||
classify_machine(
|
||||
hyper_v_host,
|
||||
non_microsoft_hypervisor(),
|
||||
read("SystemManufacturer").as_deref(),
|
||||
read("SystemProductName").as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
fn hardware() -> Result<Value> {
|
||||
let mut system: SYSTEM_INFO = unsafe { zeroed() };
|
||||
unsafe {
|
||||
@@ -91,7 +168,7 @@ fn hardware() -> Result<Value> {
|
||||
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()}),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -197,7 +274,7 @@ pub fn observations() -> Vec<Value> {
|
||||
[
|
||||
(
|
||||
"windows.hardware",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor",
|
||||
"windows.win32:GetNativeSystemInfo+GlobalMemoryStatusEx;registry:CentralProcessor,BIOS,vmms;cpuid",
|
||||
hardware as Provider,
|
||||
),
|
||||
(
|
||||
@@ -226,3 +303,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -250,16 +250,20 @@ 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])?)
|
||||
}
|
||||
|
||||
pub fn snapshot() -> 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;
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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,20 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
|
||||
])
|
||||
}
|
||||
impl Config {
|
||||
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 +115,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 {
|
||||
@@ -817,7 +834,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,
|
||||
@@ -1405,8 +1423,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
|
||||
@@ -1558,9 +1575,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 +1587,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 +1792,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")]
|
||||
{
|
||||
@@ -2619,9 +2653,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"))]
|
||||
@@ -3067,6 +3104,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::<()>();
|
||||
|
||||
@@ -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)?,
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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
@@ -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")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -425,15 +425,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 +439,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 +465,8 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
"heartbeat/1".into(),
|
||||
"agent.update/1".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,15 +476,7 @@ 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());
|
||||
}
|
||||
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||
}
|
||||
capabilities.sort();
|
||||
capabilities.dedup();
|
||||
@@ -670,8 +657,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 +733,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 +740,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);
|
||||
@@ -802,18 +778,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
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
//! 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;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum DeviceType {
|
||||
Physical,
|
||||
Virtual,
|
||||
Hypervisor,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Observation {
|
||||
@@ -66,7 +75,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)
|
||||
{
|
||||
|
||||
@@ -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
@@ -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,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
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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" }
|
||||
|
||||
|
||||
@@ -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()),
|
||||
|
||||
@@ -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.
|
||||
@@ -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")
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
@@ -418,15 +415,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)
|
||||
@@ -586,11 +621,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 +648,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 +777,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 +790,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 +1116,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 +1211,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 +1333,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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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)
|
||||
|
||||
@@ -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 {
|
||||
@@ -266,8 +493,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 +504,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 +515,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 +537,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 +545,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 +561,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 +581,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 +622,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 +651,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 +680,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':
|
||||
|
||||
@@ -23,9 +23,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 +51,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");
|
||||
|
||||
@@ -14,7 +14,9 @@ pub(super) 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?;
|
||||
}
|
||||
|
||||
@@ -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,7 @@ 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}/archive",
|
||||
post(archive_device),
|
||||
@@ -33,7 +34,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 +128,53 @@ 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,
|
||||
}
|
||||
|
||||
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?;
|
||||
|
||||
@@ -10,6 +10,7 @@ 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};
|
||||
@@ -240,7 +241,16 @@ pub async fn detail(
|
||||
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,17 @@ fn volumes(data: &Value) -> Value {
|
||||
}
|
||||
items.into()
|
||||
}
|
||||
fn device_type(hardware: &Value) -> Option<DeviceType> {
|
||||
DeviceType::deserialize(&hardware["device_type"]).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());
|
||||
@@ -332,6 +352,8 @@ fn project(row: &PgRow, now: DateTime<Utc>, full: bool) -> 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 device_type =
|
||||
device_type(observed(&data, "linux.hardware")).or_else(|| device_type(windows));
|
||||
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,7 +368,7 @@ 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()),
|
||||
@@ -402,6 +424,21 @@ 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);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "requires the disposable RLS database from tests/local_access_database.py"]
|
||||
async fn visibility_is_filtered_before_the_cursor_limit() {
|
||||
|
||||
@@ -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)
|
||||
|
||||
+366
-424
File diff suppressed because it is too large
Load Diff
@@ -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()
|
||||
}
|
||||
@@ -27,6 +27,7 @@ mod oidc;
|
||||
mod pagination;
|
||||
mod permissions;
|
||||
mod root_policy;
|
||||
mod managed_scripts;
|
||||
mod scheduler;
|
||||
mod script_library;
|
||||
mod synchronization;
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
@@ -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(
|
||||
|
||||
@@ -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
|
||||
@@ -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}',
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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(());
|
||||
}
|
||||
|
||||
@@ -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,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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
@@ -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).
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
|
||||
prepare is offline. inspect/status are remote read-only. build/deploy each launch
|
||||
one durable, create-once case worker. Lost replies permit status only, not retry.
|
||||
The notebook never runs an RMM server/client. Existing deployment tools remain
|
||||
unchanged. See docs/script-console-cloud-upgrade-v1.md before actual use.
|
||||
The current server deployment workflow is documented in docs/development.md.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
|
||||
prepare is offline. inspect/status are remote read-only. build/deploy each launch
|
||||
one durable, create-once case worker. Lost replies permit status only, not retry.
|
||||
The notebook never runs an RMM server/client. Existing deployment tools remain
|
||||
unchanged. See docs/script-console-cloud-upgrade-v2.md before actual use.
|
||||
The current server deployment workflow is documented in docs/development.md.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
|
||||
+18
-269
@@ -1,277 +1,26 @@
|
||||
# Linux agent/helper bootstrap contract (not a VM acceptance)
|
||||
# Linux-Agent betreiben
|
||||
|
||||
**Current integrated runtime contract:** [runtime-README.md](runtime-README.md).
|
||||
The module-only blockers and integration steps below record the earlier increments;
|
||||
they are historical and superseded by that runtime document. In particular Sync,
|
||||
HTTPS, rotation and authenticated helper apply are now wired in source, not VM-
|
||||
accepted. Use the current document and installed units for new bootstrap work.
|
||||
Der Linux-Client für `x86_64-unknown-linux-gnu` meldet sich ausgehend per mTLS am Gerätegateway. Als Systembenutzer `rmm-discovery` liefert er Heartbeats und Inventar, holt genehmigte Shell-Skripte ab und meldet Ausgabe und Exitcode zurück. Der optionale Root-Helper gehört zur gleichen signierten Releaseversion wie der Agent.
|
||||
|
||||
Dedicated APT runner, exact config/unit/CLI/readiness/agent-routing preflight:
|
||||
[`apt-helper-README.md`](apt-helper-README.md). This newer profile does not weaken
|
||||
the existing general/readiness helper unit. Native VM measurements remain open.
|
||||
## Installation
|
||||
|
||||
No install/start/reboot command in this document has been executed on the VM.
|
||||
No RustDesk component is installed. Deploy only the artifacts/configuration for
|
||||
the explicitly agreed test; do not copy central signing/TLS private keys.
|
||||
1. In der WebUI den Zielkunden wählen, **Gerät aufnehmen** öffnen und einen Einmalcode erzeugen.
|
||||
2. Auf dem x86-64-Linux-Gerät mit systemd und Python 3 den dort angezeigten Linux-Befehl ausführen. Er lädt `/install/linux.sh` über HTTPS und ruft es mit `sudo sh` und dem Bootstrap-Ursprung des Servers auf. Den Einmalcode am verdeckten Prompt eingeben.
|
||||
3. Für Root-Skripte die Administratoroption der WebUI wählen. Sie ergänzt `--enable-admin-scripts`. Auf einem bereits eingeschriebenen Gerät lässt sich der Installer mit demselben Ursprung und dieser Option erneut ausführen. Die Geräteidentität bleibt erhalten.
|
||||
4. Im Gerätedetail Hostname, Kunde, Agentversion und letzten authentisierten Kontakt kontrollieren. Für einen Root-Auftrag braucht das Gerät den gemeldeten Root-Kontext und eine passende zentrale Geräteregel. Ein MCP-Token benötigt zusätzlich die passenden Rechte für diesen Kunden. [MCP-Zugang](../../docs/public-access.md)
|
||||
|
||||
## Built artifacts and process configuration
|
||||
## Selbstupdate und Diagnose
|
||||
|
||||
Planned build command (the debug test/build commands actually executed are listed
|
||||
in `tests/agent_jobs/README.md`):
|
||||
`rmm-discovery-update.timer` ruft den Releasebestand nach dem Booten und anschließend alle fünf Minuten mit einer zufälligen Verzögerung von bis zu 20 Sekunden ab. Vor dem Wechsel prüft der Updater das signierte Paket und die Auftragsjournale. Eine neue Generation wird durch den frischen Kontakt des Agenten bestätigt. Scheitert die Aktivierung, wählt der Updater den Vorgänger. Ein über den Installer aktivierter Helper wechselt zusammen mit dem Agenten. [Installer und Aktualisierungslogik](../../crates/server/src/bootstrap/lifecycle.py)
|
||||
|
||||
```sh
|
||||
cargo build --release -p rmm-agent -p rmm-privileged-helper
|
||||
```
|
||||
| Am Gerät prüfen | Befehl oder Pfad |
|
||||
| --- | --- |
|
||||
| Agent und letzter Update-Lauf | `systemctl status rmm-discovery-agent.service rmm-discovery-update.timer` und `journalctl -u rmm-discovery-update.service -n 50` |
|
||||
| Installierter Root-Helper | `systemctl status rmm-discovery-managed-script-helper.service` |
|
||||
| Aktive Generation | `readlink -f /opt/rust-discovery-client/current` |
|
||||
| Zustand und Identität | `/var/lib/rmm-discovery` gehört dem Dienstkonto. Bei einem Binärwechsel bleiben Gerätedaten, Schlüssel und Journal erhalten. |
|
||||
| Tatsächlicher Neustart | `cat /proc/sys/kernel/random/boot_id` vor und nach dem Neustart vergleichen. Anschließend denselben Agenten am Gateway und das Ergebnis eines nachfolgenden Skripts prüfen. |
|
||||
|
||||
Both binaries are environment-configured, **not** positional-argument CLIs.
|
||||
Die Bibliotheksrevision „Linux neu starten“ kündigt den Neustart mit einer Minute Vorlauf an. Eine Datei unter `/tmp` kann beim Booten gemäß lokaler Systemkonfiguration verschwinden. Für die Beurteilung eines Auftrags zählt die Ausgabe seines konkreten Versuchs. [Native MCP-Abnahme](../../docs/evidence/mcp-scoped-script-requests-20261118.json)
|
||||
|
||||
Agent: `RMM_AGENT_STATE` (default `devstate/agent`), `RMM_CA_FILE` (default
|
||||
`devstate/pki/ca.pem`), `RMM_CONNECT_ADDR` (default `127.0.0.1:18443`),
|
||||
`RMM_ENROLLMENT_TOKEN_FILE` (first registration only), and optional
|
||||
`RMM_JOB_BINDING_FILE`, plus optional `RMM_HELPER_SOCKET` for explicit-root grants.
|
||||
The TCP override never changes the TLS DNS/SNI name
|
||||
`rmm-dev.internal`. No proxy or invalid-certificate bypass. Without a binding,
|
||||
the agent remains passive. It refuses to advertise/execute actions as UID 0.
|
||||
|
||||
Provision a dedicated unprivileged `rmm-agent` system account/group. Install the
|
||||
agent binary root-owned and non-writable by that account at
|
||||
`/usr/local/libexec/rmm-agent`. State must be owned by that account, mode 0700;
|
||||
its files are 0600. The sample service uses systemd `StateDirectory` and no
|
||||
ambient capabilities. Install only the public CA at `/etc/rmm/ca.pem`. An
|
||||
optional root-owned 0600 `/etc/rmm/agent.env` supplies the first-enrollment token
|
||||
**path**, never an inline token. Remove that bootstrap token after registration.
|
||||
Retain the enrolled VM-generated private device key on the VM.
|
||||
|
||||
The operator must provision the job signing key over the authenticated bootstrap
|
||||
channel: authenticated `GET https://rmm-dev.internal:18443/api/v1/job-signing-key`
|
||||
using the verified CA, checking `algorithm == "Ed25519"`, `schema_version == 1`,
|
||||
32-byte `public_key_hex` and `key_id == SHA256(raw_public_key)`. Do not trust a key
|
||||
sent alongside a job, use an unauthenticated GET, put bearer credentials in
|
||||
command arguments, or substitute TLS/update keys. This increment does not
|
||||
rotate this trust anchor. Optional automatic agent fetching is described below;
|
||||
the helper remains independently provisioned. The authenticated operator/bootstrap
|
||||
must also resolve the enrolled agent's tenant, asset, generation and assignment
|
||||
from server records, not accept an offer as identity provisioning.
|
||||
|
||||
Agent binding JSON, owned by `rmm-agent`, 0600, in a root-owned configuration
|
||||
directory (replace every placeholder; invalid placeholders intentionally fail):
|
||||
|
||||
```json
|
||||
{
|
||||
"tenant_id": "PROVISIONED-TENANT-UUID",
|
||||
"asset_id": "ENROLLED-ASSET-UUID",
|
||||
"agent_id": "ENROLLED-AGENT-UUID",
|
||||
"enrollment_generation": 1,
|
||||
"assignment_version": 1,
|
||||
"public_key_hex": "AUTHENTICATED-32-BYTE-KEY-IN-HEX"
|
||||
}
|
||||
```
|
||||
|
||||
The agent additionally compares asset/agent IDs to its enrollment response.
|
||||
Generation/assignment changes require an authenticated re-provisioning procedure,
|
||||
not an in-band config assertion. State lock, integrity check and journal capacity
|
||||
errors fail closed; never delete journal/consumption files to force a retry.
|
||||
|
||||
## Independent helper boundary
|
||||
|
||||
Helper: `RMM_HELPER_CONFIG`, default `/etc/rmm/helper.json`. It requires UID 0,
|
||||
a root-owned 0600 config, root-owned private 0700 state directory, and a
|
||||
root-owned socket parent not writable by group/others. `/run/rmm-helper` may be
|
||||
0750 with group `rmm-agent`. The root-owned socket is 0660 with the configured
|
||||
group; `SO_PEERCRED` additionally requires **exactly** the configured non-root
|
||||
agent UID. Group membership alone grants no execution authority.
|
||||
|
||||
Example `/etc/rmm/helper.json` (root:root, 0600):
|
||||
|
||||
```json
|
||||
{
|
||||
"binding": {
|
||||
"tenant_id": "PROVISIONED-TENANT-UUID",
|
||||
"asset_id": "ENROLLED-ASSET-UUID",
|
||||
"agent_id": "ENROLLED-AGENT-UUID",
|
||||
"enrollment_generation": 1,
|
||||
"assignment_version": 1,
|
||||
"public_key_hex": "AUTHENTICATED-32-BYTE-KEY-IN-HEX"
|
||||
},
|
||||
"agent_uid": 12345,
|
||||
"socket_gid": 12345,
|
||||
"socket": "/run/rmm-helper/control.sock",
|
||||
"state": "/var/lib/rmm-helper",
|
||||
"allowed_services": ["rmm-acceptance.service"],
|
||||
"allow_reboot": false,
|
||||
"allow_root_scripts": false
|
||||
}
|
||||
```
|
||||
|
||||
Use the actual dedicated account's numeric UID/GID, not the example numbers.
|
||||
The helper re-verifies exact Ed25519 bytes, all identity/hash/action/parameter
|
||||
bindings, a <=60-second grant interval, synchronized bounded host clock, explicit
|
||||
`execution_identity:"root"`, local action policy and its **own** SQLite consumption
|
||||
ledger before invoking the typed OS provider. A request-provided bearer, key or
|
||||
identity assertion is never an authority. The config has a separate, default-off
|
||||
root-script permission; enabling it is consciously broad administration, still
|
||||
subject to the sample service sandbox. Only exact allowed service units with
|
||||
running/stopped state and >=180s runtime are accepted; restart is not silently
|
||||
rewritten as start. Reboot is default-off and never yields exit-code success.
|
||||
|
||||
IPC framing: one big-endian u32 length plus JSON `Request` (<=512 KiB) per Unix
|
||||
connection. Fields are `job_bytes`, `permit_bytes`, `signature` (JSON byte arrays),
|
||||
`plan_hash`, `authorization_id`. Response has the same framing and an `Outcome`.
|
||||
Read/write deadlines are 5s. No request errors/secrets are echoed. The server
|
||||
process is serial; unknown effects retain its global device resource lock, even
|
||||
after restart. Duplicate consumed grants return stored evidence/unknown, never
|
||||
execute again. A new grant for an already consumed attempt is also refused.
|
||||
The helper refuses a preexisting socket; systemd removes its RuntimeDirectory
|
||||
on stop. Manual stale-socket recovery requires checking that no helper is alive,
|
||||
not blindly unlinking a path at startup.
|
||||
|
||||
## Explicit integration/acceptance blockers
|
||||
|
||||
* Backend currently permits only `agent_service`. Network agent intentionally
|
||||
advertises only `run_script` and `refresh_inventory`, not privileged actions.
|
||||
Network-agent → Unix-helper invocation is wired for explicit-root signed jobs
|
||||
when `RMM_HELPER_SOCKET` is configured, with root socket/peer authentication.
|
||||
A backend-authorized explicit root identity plus helper capability negotiation
|
||||
must land before service/reboot/root-script E2E tests. Helper policy denies
|
||||
unconfigured actions independently; the agent never relabels a service-identity
|
||||
grant into root authority.
|
||||
* Real APT mutation remains unsupported. A simulation followed by `apt-get`
|
||||
cannot guarantee exact approved resolution under dpkg fcntl locks or suppress
|
||||
arbitrary maintainer-script reboots. Neither `ensure_package` nor
|
||||
`apply_updates` is advertised. No false flock-on-dpkg-lock implementation.
|
||||
* No backend SyncRequest/Response exists. Only the **first** authenticated session
|
||||
of a journal may start effects. On reconnect/restart new effects are blocked;
|
||||
in-flight reservations become unknown, durable evidence still replays and
|
||||
heartbeats remain fresh. No DB deletion/new-grant shortcut. Existing previously
|
||||
connected state also needs real synchronization before jobs can be enabled.
|
||||
* Running-script cancellation is recorded but not claimed as confirmed abort;
|
||||
bounded execution finishes and reports its real result. A reboot does not
|
||||
complete without authenticated new-boot evidence; automatic reboot recovery
|
||||
synchronization is not implemented.
|
||||
* Extended collectors now map to bounded per-source observations inside the
|
||||
existing `linux.base` JSON, not new protobuf scopes/tags. Enable only after
|
||||
backend JSON-extension acceptance is confirmed, as described below.
|
||||
* No VM deployment, systemd install, root action, package/update/reboot host
|
||||
effects or real UI approval were performed by this increment.
|
||||
|
||||
## Additional environment variables and bootstrap (second increment)
|
||||
|
||||
* `RMM_JOB_SIGNING_KEY_BOOTSTRAP=1`: after enrollment, use **device mTLS** to GET
|
||||
`/api/v1/job-signing-key` over verified TLS. DNS/SNI remains `rmm-dev.internal`;
|
||||
`RMM_CONNECT_ADDR` changes TCP only. Built-in roots, proxies and redirects are
|
||||
disabled. The response is bounded to 4096 bytes and Ed25519/schema/key-hash
|
||||
checked. No bearer is copied into the agent. A preconfigured binding key must
|
||||
match; an empty key allows initial authenticated provisioning. The resulting
|
||||
`RMM_AGENT_STATE/job-signing-key.json` is private and create-only. A changed
|
||||
existing pin **fails**, never silently rotates. Keep the bootstrap flag enabled
|
||||
on subsequent starts when the binding's key is empty, so the endpoint is
|
||||
reauthenticated and checked against the cached pin. If the current backend
|
||||
endpoint accepts bearer identity only, bootstrap fails closed; backend must
|
||||
explicitly authorize the authenticated enrolled device at that endpoint.
|
||||
* Helper config optional `"signing_key_file":"/etc/rmm/helper-signing-key.json"`:
|
||||
root-owned 0600 JSON with `key_id`, `algorithm`, `schema_version`,
|
||||
`public_key_hex` in the GET response shape. Provision via the trusted operator
|
||||
bootstrap, **not** from an agent-provided file/path/request. If an inline helper
|
||||
binding key is present it must match. The helper has no network key-fetch or
|
||||
auto-replacement operation; agent cache changes cannot change helper trust.
|
||||
* `RMM_LOG_UNITS_FILE`: private, agent-owned 0600 JSON array of 1–128 exact
|
||||
`.service` names. `query_logs` is advertised only when this allowlist and a
|
||||
native journald executable/runtime exist. The signed action must bind an
|
||||
allowlisted unit, nonnegative UTC window <=24h, <=1000 lines, >=20s runtime and
|
||||
bounded output. No arbitrary paths or caller-defined journal arguments.
|
||||
Access/JSON/output failures retain quality/error metadata. The current action
|
||||
has **no cursor input field**; no cursor is fabricated or advanced. Results
|
||||
explicitly report `cursor_status:not_advanced_no_ack_contract` and partial
|
||||
coverage until a concrete durable cursor-ACK contract exists.
|
||||
* `RMM_EXTENDED_INVENTORY=1`: opt-in additive snapshot JSON fields `observations`,
|
||||
`collection_started_at`, `collection_completed_at`. Every observation has
|
||||
`scope`, source, real RFC3339 observation time, quality, completeness,
|
||||
truncation, error and data. CPU, memory, OS, interfaces, routes, DNS, volumes,
|
||||
installed packages, local update metadata and DMI are mapped; SMART remains
|
||||
explicitly unsupported. Per-scope output is <=32 KiB and entire data <=512 KiB.
|
||||
**Do not enable against a gateway deserializing the old deny-unknown-fields
|
||||
Inventory struct.** Confirm backend storage accepts these additive JSON fields
|
||||
first. Default remains compatible base JSON; no wire/protocol file changed.
|
||||
|
||||
Passive collection now runs in one bounded-inflight blocking worker with a
|
||||
bounded completion channel, not inside the network/heartbeat loop. A reconnect
|
||||
does not spawn a second collector while one is already running. A refresh job
|
||||
still collects a **new** base observation for its signed `linux.base` scope;
|
||||
it never returns an old stored passive snapshot as a live measurement.
|
||||
|
||||
Awaiting-reboot evidence now persists before effect: original native boot ID,
|
||||
exact signed request, reservation time and reconnect deadline in each process's
|
||||
own `execution_evidence` ledger. Awaiting/unknown outcomes persist without
|
||||
unlocking the consumed attempt. Neither exit code nor a process restart supplies
|
||||
authenticated new-boot completion. Cancellation arriving while a permit is
|
||||
outstanding is checked before effect; running cancellation remains conservative.
|
||||
An earlier future-scheduled job no longer starves later ready jobs.
|
||||
|
||||
## Offline package installer (not executed on VM)
|
||||
|
||||
`deploy/linux/install.py` is create-only. Planned invocation:
|
||||
|
||||
```sh
|
||||
python3 deploy/linux/install.py --root /PATH/TO/STAGING \
|
||||
--agent-binary target/release/rmm-agent \
|
||||
--helper-binary target/release/rmm-privileged-helper --ca-file /PATH/TO/PUBLIC-CA.pem
|
||||
```
|
||||
|
||||
Staging writes only the x86-64 ELF artifacts, public CA and unit files. A live
|
||||
installation additionally requires root, `--root / --install-live` and an already
|
||||
provisioned unprivileged `rmm-agent` account. It refuses overwrites, writable or
|
||||
symlinked install directories, non-x86-64 artifacts and private-key CA inputs.
|
||||
It does **not** create accounts/config/identities/state, call systemctl, enable or
|
||||
start anything, install packages, change the network or reboot. Configure trust
|
||||
and enrollment first; systemd StateDirectory/RuntimeDirectory creates the correct
|
||||
runtime state when a later explicitly authorized bootstrap starts the units.
|
||||
The units retain empty agent capabilities, NoNewPrivileges, private temp,
|
||||
read-only system/home protection and no privileged-shell bypass. Privileged
|
||||
scripts are separately default-off and remain subject to the helper sandbox.
|
||||
|
||||
## Concrete backend contracts needed next
|
||||
|
||||
### APT bridge increment (not installed or VM-tested)
|
||||
|
||||
The helper's typed APT bridge is implemented at
|
||||
`crates/privileged-helper/src/apt.rs`, through its existing SO_PEERCRED/signature/
|
||||
parent-consumption boundary. Root config has optional `apt_provider`; default is
|
||||
disabled. The exact schema-2 signed manifest, additive domain action fields,
|
||||
compile-time-known create-only provider installation, pre-grant sealed archive/
|
||||
baseline layout, context/ledger mapping and conservative outcome contract are
|
||||
documented in [`../../tools/apt-transaction/HELPER-CONTRACT.md`](../../tools/apt-transaction/HELPER-CONTRACT.md).
|
||||
|
||||
This does not remove the package-capability blocker: the domain must preserve
|
||||
the complete typed `action.apt_manifest`, validate the narrow fixture closure,
|
||||
and support dedicated `apt_native_acceptance`; the agent remains unchanged.
|
||||
Legacy package/update actions without this field fail closed. No RunScript
|
||||
conversion, arbitrary archive URL or unsigned IPC manifest is accepted.
|
||||
|
||||
Planned root-only `rmm-privileged-helper --install-apt-provider` installs only
|
||||
embedded reviewed provider/hook bytes and fixed metadata, create-only. It does
|
||||
not start services, create grants, install .deb packages or create acceptance.
|
||||
`provision-fixture-store` prepares only the pinned fixture artifacts before any
|
||||
final grant. Neither command was executed in this increment.
|
||||
|
||||
The existing helper unit's ProtectSystem=strict/other protections are **not**
|
||||
an APT write/setup profile. A reviewed native fixture runner/unit configuration
|
||||
and actual VM tests are still required; no unit restriction was relaxed here.
|
||||
Do not advertise APT merely because the Rust bridge and local tests compile.
|
||||
|
||||
Before removing `begin_session`'s fail-closed reconnect gate, agree a versioned
|
||||
authenticated SyncRequest/Response carrying device identity/assignment and
|
||||
connection generation, journal identity/checkpoint, fixed job/attempt, payload
|
||||
hash, grant ID/bytes or reservation ambiguity, local revision/state, original
|
||||
boot ID, persisted outcomes and concrete durable event receipts. Server must
|
||||
return an explicit reconciled/fenced decision, not a blanket `ok`. Unknown or
|
||||
missing old reservations must retain resource locks; no response may authorize a
|
||||
new attempt or silently manufacture a replacement grant. Restored/mismatched
|
||||
generations must stay blocked. Reboot success requires authenticated current
|
||||
envelope boot ID different from persisted original boot and bound postconditions.
|
||||
|
||||
Long-poll must deliver the same typed envelopes and concrete ACKs with one active
|
||||
generation, including late evidence ingestion; no new endpoint/wire assumption
|
||||
is implemented here. Root planning must bind explicit root identity and local
|
||||
helper capabilities/policy, never reinterpret `agent_service`. The public key
|
||||
GET must authorize enrolled device mTLS. Additive inventory JSON acceptance must
|
||||
be confirmed before enabling extended collection in a real agent.
|
||||
Für einen neuen Release oder eine direkte Entwicklungsbereitstellung den gemeinsamen [Entwicklungsweg](../../docs/development.md) verwenden.
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
# Dev/test root-helper readiness, not package acceptance
|
||||
|
||||
`python3 deploy/vm_root_bootstrap.py inspect` is read-only. `build` creates a
|
||||
private minimal Docker context containing only Rust sources, pinned Cargo files,
|
||||
migrations and the reviewed APT-tool sources; it never includes credentials.
|
||||
`install` is the separately authorized create-only systemd bootstrap. It refuses
|
||||
existing root-helper paths, unresolved VM jobs, an active agent/tunnel, changed
|
||||
agent identity/signing authority or incompatible artifacts. It never resets an
|
||||
identity/journal or authorizes a job. Do not retry a partial install blindly.
|
||||
|
||||
Fixed resources: `/usr/local/libexec/rmm-privileged-helper`, root-owned 0600
|
||||
`/etc/rmm/helper-dev-test-v1.json` and `helper-signing-key-v1.json`, private root
|
||||
state `/var/lib/rmm-helper`, `rmm-helper-dev-test.service`, and root-owned agent
|
||||
drop-in `10-dev-helper-v1.conf`. The drop-in adds only
|
||||
`RMM_HELPER_SOCKET=/run/rmm-helper/control.sock`; it does not restart the agent.
|
||||
The helper's root-owned socket is 0660/group `rmm-agent` in a 0750 root-owned
|
||||
runtime directory. `SO_PEERCRED` separately checks exactly the provisioned
|
||||
non-root agent UID; a connect-only readiness probe is not a signed IPC test.
|
||||
|
||||
Public signing authority comes from the authenticated, CA/name-verified server
|
||||
GET and must match the preserved agent binding. No server private key is copied.
|
||||
Helper trust/ledger remain inaccessible to the network service. The helper is
|
||||
enabled for its expressly named dev/test service but stopped after readiness
|
||||
only when its own consumption ledger is confirmed empty. No agent/tunnel is
|
||||
started. Creation lists, native measurements and sanitized failure class/line
|
||||
numbers are stored privately; raw stderr, payloads and exceptions are withheld.
|
||||
|
||||
## Intentionally disabled execution gates
|
||||
|
||||
The dev/test config allows only the future exact `rmm-mvp-test.service` unit;
|
||||
this bootstrap **does not create or start that test service**. Root scripts and
|
||||
reboot are disabled. `apt_provider` is null. Installing the compiled-in provider
|
||||
via `--install-apt-provider` creates trusted code/hook and empty sealed-store
|
||||
directories/metadata only. No package, fixture archive, baseline, active context,
|
||||
grant or native-acceptance record is generated. `inspect-runtime` and
|
||||
`print-config` are measurements, not authority. Their hashes belong to a future
|
||||
explicitly UI-approved immutable plan.
|
||||
|
||||
`inspect-sandbox` is invoked read-only as root in the parent environment. A veto
|
||||
there is expected and reported as **not passed**, never bypassed with fabricated
|
||||
`host-namespaces.json`/sandbox-ready files. The actual provider requires its
|
||||
signed worker context before building the final sandbox.
|
||||
|
||||
The new readiness unit preserves restrictive protections; it is deliberately
|
||||
**not APT-execution-capable**. Package setup requires CAP_SYS_ADMIN for private
|
||||
mount/PID/network namespaces and mount setup, CAP_MKNOD for the four basic device
|
||||
nodes, and write access to the actual fixture package payload/dpkg/APT stores.
|
||||
The final package child must then retain exactly CHOWN, DAC_OVERRIDE, FOWNER,
|
||||
FSETID, SETGID, SETUID, SETPCAP and SETFCAP, NNP and seccomp; no SYS_ADMIN,
|
||||
SYS_BOOT, KILL or MKNOD may remain. Host control sockets must be hidden and the
|
||||
private PID1/mount/network checks must pass. The readiness unit's deny-mount
|
||||
syscall policy and ProtectSystem=strict prevent this setup. Do not loosen them
|
||||
blindly: a separately reviewed native APT runner/profile is still required.
|
||||
|
||||
Future backend root planning, manifest preservation, helper policy changes and
|
||||
agent capability negotiation do not follow from installation. Reconnect/sync
|
||||
must be ready before starting new jobs. Every service/package/update/reboot or
|
||||
new attempt still needs its own fixed plan and actual dev/test WebUI approval.
|
||||
Actual commands/results are recorded in `docs/implementation-status.md`; this
|
||||
document alone claims no VM execution or Linux-MVP acceptance.
|
||||
@@ -1,227 +0,0 @@
|
||||
# Dedicated APT runner / VM preflight contract
|
||||
|
||||
**Implemented, built and locally tested, not deployed or measured on a VM.**
|
||||
Every command below is **planned, not executed here**. No host package, service,
|
||||
reboot, root installation or acceptance operation was executed in this dispatch.
|
||||
Readiness is not package acceptance or authorization. Existing readiness/general
|
||||
helper unit is unchanged: no broadening its write paths/capabilities/filters.
|
||||
|
||||
## Architecture and fixed paths
|
||||
|
||||
Same helper binary, two separate daemon profiles:
|
||||
|
||||
| Profile | Socket | Allowed operations |
|
||||
|---|---|---|
|
||||
| general (existing/default) | existing configured general socket | existing explicitly permitted root operations, never APT |
|
||||
| `apt_only` | `/run/rmm-apt-helper/helper.sock` | read-only readiness and typed fixture APT jobs only |
|
||||
|
||||
APT profile requires agent UID **993**, root-owned agent-group socket ACL,
|
||||
empty allowed_services, allow_reboot=false, allow_root_scripts=false and a valid
|
||||
apt_provider policy. Unknown profiles/actions/CLI programs fail closed. No shell,
|
||||
service, reboot or generic-program dispatch exists in apt_only. Root administrative
|
||||
CLI modes are fixed install/probe/inspect operations, not network-callable argv.
|
||||
|
||||
**Both daemons must run the same new helper build** and use the exact same
|
||||
`/var/lib/rmm-helper/consumption.sqlite` and `executor.lock` inodes. All SQLite
|
||||
sidecars stay in that shared directory (current ledger uses synchronous FULL /
|
||||
DELETE journal mode; no database/WAL/SHM copy or private bind). Flank lock is now
|
||||
per actual request/effect, not daemon lifetime, allowing coexistence. Startup DDL
|
||||
is locked; consume/execute/finish are locked. An unresolved consumed row blocks
|
||||
all new effects across both profiles, including reboot/package conflicts.
|
||||
No tombstone deletion, marker reset, database copy or grant replacement shortcut.
|
||||
|
||||
APT-owned store: `/var/lib/rmm-apt-transaction` (0700), including archives,
|
||||
baselines, history, probes, state, log and active handoff. The child sees neither
|
||||
the shared ledger nor `/etc/rmm` keys/config, `/var/lib/rmm-agent`, home directories,
|
||||
host manager sockets or inherited private fds. Only the trusted outside root
|
||||
controller sees the signing-key pin/ledger. Central private signing keys must
|
||||
never be deployed to the VM.
|
||||
|
||||
## Installation order (planned)
|
||||
|
||||
1. Authenticated operator installs the reviewed newly built helper at fixed
|
||||
`/usr/local/libexec/rmm-privileged-helper` using the existing controlled
|
||||
artifact deployment process. Both helper daemons need this same build; do not
|
||||
blindly overwrite an active old helper or restart away unknown effects.
|
||||
2. Before starting the new unit, run the root-only known-payload installer:
|
||||
|
||||
```text
|
||||
/usr/local/libexec/rmm-privileged-helper --install-apt-provider
|
||||
```
|
||||
|
||||
It exclusively creates known embedded provider/hook files, schema-2 install
|
||||
metadata, the exact `rmm-apt-helper.service` at `/etc/systemd/system/`, private
|
||||
store directories and empty `/usr/share/rmm-mvp-test`. It does NOT install a
|
||||
.deb, start systemd, create grants or create an acceptance record. Existing/
|
||||
partial paths are refused, not overwritten, chmod-repaired or deleted.
|
||||
3. Root-provision `/etc/rmm/apt-helper.json` (0600) from
|
||||
`apt-helper.example.json`; replace all invalid placeholders and verify actual
|
||||
rmm-agent UID is 993 and socket_gid is the actual rmm-agent group GID. Keep
|
||||
the existing separately authenticated Ed25519 key pin/binding procedure.
|
||||
4. Inspect the installed provider/config/runtime, including installed helper
|
||||
binary and exact unit profile:
|
||||
|
||||
```text
|
||||
/usr/bin/python3 -I /usr/lib/rmm-apt-transaction/apt_transaction.py print-config
|
||||
/usr/bin/python3 -I /usr/lib/rmm-apt-transaction/apt_transaction.py inspect-runtime
|
||||
```
|
||||
|
||||
Set approved apt_config_sha256 from exact config bytes. Set runtime_sha256
|
||||
from the canonical runtime object **without its trailing newline**. Review
|
||||
the contents/code/configuration; blindly hashing unreviewed configuration is
|
||||
not a security review. No timestamp/hash placeholder can enable execution.
|
||||
5. After valid private config/key provisioning, inspect the helper identity pin:
|
||||
|
||||
```text
|
||||
RMM_HELPER_CONFIG=/etc/rmm/apt-helper.json /usr/local/libexec/rmm-privileged-helper --inspect-apt-profile
|
||||
```
|
||||
|
||||
Operator installs its exact JSON output at e.g.
|
||||
`/etc/rmm/apt-helper-proof.json`, root:rmm-agent 0640, in root-owned,
|
||||
non-group/world-writable configuration parents. This pin contains public
|
||||
identity/hash metadata, no grant or secret. Agent must be able to read it but
|
||||
not alter it. The inspected executable must match the installed daemon bytes.
|
||||
6. Validate the unit on the VM before start (`systemd-analyze verify`), then
|
||||
perform the separately authorized unit bootstrap. `ExecStartPre` executes:
|
||||
|
||||
```text
|
||||
RMM_HELPER_CONFIG=/etc/rmm/apt-helper.json /usr/local/libexec/rmm-privileged-helper --probe-native
|
||||
```
|
||||
|
||||
**The probe runs under the actual dedicated service profile**, not a generic
|
||||
root shell: controller verification requires NoNewPrivileges, exact ten-bit
|
||||
setup capability set, zero inherited/ambient caps, the actual
|
||||
rmm-apt-helper.service cgroup and readonly /usr, /etc and /var. Direct daemon/
|
||||
probe invocation outside that profile is rejected. `--inspect-apt-profile`
|
||||
remains a read-only administrative metadata operation and is not readiness.
|
||||
Controller verification also requires an outer seccomp filter, actual writable
|
||||
declared targets, and rejects unexpected writable submounts below /usr,/etc,
|
||||
/var. Inspect effective systemd configuration (`systemctl cat/show`) on the VM;
|
||||
do not introduce unreviewed drop-ins or substitute a root-shell launch.
|
||||
|
||||
## Unit and irreversible worker sandbox
|
||||
|
||||
`rmm-apt-helper.service` provides NNP, PrivateTmp/PrivateNetwork, strict readonly
|
||||
system/home/kernel/control-group protection, AF_UNIX only, native syscall ABI,
|
||||
mount/PID/net namespaces only, no ambient caps. Bounding set is filesystem/UID
|
||||
bits 0,1,3,4,6,7,8,31 plus SYS_ADMIN/MKNOD for trusted setup; no SYS_BOOT,
|
||||
SYS_CHROOT or SYS_TIME. DevicePolicy=strict permits only null/zero/random/urandom
|
||||
rwm; PrivateDevices=no permits trusted construction of a minimal private /dev.
|
||||
|
||||
Outer filter allows mount/unshare/fork/capset/prctl/seccomp trusted setup instead
|
||||
of an outer @mount prohibition. Reboot/module/raw-io/swap/debug and clock setters
|
||||
remain denied. The narrow adjtimex exception is necessary for the existing
|
||||
read-only modes=0 trusted-clock query; mutating adjtimex still needs CAP_SYS_TIME,
|
||||
which is absent. This is not a clock-verification bypass.
|
||||
|
||||
Write paths are **only** `/var/lib/dpkg`, shared helper ledger, private provider
|
||||
store and precreated `/usr/share/rmm-mvp-test`. No whole /usr, /etc or /var writes.
|
||||
APT terminal/history logs and dpkg log are explicitly under provider `log/`;
|
||||
APT cache/state and extended_states are private, no default /var/log/apt write.
|
||||
These are configured paths, **not natively proven log/write requirements** yet.
|
||||
Unexpected native write failures must be reported, not fixed with blanket writes.
|
||||
|
||||
One common Python setup function serves mutation and readiness. It makes mount
|
||||
propagation private, hides keys/ledger/sockets/fds, mounts minimal devices and
|
||||
kernel controls, then irreversibly drops E/P/B to the original eight caps,
|
||||
clears I/A, retains NNP and installs seccomp. Both clone namespace flags
|
||||
(including NEWUSER/NEWTIME) and clone3 pointer flags are closed: clone3 returns
|
||||
ENOSYS for libc's ordinary fork fallback; clone namespace flags return EPERM.
|
||||
Ordinary fork/exec remains allowed. No reconfiguration/reboot/kexec escape is
|
||||
allowed after setup. Trusted setup with SYS_ADMIN is explicitly in the TCB.
|
||||
|
||||
## Readiness probe: no package transaction
|
||||
|
||||
`--probe-native` does NOT create jobs, grants, receipts, launch/effect markers or
|
||||
native-acceptance records. It exclusively creates a generated private probe dir,
|
||||
copies host dpkg status (host opened read-only), binds the copy over /var/lib/dpkg
|
||||
inside the worker namespace, uses source/hook-isolated private APT config, tests
|
||||
private-db frontend lock conflict and runs positive `apt-get check` on that copy.
|
||||
The host frontend lock is only observed with O_RDONLY/F_GETLK: never F_SETLK,
|
||||
flock/lockf, deletion or killing an owner. Invalid-magic/flags reboot/kexec probes
|
||||
must return EPERM; no valid calls or PID1 signals are attempted.
|
||||
|
||||
The worker checks namespaces/PID1, capabilities/NNP/seccomp, readonly control
|
||||
mounts, hidden sockets and masked sysrq. Parent verifies complete result and
|
||||
private namespace identities, unchanged host status/runtime and publishes only
|
||||
root-private `native-readiness.json` (readiness_only=true, native_acceptance=false).
|
||||
It is boot-/code-/OS-/binary-/unit-bound and invalidated by changes. Partial,
|
||||
failed or malformed results do not publish new readiness. Acceptance/bootstrap
|
||||
attempt tombstones are neither created nor reset by this operation.
|
||||
|
||||
## Agent environment / read-only IPC API
|
||||
|
||||
```
|
||||
RMM_APT_HELPER_SOCKET=/run/rmm-apt-helper/helper.sock
|
||||
RMM_APT_HELPER_PROOF_FILE=/etc/rmm/apt-helper-proof.json
|
||||
```
|
||||
|
||||
`RMM_HELPER_SOCKET` remains the general route. Typed ensure_package,
|
||||
apply_updates and apt_native_acceptance exclusively use the dedicated socket.
|
||||
Missing/wrong APT socket/pin/readiness never falls back to general helper, SSH,
|
||||
shell or local execution. The unprivileged agent obtains a fresh read-only probe
|
||||
before capability advertisement and before use; it authenticates root SO_PEERCRED,
|
||||
root-owned safe socket/parents and independent root-provisioned pin.
|
||||
|
||||
Same u32-big-endian framed JSON socket, a distinct read-only request shape:
|
||||
|
||||
```
|
||||
operation: "apt_readiness_v1"
|
||||
challenge: fresh nonnil UUID
|
||||
identity: {tenant_id,asset_id,agent_id,enrollment_generation,assignment_version,signing_key_id}
|
||||
expected_stack_sha256: independently pinned helper/identity/policy/unit stack hash
|
||||
```
|
||||
|
||||
Response strictly binds nonce, identity, apt_only profile and provider stack;
|
||||
includes shared ledger/lock dev/inodes and separate fixture_acceptance_ready,
|
||||
bootstrap_recipes and accepted_recipes. Wrong nonce/identity/generation/profile/
|
||||
stack/root peer is rejected. An unresolved shared ledger suppresses all APT
|
||||
readiness/capabilities. This API never consumes a grant or authorizes a job.
|
||||
|
||||
Readiness alone advertises **only apt_native_acceptance** for fixed allowed
|
||||
fixtures. Valid native acceptance records enable only matching fixture recipes:
|
||||
ensure_package, and apply_updates only for the accepted update recipe. Agent
|
||||
also checks each actual typed job's manifest recipe, not just aggregate action
|
||||
capability names. No production/arbitrary catalog capability is manufactured.
|
||||
|
||||
## Actual jobs remain UI-authorized
|
||||
|
||||
Domain's additive typed schema-2 apt_manifest and dedicated AptNativeAcceptance
|
||||
are now present; local tests roundtrip the actual domain variant through exact
|
||||
signed bytes into the helper validator. See
|
||||
`tools/apt-transaction/HELPER-CONTRACT.md` for the full immutable payload/context
|
||||
schema. Readiness does not replace independent Ed25519 verification, all target/
|
||||
tenant/generation/plan/job/attempt/authorization/action/hash/time bindings,
|
||||
current trusted clock, parent consumption and immutable WebUI approval.
|
||||
|
||||
Use provision-fixture-store / prepare-baseline **before** final grant to stage
|
||||
the two known archives and snapshot. One UI-approved dedicated fixture job may
|
||||
install 1.0, another may update 1.0 -> 1.1. Same guard/native lock/deadline/hash/
|
||||
postcondition pipeline, no weak path. Failed/stale/partial/unknown never acceptance.
|
||||
Armed/unknown outcomes retain both parent resource fencing and effect markers.
|
||||
One-time failures are not blindly reset: technical no-start recovery needs a
|
||||
separate durable signed reconciliation procedure, not implemented as a shortcut.
|
||||
|
||||
No actual native namespace/APT/service/root execution has been measured here.
|
||||
The subsequent VM worker must execute this profile/probe and UI-authorized
|
||||
fixture jobs, retain actual evidence and report all native failures separately.
|
||||
|
||||
## Executed local verification (this increment)
|
||||
|
||||
* Source-tree rustfmt check passed for helper lib/main and agent main/modules.
|
||||
* Targeted Clippy `-p rmm-privileged-helper -p rmm-agent --lib --bins -- -D warnings`
|
||||
passed.
|
||||
* `cargo test -p rmm-privileged-helper -p rmm-agent --lib --bins`: **37 passed**
|
||||
(20 helper library, 3 helper binary, 14 agent).
|
||||
* `PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests/apt_transaction -p 'test_*.py' -v`:
|
||||
**48 passed**; AST syntax checks **7 Python files**; example JSON syntax passed.
|
||||
* Local unprivileged seccomp invalid-input/clone-flag denial and ordinary
|
||||
fork/exec really ran. Root setup/installer/APT/probe unit execution was mocked
|
||||
where unsafe. Temporary mock readiness files are not deployed native evidence.
|
||||
|
||||
Package-wide verification has a concurrent-work limitation: the last full
|
||||
`cargo fmt --check` encountered formatting in the other worker's
|
||||
`crates/privileged-helper/tests/reconcile.rs`; the last all-target Clippy attempt
|
||||
failed on missing `validate_history` in its included `src/reconcile.rs`. Those
|
||||
Sync files were not edited here. The focused source checks/tests above passed
|
||||
afterwards; this is not a claim that the parallel Sync integration suite passed.
|
||||
@@ -1,241 +0,0 @@
|
||||
# Explizite Hostwartung mit full_maintenance_v1
|
||||
|
||||
Stand 2026-11-14, Spezifikation1.20. Die Batch-Skriptkonsole und der unabhängig
|
||||
geprüfte Fullhelper-Binärpinfix sind implementiert, neu quellqualifiziert und nach
|
||||
tatsächlichem Linux-Unitlauf erhaltend auf der Cloud-Linux-VM bereitgestellt.
|
||||
Agent, General und Full laufen mit den geprüften Images; signierter Folgeabgleich
|
||||
und WebUI-genehmigter Fulljob bleiben separat offen. Tatsächliche Teilfehler,
|
||||
Fortsetzungen und unveränderte Originalbelege:
|
||||
[Bootstrap-Ergebnisse](../../docs/script-console-bootstrap-results.md).
|
||||
Cloud-Linux-VM zuerst, Windowsgast separat; Notebook ausschließlich Entwicklung.
|
||||
|
||||
## Aktueller korrigierter lokaler Nachweis
|
||||
|
||||
Der neue eigenständige Pack liegt privat unter
|
||||
`devstate/script-console-qualification/run-29461892-343f-42f4-b469-88703535425e/`.
|
||||
Manifest-SHA256:
|
||||
`ddd1a78d1cd289b02b1f98572f9652171ec00be84e01ce099fd722d689bcaacd`.
|
||||
158 vollständige Compiler-/Include-/Fixture-/Deploymentinputs vor/nach identisch.
|
||||
Sourcearchiv-SHA256:
|
||||
`fcb57f69ad81ea4acde15af6022d5c2da32f5699ebd39886c530c77882b369cc`.
|
||||
|
||||
Tatsächlich ausgeführt: Formatprüfung, Linux-Workspace-Alltargets-Clippy mit
|
||||
`-D warnings`,285 lokale Tests bestanden (5DB-Fälle zunächst ausgelassen), danach
|
||||
sämtliche45 Serververträge inklusive dieser5 gegen frisches isoliertes PostgreSQL
|
||||
bestanden (0ignored). Windows-GNU-Alltargets-Clippy mit -Dwarnings im Default-
|
||||
und SYSTEM-Helperprofil bestanden. Kein geänderter Test unterdrückt; die neue
|
||||
Imageprüfung führt auch bei nicht vertrauenswürdigem Dateibesitz echte
|
||||
Verweigerungsassertions aus, keinen stillen Early-return-Skip.
|
||||
|
||||
Neue tatsächliche Linux-Unitlisten: Domain22, Linuxruntime16, Helperpolicy6,
|
||||
Serververträge45. Auf Cloud-Linux ohne isolierte DB erwartet:84PASS und5explizite
|
||||
DBignored; diese5 sind separat im lokalen45er-DB-Lauf tatsächlich bestanden.
|
||||
Alle vier vollständigen Listen müssen vor irgendeinem Unitstart geprüft sein.
|
||||
Linux-Release-Helper SHA256
|
||||
`79442727c3ba31cda02a8bc0e67481f14db9f39fc07520a880a90b64f10f1eaf`;
|
||||
Agent `0a7ad6eefaefda79ee80b6a41b2df904e9e7f50ae6ebeed01b98c25b6ce5c06f`;
|
||||
Server `610017637a9f9e55a6cb3cd8264937b953996af84e86dd49f2ea00c8e59739cd`.
|
||||
Keine dieser neuen Binaries ist durch den Builder auf einem Ziel installiert.
|
||||
Native Cloud-Linux-Units bestanden anschließend tatsächlich; siehe den separaten
|
||||
Beleg unten. Auch die späteren 36+7 Windows-Units bestanden separat nativ:
|
||||
[Windows-Nachweis und Grenzen](../../docs/script-console-windows-link.md).
|
||||
Laufende Windows-SYSTEM-Runtime und WebUI-genehmigter FullMaintenancejob sind
|
||||
eigenständige, dadurch nicht ersetzte Nachweise.
|
||||
|
||||
## Frühere lokale Nachweise und der danach behobene Binärpinbefund
|
||||
|
||||
Das eingefrorene Paket liegt ausschließlich privat unter
|
||||
`devstate/script-console-qualification/run-de34d47c-985e-460c-b18c-3f0d1b3fd315/`.
|
||||
Manifest-SHA256:
|
||||
`60a50262f9f8d85c11eb58e1a9e0f6e03be6cd5db7a59bc1745fb7d9dc8a6f65`.
|
||||
157 Compiler-, Include-, Fixture- und Deploymentinputs wurden vor/nach dem
|
||||
vollständigen Lauf identisch geprüft. `reviewed-sources.tar.gz`:
|
||||
`ef822b2e2ec6f8ad3d828f0923b2aa886d462fba328affb61bd80e98acf2c357`.
|
||||
|
||||
Tatsächlich lokal ausgeführt: Formatprüfung; Linux-Workspace-Clippy mit allen
|
||||
Targets und `-D warnings`; Workspace284PASS bei fünf zunächst ausgelassenen
|
||||
DB-Fällen; anschließend sämtliche45 Servertests mit `--include-ignored` in
|
||||
frischem isoliertem PostgreSQL17.6:45PASS,0ignored. DB ohne veröffentlichten Port,
|
||||
Netzwerknamespace ausschließlich intern, frische Rollen/Migrationen, danach
|
||||
entfernt. Keine Produktionsdatenbank. Windows-GNU-Alltargets-Clippy separat im
|
||||
Default- und SYSTEM-Helperprofil jeweils bestanden; keine native Windowsausführung.
|
||||
Linux-Releasebinaries und vier native Linux-Testprogramme dieses früheren
|
||||
Quellenstands sind gebaut/gehasht, noch nicht auf der Cloud-VM ausgeführt oder
|
||||
installiert. **Nachträglicher unabhängiger Reviewblocker:** Dieser Pack bindet
|
||||
noch nicht den tatsächlichen laufenden Linux-Fullhelpercodehash. Er berechtigt
|
||||
keine Fullprofilaktivierung. Der danach separat geprüfte und im neuen Pack qualifizierte enge Corefix ergänzt ausschließlich
|
||||
im Fullprofil tatsächliches gehaltenes `/proc/self/exe`, geschützten Binärpin,
|
||||
authentisierte Probe, zusätzliche Binärcapability und zentrale Hashprüfung.
|
||||
General/APT lassen neue Metadaten vollständig aus. Der neue lokale Stand steht
|
||||
oben; dieser alte Pack bleibt ausdrücklich der ursprüngliche Beleg.
|
||||
|
||||
Die ersten Packvorbereitungen erzeugten kein qualifiziertes Manifest: Der erste
|
||||
before/after-Schutz bemerkte die währenddessen vervollständigte Builderinputliste;
|
||||
der zweite hielt bei PostgreSQLs temporärer Initialisierungsphase an. Der finale
|
||||
oben genannte Lauf wartet auf den endgültigen TCP-Endpunkt und besteht vollständig.
|
||||
Diese Vorbereitungsläufe werden nicht zu bestandenen Abnahmen umgedeutet.
|
||||
|
||||
## Separater Linux-first-Unitrunner
|
||||
|
||||
Der Runner `deploy/script_console_acceptance.py` ist separat reviewbar und kein
|
||||
Teil der158 eingefrorenen Compilerinputs; er baut und verändert diese nicht.
|
||||
Er ist ausdrücklich auf den neuen Pack29461892 und dessen Manifestddd1a78d…
|
||||
gebunden; bei veränderten Compilerinputs wird ein neuer Start verweigert. Die
|
||||
ursprüngliche Vorbereitung für Packde34 bleibt ein früherer, nie ausgeführter
|
||||
Runnerstand. Die jetzigen Counts beruhen auf den tatsächlich erzeugten Listen.
|
||||
Runnerquellhash:
|
||||
`2b3ba8d548d18627643a9f73c9a4f7bacce4ac2cd5495745c6760d088e078145`.
|
||||
Supportquellen werden vor Import und jedem Zielaufruf inklusive Readback exakt
|
||||
geprüft und in Intent/Payload/Result gebunden: Runtime-Bootstraphelper
|
||||
`833ad8806c90a19342aa6fbc71c33e81975caffb1746550e9b0fbdca7fa0c7ab`,
|
||||
Zugangsparser
|
||||
`5c8107ea9151a9f498b2530cdc61c1a7a6d745aff853a9b05710f3395838c0dd`.
|
||||
Der finale Readback verlangt product_state_writes, rmm_jobs,
|
||||
capabilities_activated und approvals ausdrücklich jeweils false.
|
||||
Er verwendet ausschließlich den vorhandenen strikten Bootstraptransport und
|
||||
`credentials/linux-vm.conf` im ursprünglichen Hauptcheckout, ausschließlich als root auf der festgelegten Linux-Test-VM, mit vorhandenem
|
||||
SSH-Key und strenger Hostprüfung. Keine
|
||||
Zugangsdatenkopie ins Scriptworktree, keine alternative IP oder Passwortfallback.
|
||||
|
||||
**Tatsächlich ausgeführt:** Alle vier Listen wurden vor jedem Unitstart geprüft;
|
||||
84 Tests bestanden, fünf ausdrücklich ausgelassene DB-Verträge waren zuvor im
|
||||
isolierten lokalen PostgreSQL-Lauf bestanden. Fall
|
||||
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, Beleg-SHA256
|
||||
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
|
||||
Der verwendete Aufruf war:
|
||||
|
||||
```bash
|
||||
python3 deploy/script_console_acceptance.py execute-linux
|
||||
```
|
||||
|
||||
Es entstehen nur neue private Scratchdateien unter
|
||||
`/var/lib/rmm-script-console-contracts/<case-id>/`. Erst werden alle vier exakten
|
||||
ELF-Hashes und vollständigen Listen geprüft; kein Unitstart vor dem gesamten
|
||||
Listenbeleg. Danach feste Testargumente, geleerte Umgebung, eigenes TMPDIR,
|
||||
eigener Netzwerknamespace und CPU-/Speicher-/Dateilimits. Erwartet werden84PASS
|
||||
und fünf ausdrücklich ausgelassene DB-Fälle auf der VM ohne DB; dieselben fünf
|
||||
DB-Verträge sind bereits im isolierten lokalen45er-Lauf belegt. Keine Installation,
|
||||
Enrollment-, Dienst-, Policy-, Paket-, Schlüssel-, Journal- oder Capabilityänderung.
|
||||
|
||||
Bei verlorenem Ergebnis ausschließlich denselben ursprünglichen Fall lesen:
|
||||
|
||||
```bash
|
||||
python3 deploy/script_console_acceptance.py read-linux --case <urspruengliche-case-id>
|
||||
```
|
||||
|
||||
Readback erzeugt keinen zweiten Remote-Start. Ein vorhandener Create-once-
|
||||
Startmarker erlaubt kein erneutes `run`; Teilergebnisse bleiben erhalten. Ein
|
||||
unvollständiger/fehlender Beleg ist keine bestandene Abnahme und wird nicht blind
|
||||
wiederholt. Native Units sind keine RMM-Dienst-/WebUI-/FullMaintenanceabnahme.
|
||||
|
||||
## Bootstrapvorbereitung nach gesondertem Erhaltungsreview
|
||||
|
||||
Der ursprüngliche Erhaltungsplan und die weiterhin geltenden Schutzgrenzen
|
||||
folgen unten; tatsächliche Ausführung samt fehlgeschlagenen Teilphasen und
|
||||
separaten Erststartfortsetzungen steht in den
|
||||
[Bootstrap-Ergebnissen](../../docs/script-console-bootstrap-results.md).
|
||||
Aktuelle Cloudbelege, Geräte-/Boot-/
|
||||
Journalidentitäten, Inodes, Verbrauchszeilen und Dienstzustände werden vor einer
|
||||
Änderung durch den verantwortlichen Rootprozess unabhängig gegengeprüft. Die
|
||||
bisherigen General-/APT-Units und Pins sowie deren Historie bleiben erhalten;
|
||||
keine Ledgerkopie, kein Reset und kein stilles Öffnen alter Scopes.
|
||||
|
||||
Die neue Unit ist `deploy/linux/rmm-full-maintenance-helper.service` mit eigenem
|
||||
Runtimeverzeichnis `/run/rmm-helper-maintenance`. Sie verweist auf
|
||||
`/etc/rmm-remote/helper-full-maintenance.json`. Diese Konfiguration erhält exakt
|
||||
die bestehende provisionierte öffentliche Bindingidentität und dieselben
|
||||
Root-Sharedledger-/Lockdateien; neue Auswahl:
|
||||
|
||||
```json
|
||||
{
|
||||
"profile": "full_maintenance_v1",
|
||||
"allowed_services": [],
|
||||
"allow_reboot": false,
|
||||
"allow_root_scripts": true,
|
||||
"allowed_script_profiles": ["full_maintenance_v1"],
|
||||
"helper_binary_sha256": "<tatsaechlicher SHA256 der qualifizierten laufenden Helperbinary>"
|
||||
}
|
||||
```
|
||||
|
||||
Das ist ein Ausschnitt, keine vollständige einsatzfähige Konfiguration. Socket,
|
||||
Agent-UID/GID, Zustandspfad und bestehendes Binding müssen aus dem tatsächlich
|
||||
geprüften Bestand kommen. Kein `apt_provider`. `allow_reboot=false` verweigert
|
||||
nur die typisierte Rebootaction; genehmigter Rootcode besitzt volle Hostautorität.
|
||||
|
||||
Der separat geschützte Policy-Pin bindet Profil `full_maintenance_v1`, bestehende
|
||||
Identität, tatsächlichen lokalen Policyhash und unabhängig beobachteten
|
||||
laufenden Binärhash. Das neue Fullprofil benötigt Schema2 im Pin; der Helper
|
||||
kann diesen nach selbst geprüftem Rootimage mit dem ausdrücklich getrennten
|
||||
Bootstrapmodus `--inspect-full-maintenance-profile` ausgeben. Generalpin
|
||||
Schema1 bleibt unverändert. Agentumgebung ausschließlich
|
||||
additiv um `RMM_FULL_MAINTENANCE_HELPER_SOCKET` und
|
||||
`RMM_FULL_MAINTENANCE_POLICY_FILE` ergänzen. Kein Fallback auf General/APT und
|
||||
keine Änderung deren bestehender Umgebung. Die zentrale Rootpolicy braucht
|
||||
Schema2 und einen ausdrücklich begrenzten Scope mit neuen exakten Helperpins
|
||||
sowie `allowed_script_profiles=["full_maintenance_v1"]`. Aktuelle Rechte beider
|
||||
Planakteure, Helper-Sync, TrustedClock, ursprünglicher Grant und Einmalverbrauch
|
||||
bleiben zusätzlich erforderlich. Eine Policy ist keine Jobgenehmigung.
|
||||
|
||||
Vor Installation werden zusammengesetzte systemd-Unit und etwaige Drop-ins
|
||||
geprüft: Vollwartung darf keine General-Sandbox erben, die Hostdateisystem oder
|
||||
Netzwerk unerwartet sperrt. Dienst- und Binärwechsel nur mit qualifizierten
|
||||
Artefakten und explizitem Erhaltungsplan. Insbesondere darf eine neue allgemeine
|
||||
Helperbinary nicht still die alten APT-Codepins überschreiben/öffnen. Gegebenenfalls
|
||||
eigenen qualifizierten Binärpfad für die neue FullMaintenanceunit wählen und die
|
||||
bestehenden Providerpfade unverändert erhalten. Native Erhaltung und Sync nachweisen,
|
||||
bevor neue Capabilities/Scopes geöffnet werden.
|
||||
|
||||
Erster tatsächlicher FullMaintenancejob nur nach bereitgestellter WebUI und
|
||||
expliziter Genehmigung der unveränderlichen Skript-/Profil-/Ziel-/Rechtebytes.
|
||||
Abgestimmter Scope: harmlose Identität/stdout/stderr und kontrollierte lesende
|
||||
Dateisystem-/Netzwerkbeobachtung; kein Betriebssystemupdate oder Neustart. Volle
|
||||
Hostautorität wird sichtbar erklärt; kein Sandbox-, No-Reboot- oder Rollbackversprechen.
|
||||
Windows-SYSTEM folgt nach eigenem Clock-/Pipe-/Profilnachweis. Die vorhandene
|
||||
PipeV2-Datei ist unverändert SHA256
|
||||
`ce525dab23f2e4faa2c9816280c1a5a8b40e56d0e63a350256e83b2df1d9229d`;
|
||||
ursprüngliche native Pipebelege werden nicht als Belege der neuen Runtime ausgegeben.
|
||||
|
||||
## Anschließend auf der tatsächlichen Cloud-Linux-VM bestanden
|
||||
|
||||
Root führte ausschließlich den korrigierten Pack29461892 nativ aus: Fall
|
||||
`7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, **84PASS,5explizite DBignored**.
|
||||
Die vier vollständigen tatsächlichen Listen wurden vor irgendeinem Unitstart
|
||||
exakt geprüft; anschließend liefen alle vier festen ELFs im eigenen Scratch,
|
||||
mit geleerter Umgebung, Netzwerknamespace und Ressourcenlimits. Die5DB-Verträge
|
||||
bleiben diesem VM-Lauf ausdrücklich nicht zugerechnet; sie sind im separaten
|
||||
isolierten45er-PostgreSQL-Lauf belegt. Kein stiller Testskip oder Produktjob.
|
||||
|
||||
Beleg `passed-e214cd9b-21ac-48ce-82dc-d10364329d04.json`, SHA256
|
||||
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`.
|
||||
Keine Agent-/Helperinstallation, Änderung bestehender Dienste/Policies/PKI/
|
||||
Datenbanken, veröffentlichte Capability oder WebUI-Genehmigung durch diesen
|
||||
Unitlauf. Der oben ursprünglich geplante Unitaufruf ist damit abgeschlossen.
|
||||
Der inzwischen erhaltend ausgeführte Bootstrap steht in den separaten
|
||||
[Bootstrap-Ergebnissen](../../docs/script-console-bootstrap-results.md);
|
||||
signierter Folgeabgleich und tatsächlicher FullMaintenancejob sind dadurch
|
||||
noch nicht abgenommen.
|
||||
|
||||
## Verbindlicher Generationsentscheid vor dem Bootstrap
|
||||
|
||||
Ein eigener neuer Fullhelper bei weiterlaufendem altem Generalhelper reicht
|
||||
nicht: Alle aktiven Leser des gemeinsamen Root-Ledgers müssen neue
|
||||
`privileged_script_profile`-Jobbytes unabhängig dekodieren und prüfen können.
|
||||
Alte Decoder verweigern selbst geschlossene neue Zeilen und können beim
|
||||
Snapshot/Sync einen sticky Fault schreiben. Deshalb neuer Agent und aktive
|
||||
General-/Fullhelper gemeinsam auf die neue qualifizierte Generation; bestehende
|
||||
Generalunit/Sandbox/Config/Policy-/Pinbytes unverändert. APT bleibt disabled/
|
||||
inactive, ohne Endpoint und mit geschlossenen Scopes. Seine aktuelle Generation
|
||||
war bereits laut vorherigem Runtimeindex nicht qualifiziert; historische
|
||||
Abnahmen bleiben erhalten. Vor späterer Wiedereröffnung eigener APT-Stackpin-
|
||||
/Generationnachweis, kein alter Helper gegen neue Ledgerzeilen.
|
||||
|
||||
Der Rootprozess hat die84 native Cloud-Linux-Units tatsächlich ausgeführt:
|
||||
Fall `7b61ce46-7913-492b-9c6b-414a0c2b6ffc`, Proof-SHA256
|
||||
`a831a70a3cf76a3e8a9bf5820dcca7100d2ef9860dd9388539fe9c13f949f470`,
|
||||
84PASS und5 ausdrücklich ausgelassene DB-Fälle. Diese5 sind im isolierten lokalen
|
||||
45er-Lauf bestanden. Keine RMM-Jobs oder neue Capabilities aus diesem Unitlauf;
|
||||
der inzwischen ausgeführte Runtimeaustausch ist separat belegt. Tatsächlicher
|
||||
signierter Folgeabgleich und genehmigter Fulljob bleiben eigene offene Schritte.
|
||||
|
||||
Details und Nach-MVP-Entdeckung:
|
||||
[script-console-helper-generations.md](../../docs/script-console-helper-generations.md).
|
||||
@@ -1,311 +0,0 @@
|
||||
# Agent/helper runtime — integrated source, VM acceptance pending
|
||||
|
||||
This is the current runtime contract. It supersedes the earlier module-only
|
||||
handoffs in `README.md` and `tests/agent_sync/README.md`. No installation, target
|
||||
job, service/reboot/package mutation, SSH tunnel or server restart was performed
|
||||
by this integration. Actual VM execution/acceptance belongs to the next worker.
|
||||
Nothing here approves an RMM job or substitutes for the WebUI approval boundary.
|
||||
|
||||
## Binaries and complete CLI/environment
|
||||
|
||||
Both binaries support `--help`; unknown arguments fail closed. Normal agent
|
||||
operation has no positional arguments. Planned bootstrap invocation:
|
||||
|
||||
```text
|
||||
RMM_AGENT_STATE=/var/lib/rmm-agent
|
||||
RMM_CA_FILE=/etc/rmm/ca.pem
|
||||
RMM_CONNECT_ADDR=127.0.0.1:18443
|
||||
RMM_TRANSPORT=https
|
||||
/usr/local/libexec/rmm-agent
|
||||
```
|
||||
|
||||
These are environment assignments, not an instruction to source a credential
|
||||
file. The trusted CA and TLS name **rmm-dev.internal** are always checked. TCP
|
||||
override changes neither DNS/SNI nor certificate verification. No proxy trust,
|
||||
invalid-certificate bypass or public Docker port is introduced.
|
||||
|
||||
| Variable | Meaning/default |
|
||||
|---|---|
|
||||
| `RMM_AGENT_STATE` | Private 0700 owned agent state; default `devstate/agent` |
|
||||
| `RMM_CA_FILE` | Public trusted CA; default `devstate/pki/ca.pem` |
|
||||
| `RMM_CONNECT_ADDR` | Parsed TCP SocketAddr; default `127.0.0.1:18443` |
|
||||
| `RMM_TRANSPORT` | `auto` (default), `wss`, or `https`; HTTPS can be explicitly selected for VM acceptance |
|
||||
| `RMM_ENROLLMENT_TOKEN_FILE` | First registration only; remove the bootstrap token after enrollment |
|
||||
| `RMM_JOB_BINDING_FILE` | Optional private agent-owned JSON Binding; absent means passive, no job capabilities |
|
||||
| `RMM_JOB_SIGNING_KEY_BOOTSTRAP=1` | Authenticated device-mTLS GET, using the current rotation-store identity; pins without replacing existing trust |
|
||||
| `RMM_HELPER_SOCKET` | Configured general helper socket, e.g. `/run/rmm-helper/control.sock` |
|
||||
| `RMM_HELPER_POLICY_FILE` | Root-owned, agent-readable public general policy pin; required with general socket |
|
||||
| `RMM_APT_HELPER_SOCKET` | Dedicated fixed `/run/rmm-apt-helper/helper.sock`, never generic fallback |
|
||||
| `RMM_APT_HELPER_PROOF_FILE` | Root-owned public APT stack/profile/identity pin; see `apt-helper-README.md` |
|
||||
| `RMM_LOG_UNITS_FILE` | Private agent-owned JSON array of exact allowed service units for unprivileged live logs |
|
||||
| `RMM_EXTENDED_INVENTORY` | `1` by default with the now-compatible backend, `0` for legacy base-only JSON |
|
||||
| `RMM_AGENT_PROFILE` | `development` required only for the rotation-test interval override |
|
||||
| `RMM_ROTATION_TEST_AFTER_SECONDS` | Positive development-only certificate-age trigger; never bypasses chain/expiry/EKU/key/identity verification |
|
||||
|
||||
Binding fields: tenant_id, asset_id, agent_id, enrollment_generation,
|
||||
assignment_version, public_key_hex. Device/asset must match enrollment. Empty key
|
||||
is allowed only with authenticated signing-key bootstrap; later startup must
|
||||
reauthenticate that bootstrap or use a fully provisioned binding. Key response is
|
||||
Ed25519/schema 1/raw 32-byte key with SHA-256 key ID, bounded and no redirects.
|
||||
The immutable agent cache is `job-signing-key.json`. Signing-pin replacement and
|
||||
identity/assignment recovery are controlled provisioning operations, not automatic
|
||||
trust in a key from a job. Helper trust stays independently root-provisioned.
|
||||
|
||||
The unit leaves the job-binding optional in `/etc/rmm/agent.env`, allowing a first
|
||||
passive enrollment. Set binding/key-bootstrap/helper variables only after the
|
||||
authenticated operator resolves the enrolled IDs and provisions their pins.
|
||||
Do not delete an old identity/journal to get a new first-session shortcut.
|
||||
|
||||
## Integrated transport and sync
|
||||
|
||||
One bounded actor and one dispatcher serve WSS and HTTPS with identical envelopes,
|
||||
journal, result receipts, cancellation and signature checks. `auto` tries WSS
|
||||
first and falls back only after two typed HTTP upgrade-block classifications;
|
||||
401/403, TLS/identity failures and ambiguous errors never select a bypass.
|
||||
WSS Ping/Pong are handled. HTTPS uses the existing MessageBatch/25-second poll
|
||||
contract. Poll cancellation cannot create a new attempt; fresh heartbeat IDs/
|
||||
sequences are never reused or queued as offline telemetry. Actor queues are bounded.
|
||||
|
||||
Every authenticated Hello advertises `rmm.sync.v1` and closes all local effect
|
||||
gates. Agent obtains actual root snapshots, durably reserves the fresh SyncRequest,
|
||||
checks exact signed SyncResponse bytes and all device/channel/boot/checkpoint/
|
||||
request-hash/time bindings, commits targeted journal/receipt changes, applies its
|
||||
own consumption decisions, forwards the **original** signed response plus original
|
||||
request protobuf to every configured helper, then confirms actual applied root
|
||||
checkpoints. No generic ready boolean opens either process.
|
||||
|
||||
Both root profiles share actual DB/lock inodes. They join an unchanged pending
|
||||
root capture created after both process births, so ONE signed response/checkpoint
|
||||
can be independently applied by both. A new process never inherits readiness
|
||||
from the shared DB. Stale process captures are fenced; known outcomes may unlock
|
||||
specifically while an unknown retains the resource and global gates stay closed.
|
||||
Consumed grant/attempt tombstones are never removed.
|
||||
|
||||
Scheduler AND immediate worker effect admission check the current signed lease;
|
||||
the worker also rechecks fresh grant/time and the disconnect/rotation atomic fence.
|
||||
Helper checks its own process gate under the same executor guard before consumption.
|
||||
Unknown, missing authoritative history, clock failure and rollback remain closed.
|
||||
Clock/helper sync failure does not stop independent passive heartbeat/inventory
|
||||
traffic. Sync retries are bounded, happen on fresh inventory/result ACK and on a
|
||||
lease timer, and never retry a lost permit request as a new grant.
|
||||
|
||||
After reboot, old/new boot ID alone is not success. Fresh current-boot inventory
|
||||
is durably ACKed, a new signed decision must bind the persisted original boot and
|
||||
current authenticated boot plus inventory evidence, then each helper independently
|
||||
applies that specific canonical terminal outcome/unlock. Thus an initial negative
|
||||
sync does not deadlock waiting forever without the post-inventory resync.
|
||||
|
||||
Result envelopes are archived before concrete ACK deletion in one SQLite
|
||||
transaction. Historical message identity/output is retained for reconciliation.
|
||||
Inventory mapping preserves source/time/quality/completeness and unsupported states.
|
||||
Live journal permission warnings become permission_denied, not a fake empty success.
|
||||
|
||||
## Helper bootstrap/policy inspection
|
||||
|
||||
Helper normal daemon: `RMM_HELPER_CONFIG=/etc/rmm/helper.json` (root-owned 0600).
|
||||
Both profiles use `/var/lib/rmm-helper/consumption.sqlite` and `executor.lock`.
|
||||
Helper config uses the existing binding, optional independent signing_key_file,
|
||||
agent_uid, socket_gid, socket, shared state, allowed_services, allow_reboot,
|
||||
allow_root_scripts; APT adds its existing sealed apt_provider configuration.
|
||||
|
||||
Public general pin, **planned command, not executed on VM here**:
|
||||
|
||||
```text
|
||||
RMM_HELPER_CONFIG=/etc/rmm/helper.json /usr/local/libexec/rmm-privileged-helper --inspect-general-profile
|
||||
```
|
||||
|
||||
Install the exact JSON as root:rmm-agent 0640 in non-writable root-owned parents,
|
||||
then set RMM_HELPER_POLICY_FILE. It binds profile, device identity/key and exact
|
||||
policy hash. General policy probe uses root socket/peer credentials and a fresh
|
||||
challenge; capabilities reflect actual policy/interpreter availability. Root
|
||||
scripts remain default-off broad administration. Services are exact allowed
|
||||
running/stopped units with >=180s runtime, reboot separately enabled with >=60s.
|
||||
Root jobs are NEVER relabelled into agent_service.
|
||||
|
||||
APT install/probe/inspection modes and profile sandbox remain exactly documented
|
||||
in `apt-helper-README.md`. Both daemons need this same installed build and reviewed
|
||||
new proof hashes (binary bytes are part of the APT proof). Prefetched sealed
|
||||
archives, receipts predating the grant and exact baselines are still prerequisites;
|
||||
this integration introduces no unsafe generic APT download/install/simulation path.
|
||||
Root native-acceptance and accepted-recipe/manifest capabilities come only from
|
||||
authenticated real readiness. Successful native acceptance triggers a controlled
|
||||
reconnect to advertise newly accepted recipes; periodic safe capability refresh
|
||||
also reconnects rather than silently changing the Hello contract.
|
||||
|
||||
## Passive APT planning and declarative no-change
|
||||
|
||||
The normal extended inventory worker now runs at startup and every 60 seconds
|
||||
(one inflight collector; not in the heartbeat handler). Unacknowledged durable
|
||||
traffic backpressures new collection without deleting old data; job results and
|
||||
control receipts retain priority. It includes the fixed
|
||||
`linux.apt.planning` scope from `root-helper:apt_planning_v1`. This currently
|
||||
refreshes the existing extended inventory scopes too; their actual individual
|
||||
source timestamps/quality remain intact. There is no arbitrary package query,
|
||||
requested live diagnosis or software effect hidden in this collector.
|
||||
|
||||
`apt_planning_v1` uses the existing UID-authenticated dedicated Unix socket,
|
||||
fresh challenge, device/generation/signing-key identity, root peer and separately
|
||||
root-provisioned stack pin. Its response is the readiness envelope with a typed
|
||||
`planning` result and **empty capability/acceptance fields**. It does not depend
|
||||
on a prior native-acceptance record and cannot create one. Root validates the
|
||||
installed code, exact runtime/config policy pins and actual archive bytes, sizes,
|
||||
ownership/modes/link count and private prefetch receipts. No artifact is fetched
|
||||
or installed by this RPC. Administratively stage the known fixture archives via
|
||||
`provision-fixture-store` before planning/the final 60-second grant.
|
||||
|
||||
The fixed metadata child has a 4-second whole-process/output budget (32 KiB),
|
||||
the socket has 5-second IO limits, and root measurement timestamps are preserved.
|
||||
Dirty dpkg updates/triggers, foreign locks, unsafe/missing receipts, permission
|
||||
failure, timeout or missing helper yield an unknown observation with null data,
|
||||
not fake hashes or accepted capability. Runtime policy drift fails closed.
|
||||
Complete observations contain the suite's `fixture_package`, `baseline_sha256`,
|
||||
`sealed_baseline_sha256`, `status_fingerprint`, `dpkg_updates_empty`,
|
||||
`pending_triggers_empty`, `runtime`, `runtime_sha256`, `provider_sha256`,
|
||||
`hook_sha256`, `apt_config_sha256` and `prefetch`. The full package baseline stays
|
||||
root-private at `baselines/<sha256>.json`; only hashes, fixture projection and
|
||||
minimal public runtime/artifact pins cross the wire. Stable sampling is checked
|
||||
before and after content-addressed exclusive write/file+directory fsync; existing
|
||||
identical seals are verified, never overwritten. This is passive metadata, not
|
||||
job authority. The ordinary durable inventory outbox/ACK path persists it.
|
||||
|
||||
Normal accepted fixture `ensure_package`/`apply_updates` may return
|
||||
`POSTCONDITION_ALREADY_MET`, `changed=false`, `already_desired=true`,
|
||||
`postcondition_already_met=true`, `transaction_executed=false` only when the
|
||||
**entire selected set** is independently installed at its exact target version
|
||||
and architecture, clean, matches the current approved baseline/fingerprint and
|
||||
has the expected fixture payload. Root signature, all original bindings,
|
||||
expiry/sync/local-policy/resource gates, all manifest/code/runtime/artifact pins,
|
||||
native accepted-recipe record and durable grant/attempt consumption remain
|
||||
mandatory. Only the historical `old_version` condition is skipped in this
|
||||
no-mutation branch. No APT/hook/native launch/effect marker is created. A foreign
|
||||
lock, dirty/unknown state or changed baseline cannot become success; native
|
||||
acceptance itself never uses this branch. Other versions still follow the
|
||||
unchanged no-reinstall/no-downgrade/no-remove mutation guards.
|
||||
|
||||
VM suite owner must update its absent/1.0-only adapter: after native update to
|
||||
1.1, a normal exact desired-1.1 job must use the accepted update recipe with a
|
||||
fresh planning seal. A desired-1.0 job on 1.1 is still correctly denied; this
|
||||
implementation does not authorize removal/downgrade to make a stale test pass.
|
||||
No backend/domain/protobuf signatures or plan bytes have been changed.
|
||||
|
||||
Provider source changes change the embedded provider/helper/stack/runtime pins.
|
||||
Deploy both helpers from this build and provision reviewed new proof/policy
|
||||
pins **before** native acceptance; old native records cannot silently certify
|
||||
new runtime bytes. Manifest schema 2 / transaction schema 1 / fixture archives
|
||||
1.0 and 1.1 (20,672 bytes, unchanged hashes) remain unchanged.
|
||||
|
||||
These are implemented source/local-fixture semantics, not VM or MVP acceptance.
|
||||
|
||||
## Certificate rotation and recovery
|
||||
|
||||
`RMM_AGENT_STATE/certificates/current.json` is the authoritative atomic selector
|
||||
over private versioned device key/cert files. Existing enrolled files initialize
|
||||
the store exactly once; later connections/bootstrap use the selected identity.
|
||||
Rotation checks chain, current validity, exact agent CN, clientAuth purpose and
|
||||
public/private key match. It persists one pending key/CSR and retries those SAME
|
||||
CSR bytes after response loss. A verified swap closes the old actor/effect fence
|
||||
and requires a new Hello/Sync. Agent/enrollment IDs and independent job/helper
|
||||
signing pins do not change. Expired/revoked/invalid certs remain blocked and need
|
||||
authorized identity recovery; no auto-reenrollment or TLS downgrade.
|
||||
|
||||
## Verification boundaries / concrete remaining policy issue
|
||||
|
||||
Local Rust source/unit/integration tests cover actual loopback mTLS dispatcher
|
||||
WSS/HTTPS clean reconnect, Ping, forged sync rejection, passive traffic with an
|
||||
untrusted effect clock, journal reopen/replay and independent helper checkpoint/
|
||||
outcome/boot checks. Unsafe OS providers are mocked or denied; no local service,
|
||||
APT install or reboot was executed. This is not a real WebUI-approved VM result,
|
||||
native package acceptance, production auth acceptance or full Linux-MVP sign-off.
|
||||
|
||||
Concrete backend policy limitation, not bypassed here: `RootScope::permits` in
|
||||
`crates/server/src/root_policy.rs` does not match `Action::QueryLogs` and falls
|
||||
through to false. The typed, bounded root helper log handler exists, and the
|
||||
unprivileged allowlisted path is live, but a root live-log plan will be denied by
|
||||
that backend policy until its owner adds an explicit permitted scope. Do NOT
|
||||
work around it by relabelling identity, direct approval or a generic root shell.
|
||||
|
||||
## Executed local verification
|
||||
|
||||
Using `/home/Kevin/.cargo/bin/cargo`, actually passed during integration:
|
||||
|
||||
```sh
|
||||
cargo test -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked
|
||||
cargo clippy -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked -- -D warnings
|
||||
cargo build -p rmm-agent -p rmm-privileged-helper --locked
|
||||
cargo fmt -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux -- --check
|
||||
python3 tests/agent_jobs/test_install.py
|
||||
target/debug/rmm-agent --help
|
||||
target/debug/rmm-privileged-helper --help
|
||||
```
|
||||
|
||||
111 executed Rust test cases passed (including reused transport tests), two
|
||||
create-only installer guard tests passed, both debug binaries built and both
|
||||
help commands returned successfully without loading secret configuration. No
|
||||
warnings/type errors were suppressed. A boxed tungstenite HTTP-response test
|
||||
constructor was corrected, not bypassed. No coverage percentage was measured.
|
||||
|
||||
Coverage boundaries: real loopback TLS/dispatcher WSS and HTTPS reconnect and
|
||||
forged sync rejection are exercised; helper cryptography/checkpoints/two-process
|
||||
shared signature and replay/unknown/reboot decisions use real SQLite/signatures
|
||||
with local fixtures. Native service/APT/reboot effects and positive root UID-0
|
||||
daemon/VM RPC acceptance are NOT substituted by these tests. The built artifacts
|
||||
are `target/debug/rmm-agent` and `target/debug/rmm-privileged-helper`; a reviewed
|
||||
VM-compatible release artifact still needs the target worker's ELF/glibc/library
|
||||
preflight and actual authorized VM run.
|
||||
|
||||
## Executed local verification — planning/no-change increment
|
||||
|
||||
After **all** source changes, the following complete targeted block passed with
|
||||
`/home/Kevin/.cargo/bin` on PATH (2026-11-12):
|
||||
|
||||
```sh
|
||||
cargo test -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked
|
||||
PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s tests/apt_transaction -p 'test_*.py' -v
|
||||
cargo clippy -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux --all-targets --locked -- -D warnings
|
||||
cargo fmt -p rmm-agent -p rmm-privileged-helper -p rmm-agent-linux -- --check
|
||||
cargo build -p rmm-agent -p rmm-privileged-helper --locked
|
||||
cargo build -p rmm-agent -p rmm-privileged-helper --release --locked
|
||||
python3 tests/agent_jobs/test_install.py
|
||||
target/debug/rmm-agent --help
|
||||
target/debug/rmm-privileged-helper --help
|
||||
```
|
||||
|
||||
Results: **115 Rust tests**, **56 Python APT tests**, **2 installer guard tests**
|
||||
passed; warning-denying all-target Clippy and formatting passed; both Debug and
|
||||
Release binaries built; both help commands succeeded. Separate final AST parsing
|
||||
passed for **8 Python files**. No full workspace/backend/web test suite was run.
|
||||
|
||||
New regressions cover shared Python/Rust canonical golden bytes/hash, receipt
|
||||
and timestamp freshness, private content-addressed seal reuse/change without
|
||||
full-baseline disclosure, sampling drift/dirty/foreign-lock/bad-artifact failure,
|
||||
normal exact already-desired install/update postconditions, no launch/effect
|
||||
markers, old-version mutation rejection, wrong architecture/newer version,
|
||||
audit/payload/expiry rejection, no-change outcome binding and durable duplicate
|
||||
grant/attempt rejection, honest missing-helper data and collection backpressure.
|
||||
Root ownership/kernel state and unsafe native package processes are mocked;
|
||||
existing harmless unprivileged seccomp tests really execute. No native host
|
||||
package mutation, root systemd/probe/VM action, approval or reboot was performed.
|
||||
|
||||
Earlier intermediate failures were corrected, not suppressed: the inherited two
|
||||
unformatted source edits, a mock reader missing the `limit` keyword argument,
|
||||
and a newly inserted function accidentally inheriting a test-only cfg attribute.
|
||||
The final complete block above passed after these corrections.
|
||||
|
||||
Final artifact SHA-256 (native developer-PC builds; **not** Bookworm/VM proof):
|
||||
|
||||
| Artifact | SHA-256 |
|
||||
|---|---|
|
||||
| `target/debug/rmm-agent` | `90a4eab064301740cd938a41a76a510ad3b4abc3e48a188ba12bfe22f123266c` |
|
||||
| `target/debug/rmm-privileged-helper` | `54db2fe17841fef9af48bbeb446f45bda52f62e442a4900e0543e358095900b7` |
|
||||
| `target/release/rmm-agent` | `eac5434fd7a1e509c0971e4e05d4e1aedbde1bb90f7d7a8f9ec4d48ab4d34597` |
|
||||
| `target/release/rmm-privileged-helper` | `581a033478b41365066df2dc9ac0d11e314160909b5fab612be0be97be1bbbdc` |
|
||||
| `tools/apt-transaction/apt_transaction.py` | `57b695bf57ea2703393e39f92a1b6ef2314b4838f3dfb29e4e70da79687c9987` |
|
||||
|
||||
Remaining: suite-owner adapter update for exact desired 1.1 after native upgrade,
|
||||
reviewed deployment/new pins, actual dedicated-profile metadata RPC and native
|
||||
UI-approved fixture/no-change VM proof, target ELF/library compatibility, and
|
||||
VM resource/retention measurements for the new 60-second extended collection.
|
||||
No real current baseline change was induced on the host/VM: freshness tests use
|
||||
changed temporary/mock package state, not a disguised package installation.
|
||||
Linux-MVP and production acceptance remain open. Backend Root QueryLogs policy
|
||||
is owned by its separate worker and was neither changed nor reverified here.
|
||||
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
|
||||
volumes:
|
||||
- ../devstate/managed-scripts:/managed-scripts:ro
|
||||
public-api:
|
||||
environment:
|
||||
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
|
||||
volumes:
|
||||
- ../devstate/managed-scripts:/managed-scripts:ro
|
||||
gateway:
|
||||
environment:
|
||||
RMM_MANAGED_SCRIPT_POLICY_FILE: /managed-scripts/policy.json
|
||||
volumes:
|
||||
- ../devstate/managed-scripts:/managed-scripts:ro
|
||||
@@ -21,11 +21,13 @@ services:
|
||||
RMM_BOOTSTRAP_ORIGIN: https://discovery.ease-technologies.de:8443
|
||||
RMM_AGENT_UPDATE_ARTIFACT_DIR: /release-objects
|
||||
RMM_AGENT_UPDATE_LINUX_KEYRING_FILE: /release-config/linux-keyring.json
|
||||
RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE: /release-config/linux-arm64-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE: /release-config/windows-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE: /release-config/windows-gnu-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE: /release-config/windows-gnu-official-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_FILE: /release-config/linux-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE: /release-config/linux-arm64-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_FILE: /release-config/windows-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-official-bootstrap.json
|
||||
ports: ["127.0.0.1:18445:18443"]
|
||||
volumes:
|
||||
- ../devstate/api-pki:/pki:ro
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
x-release-environment: &release-environment
|
||||
RMM_AGENT_UPDATE_ARTIFACT_DIR: /release-objects
|
||||
RMM_AGENT_UPDATE_LINUX_KEYRING_FILE: /release-config/linux-keyring.json
|
||||
RMM_AGENT_UPDATE_LINUX_ARM64_KEYRING_FILE: /release-config/linux-arm64-keyring.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_KEYRING_FILE: /release-config/windows-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_FILE: /release-config/linux-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_LINUX_ARM64_FILE: /release-config/linux-arm64-bootstrap.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_FILE: /release-config/windows-bootstrap.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_KEYRING_FILE: /release-config/windows-gnu-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-bootstrap.json
|
||||
RMM_AGENT_UPDATE_WINDOWS_GNU_OFFICIAL_KEYRING_FILE: /release-config/windows-gnu-official-keyring.json
|
||||
RMM_AGENT_BOOTSTRAP_WINDOWS_GNU_FILE: /release-config/windows-gnu-official-bootstrap.json
|
||||
|
||||
services:
|
||||
api:
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
# Native gemeinsame Core-Unitabnahme
|
||||
|
||||
**Persistenzprofil tatsächlich ausgeführt, 2026-11-14:**
|
||||
Fall `08a9be72-dd7c-46b7-a2c6-7d17424533c2`, Linux76 vor Windows54, ohne Skip.
|
||||
Getrennte eigene SQLite-/Signaturfixturen, keine native Job-/Dienstabnahme.
|
||||
|
||||
**Helper-Sync-Profil tatsächlich ausgeführt, 2026-11-14:**
|
||||
Fall `5704073c-a135-431c-aa84-fedc68a3de0b`, Linux 69/69 vor Windows 47/47,
|
||||
keine Skips oder RMM-Wirkung. Auch dies ersetzt keine Windows-SYSTEM-Dienstprobe.
|
||||
|
||||
`shared_core_acceptance.py` führt ausschließlich die zwei source-/hashgebundenen
|
||||
Testprogramme `contracts` und `reconcile` aus: eigene temporäre SQLite-Fixturen,
|
||||
Testsignaturen, Fake-Clock und Fake-Channel. Keine RMM-Jobs, Hello-Wirkung,
|
||||
Enrollment, Schlüsselzugriffe, Runtimeersetzung, Dienste oder Serverkontakte.
|
||||
Die Tests enthalten keine Netzwerkstrecke; der Runner behauptet keine zusätzliche
|
||||
OS-Netzwerksandbox. Bootstraptransport bleibt vorhandenes hostkeygeprüftes SSH/SFTP.
|
||||
|
||||
**Tatsächlich ausgeführt, 2026-11-14:**
|
||||
|
||||
```sh
|
||||
python3 deploy/shared_core_acceptance.py linux
|
||||
python3 deploy/shared_core_acceptance.py windows --case-id 4bc4db12-2990-4e93-bb86-8fbd94b691fb
|
||||
```
|
||||
|
||||
Fall `4bc4db12-2990-4e93-bb86-8fbd94b691fb`: Linux 25/25 und danach Windows
|
||||
24/24 nativ bestanden, jeweils ohne Skip. Permanente Dienste wurden nicht
|
||||
ersetzt; insbesondere kein Windows-Job- oder Dienst-Syncnachweis daraus.
|
||||
|
||||
Der Runner prüft beide privaten Qualifikationsmanifeste, sämtliche gebundenen
|
||||
Quellhashes und genau zwei Artefakte. Linux läuft zuerst (5+20 Fälle). Windows
|
||||
(4+20 Fälle) verlangt denselben gespeicherten vollständigen Linux-Nativbeleg und
|
||||
bindet dessen SHA256. Alle Fälle müssen erfolgreich und ohne Skip ausgeführt sein.
|
||||
Exakte Testargumente: ausschließlich `--test-threads=1`.
|
||||
|
||||
Lokale Intent-/Start-/Readback-/PASS-Dateien unter
|
||||
`devstate/shared-core/acceptance/<UUID>/` entstehen create-only. Remote nur eigene
|
||||
geschützte Bootstrap-Testverzeichnisse: Linux
|
||||
`/var/lib/rmm-shared-core-acceptance/<UUID>/<SHA256>/`, Windows bestehendes
|
||||
`C:\ProgramData\RustDiscoveryBootstrap\<SHA256>\windows-core-*.exe` und eigener
|
||||
`shared-core-<UUID>`-Fall. Ausgaben/Fehler bleiben privat; stdout enthält nur
|
||||
sanitisierten Status und bei PASS Fall-/Artefakt-/Nachweishashes.
|
||||
|
||||
Bei verlorener Ausführungsantwort **nicht erneut starten**. Ausschließlich
|
||||
vorhandene Remotequittungen lesen:
|
||||
|
||||
```sh
|
||||
# GEPLANT, NICHT AUSGEFÜHRT: keine erneute Testausführung.
|
||||
python3 deploy/shared_core_acceptance.py finish-linux --case-id <UUID>
|
||||
python3 deploy/shared_core_acceptance.py finish-windows --case-id <UUID>
|
||||
```
|
||||
|
||||
Fehlt eine Quittung, bleibt die Abnahme unvollständig; kein automatisches Resume,
|
||||
keine Bereinigung oder Wiederholung. Native Unittests ersetzen weder den späteren
|
||||
Linux-Dienst-Syncnachweis des extrahierten Kerns noch Windows-WebUI-/Clock-/
|
||||
Prozess-/Jobabnahmen. Der aktuelle Windowsclient erhält dadurch keine Jobfähigkeit.
|
||||
|
||||
## Nachfolgendes festes Profil `helper-sync-v1`
|
||||
|
||||
Eigenständige neue Qualifikationsmanifeste/Artefakte unter
|
||||
`devstate/shared-core/helper-sync-v1/` und `devstate/windows-core/helper-sync-v1/`;
|
||||
Originalartefakte, Manifeste und deren native Fälle bleiben unverändert.
|
||||
Das feste Profil prüft Linux **5+21+22+21=69** Fälle, zuletzt den bestehenden
|
||||
Linuxhelper mit echtem Unix-ExecutorGuard und Bootquelle an eigenen Fixturen.
|
||||
Erst dessen vollständiger Nativbeleg erlaubt Windows **4+21+22=47** Fälle.
|
||||
Portable Helperfälle verwenden einen ausdrücklich simulierten Ledgerguard und
|
||||
qualifizieren keine Windows-Pipe, Volume-/File-ID oder SYSTEM-Wirkung.
|
||||
|
||||
```sh
|
||||
# GEPLANT, NICHT AUSGEFÜHRT: Parent übernimmt tatsächliche VM-Ausführung.
|
||||
python3 deploy/shared_core_acceptance.py linux --profile helper-sync-v1
|
||||
python3 deploy/shared_core_acceptance.py windows --profile helper-sync-v1 --case-id <UUID>
|
||||
# Bei verlorener Antwort weiterhin nur lesen, mit demselben festen Profil:
|
||||
python3 deploy/shared_core_acceptance.py finish-linux --profile helper-sync-v1 --case-id <UUID>
|
||||
python3 deploy/shared_core_acceptance.py finish-windows --profile helper-sync-v1 --case-id <UUID>
|
||||
```
|
||||
|
||||
Profil, Quellen und Artefakte sind an den privaten create-only Intent gebunden.
|
||||
Es gibt weiterhin keinen frei wählbaren Programmpfad oder Argumentvektor.
|
||||
|
||||
## Persistenzkorrektur `durable-outcome-v1`
|
||||
|
||||
Neue unveränderliche Qualifikation unter `devstate/*core/durable-outcome-v1/`.
|
||||
Das feste Profil erwartet Linux **7+26+22+21=76**, danach Windows **6+26+22=54**.
|
||||
Lokale Regressionen und Cross-Builds sind im Manifest separat von der noch
|
||||
geplanten tatsächlichen VM-Ausführung ausgewiesen. Kein früherer Nachweis wird
|
||||
umgeschrieben. Vorläufige verworfene Builds sind ausdrücklich unqualifiziert.
|
||||
|
||||
```sh
|
||||
# GEPLANT, NICHT AUSGEFÜHRT: tatsächliche VM-Ausführung durch Parent.
|
||||
python3 deploy/shared_core_acceptance.py linux --profile durable-outcome-v1
|
||||
python3 deploy/shared_core_acceptance.py windows --profile durable-outcome-v1 --case-id <UUID>
|
||||
```
|
||||
|
||||
Die gezielten Fälle prüfen atomaren Verbrauch+Startzeugen, Original-Outcome-CAS,
|
||||
Crash vor/nach Resultcommit, Reconnect-Unknown mit späterer Originalcompletion
|
||||
und die weiterhin verweigerte Freigabe bei fehlendem lokalen Outcome.
|
||||
Startup journalisiert ausschließlich bereits gebundene gespeicherte Belege neu;
|
||||
Unknown ohne solchen Beleg bleibt gesperrt. Server-/Unlockregeln bleiben strikt.
|
||||
Dies simuliert Commitgrenzen mit eigenen Fixtures; es ersetzt keinen späteren
|
||||
wirklichen Agentprozessabsturz oder unabhängigen SYSTEM-Helperabschlussnachweis.
|
||||
@@ -1,108 +0,0 @@
|
||||
# Preserving Linux shared-core runtime qualification
|
||||
|
||||
The notebook only builds and orchestrates. The fixed Cloud Linux VM remains the
|
||||
client; `discovery.ease-technologies.de` remains the server. These bootstrap
|
||||
tools never create or approve an RMM job, enroll, reset a journal, install a
|
||||
package or reboot the guest.
|
||||
|
||||
The original `cloud_shared_core_upgrade.py` remains frozen at SHA-256
|
||||
`09b60e99e1bf92dbaa60f0b0a64f9b94e3cefebb110d558b14c381293cbde873`.
|
||||
Its case `2f8de8b9-2abe-4125-aa12-ae38332a32c6` stopped before any binary exchange:
|
||||
the generic `nlink == 1` check rejected an existing valid APT publication pair.
|
||||
The original failed report, staged binaries and APT records remain retained.
|
||||
`cloud_shared_core_failed_restore.py` restarts only the verified original
|
||||
runtime, once; its saved actual readback is required before a new V2 case.
|
||||
|
||||
V2 is a source copy with a narrow alias admission and earlier object checks:
|
||||
`cloud_shared_core_upgrade_v2.py`, SHA-256
|
||||
`d4f857b8ff6e7d9802f863a120a1576ffac5b36facb6a259149409ef25bfbc91`.
|
||||
The only permitted alias paths are under `/var/lib/rmm-apt-transaction/`:
|
||||
|
||||
- `acceptance-rmm-apt-fixture-update-1.1.json`
|
||||
- `pending-acceptance-rmm-apt-fixture-update-1.1.json`
|
||||
|
||||
Both must retain device `2049`, inode `1028362`, UID `0`, GID `984`, regular-file
|
||||
mode `0600`, link count `2`, and SHA-256
|
||||
`a88d6b10bbf6c36eaa8dee87eb1a381f2becc36297db8df2b4189791b9165506`.
|
||||
That content hash comes from the original verified, UI-approved native APT
|
||||
update result. The mode is the actual stored `lstat` value `33152` (`0100600`).
|
||||
Neither name is rewritten, unlinked or chmodded. Other hardlinks, symlinks and
|
||||
unexpected nonregular state objects remain rejected.
|
||||
|
||||
The qualified `durable-outcome-v1` release artifacts remain:
|
||||
|
||||
| Artifact | SHA-256 |
|
||||
|---|---|
|
||||
| Linux agent | `c9c09de0ecb52b556d707cf45accb69186c73b8ec9baeeabfaeff220fafb1d4e` |
|
||||
| Linux helper | `51c3142ab332216d6a94ff64ff15cbc37ee1d5a99896c14c87bb6f62e63bb946` |
|
||||
| Unchanged APT provider | `1dc0237dd8df9c9d22568bb1f6b047ede73bc2a5fca5c7fcedb7f24ab2a58b1e` |
|
||||
|
||||
Planned, not executed by this preparation:
|
||||
|
||||
```text
|
||||
python3 deploy/cloud_shared_core_upgrade_v2.py prepare --restore-readback <exact-private-original-case-readback.json>
|
||||
python3 deploy/cloud_shared_core_upgrade_v2.py install <new-case-id>
|
||||
python3 deploy/cloud_shared_core_upgrade_v2.py finish <same-new-case-id>
|
||||
```
|
||||
|
||||
Each new intent binds both runner hashes, the restore readback, actual alias
|
||||
metadata, original APT checkpoint, release qualifications and the Linux-MVP
|
||||
closeout. Local cases use `devstate/shared-core/runtime-upgrade-v2/`; remote
|
||||
cases use `/var/lib/rmm-bootstrap-history/shared-core-v2-<id>`. A durable
|
||||
installation receipt forbids repeating installation, including after a lost
|
||||
reply; only readback/finish of that same case is permitted.
|
||||
|
||||
The pre-restart preservation checks run under both existing locks. Old
|
||||
consumptions, outcomes, signatures, database identities, trust and backup
|
||||
witnesses remain bound. Private key contents are never read or exported.
|
||||
General policy/pin remain unchanged, `allow_reboot=false`; the APT endpoint
|
||||
stays closed and its historical runtime pins remain stale. Native mTLS/Sync,
|
||||
MCP and central-count qualification are separate final acceptance steps.
|
||||
|
||||
V2 preparation checks passed locally: Python syntax, fixed RPC globals, source
|
||||
format, all 65 qualified release source bindings and the existing native Linux76
|
||||
core-unit receipt. This document does not claim native V2 installation success.
|
||||
|
||||
## Retained native bootstrap assertion failures
|
||||
|
||||
The original V1 failure above was a bootstrap verifier error: the existing
|
||||
legitimate APT hardlink publication was rejected. Neither alias was repaired or
|
||||
rewritten. Its original-runtime restart and actual readback were separately
|
||||
recorded before the new V2 case.
|
||||
|
||||
V2 case `a2423612-721f-4a6c-a832-b9eef549c41e` subsequently reached the persisted
|
||||
`installed_preserved` stage: both new binaries were installed, all pre-restart
|
||||
data witnesses matched, and both daemons started. Its last verifier assertion
|
||||
incorrectly compared process GID with the account's primary passwd GID. Actual
|
||||
readback showed the expected service identity, UID993/GID984, matching the
|
||||
independently verified Linux-MVP closeout. This was a second bootstrap verifier
|
||||
error; the report remains `completed=false` and is never rewritten as success.
|
||||
|
||||
`cloud_shared_core_upgrade_attestation.py` is a separate read-only supplement
|
||||
for that exact case. It rechecks preserved rows/schema/inodes/trust/backups and
|
||||
the actual process identity, and binds the stored native VM/server Sync114
|
||||
evidence to the retained exact signed decision and request. It does not start
|
||||
services, retry installation, change SQL, alter the original report, or create
|
||||
jobs. Its prepared SHA-256 is
|
||||
`59b20ecd2d32ea3b37f2840868eb67ce677ffdb967e079a667e53c7907fce86b`.
|
||||
|
||||
## Actual read-only closeout, 2026-11-14
|
||||
|
||||
The supplemental attestation was actually executed and passed; its protected
|
||||
receipt is `readonly-attestation-63730c38-327e-4635-802f-8289c28081de.json`
|
||||
inside the V2 case. A prior strict row-hash readback rejected28 cached outcome
|
||||
references that normal signed Sync had renewed. Only those reference changes
|
||||
were then independently proven: reconstruct the original complete row hash with
|
||||
identical job/attempt/outcome bytes and the preserved original decision ID;
|
||||
verify both original Ed25519 decisions and the exact applied request/response,
|
||||
grant/plan/outcome binding and monotonic journal history. All other historical
|
||||
rows remain byte-identical. No general outcome exemption or state rewrite.
|
||||
|
||||
Native MCP subsequently read the existing Linux device online, rejected the
|
||||
foreign tenant, and confirmed unchanged30/30/26/0 central counts. Agent/helper
|
||||
and server share the ready signed Sync114; original18 Root consumptions remain
|
||||
closed. `devstate/cloud-shared-core-current-runtime.json` binds both actual
|
||||
attestation and MCP receipts. It supplements the preserved historical MVP
|
||||
closeout and does not requalify APT for the new binary hashes. All original
|
||||
failure reports remain unchanged, and no installation or service start was
|
||||
repeated to obtain this read-only closeout.
|
||||
@@ -1,231 +0,0 @@
|
||||
# Windows-Client: erster nativer Entwicklungsstand
|
||||
|
||||
Stand 2026-11-13, Spezifikation 1.15. Windows-11-Gast und Notebook-Host sind
|
||||
verschiedene Geräte. Auf dem Notebook laufen ausschließlich Entwicklungstools;
|
||||
der Client verwendet den endgültigen Cloudserver `discovery.ease-technologies.de`.
|
||||
|
||||
Neuer Quellenstand 2026-11-15: [passive Zertifikatserneuerung](../../docs/windows-certificate-renewal.md)
|
||||
mit geschützter Keydatei und atomarer Versionswahl ist implementiert; native
|
||||
Windows-Renewal-/Abbruch-/DACLabnahme und Freigabe der permanenten Identität
|
||||
bleiben offen. Frühere Transportabnahmen darunter bleiben historische Belege.
|
||||
|
||||
## Aktueller Dienst dauerhaft auf Auto — 2026-11-13
|
||||
|
||||
Nach dem bestandenen Fallbacktest wurde die bestehende VM im separaten Fall
|
||||
`422562e8-18eb-4865-977d-ab2af65f510b` dauerhaft auf `transport=auto` gestellt.
|
||||
WSS bleibt bevorzugt; zwei frische WSS-Heartbeats und ein konkretes Inventar-ACK
|
||||
sind unter dem tatsächlichen LocalService (`S-1-5-19`) nativ nachgewiesen.
|
||||
Binary, Geräteidentität, CA, Zertifikat, Schlüssel, ACLs und Telemetriehistorie
|
||||
blieben erhalten. Beide Server-Testhooks bleiben deaktiviert; Serverkonfiguration
|
||||
und Rootpolicy wurden bei dieser Umstellung nicht verändert. Windows bleibt bei
|
||||
0 Jobs/Outbox/Grants/ungeklärten Wirkungen, Linux unverändert bei 30/30/26/0.
|
||||
|
||||
Der verifizierte geschützte Beleg liegt unter
|
||||
`devstate/windows-client/auto-default/422562e8-18eb-4865-977d-ab2af65f510b/result.json`.
|
||||
`devstate/windows-client/current-transport.json` bindet ihn per Hash und hält den
|
||||
aktuellen Transport getrennt von historischen Abnahmen fest. Originalkonfiguration
|
||||
und ACLs bleiben versioniert für eine ausdrückliche Wiederherstellung erhalten.
|
||||
Die Installerquelle verwendet ebenfalls `auto`; eine frische Installation wurde
|
||||
damit nicht ausgeführt. Fünf gezielte lokale Schutztests sowie Parserprüfungen
|
||||
bestanden. Es wurden keine Windows-Jobs oder Reboots ausgeführt.
|
||||
|
||||
## Automatischer WSS→HTTPS-Fallback nativ bestanden — 2026-11-13
|
||||
|
||||
Eigener Fall `2ff2e1aa-0037-4831-9bc2-31218bf1461c` auf derselben bestehenden
|
||||
Windows-Identität unter LocalService. Nur der eigene Agenttransport wurde
|
||||
versioniert auf `auto` gestellt. Zunächst zwei frische WSS-Heartbeats;
|
||||
dann exakt gerätegebundene, zehn Minuten gültige dev/test-Störung.
|
||||
Zwei tatsächliche mTLS-authentisierte HTTP503 bei WSS, mit unterschiedlichen
|
||||
Handshake-IDs und den festen Slots1/2, Zertifikatsfingerprint und Config-Hash.
|
||||
Der Agent wechselte selbst zu HTTPS; zwei frische HTTPS-Heartbeats und konkreter
|
||||
Inventar-ACK nach beiden Verweigerungen tatsächlich gespeichert.
|
||||
|
||||
Gleiche Agent-/Asset-/Enrollment-/Zuordnungsversion und Dateien/ACLs, monotone
|
||||
Sequenz, TenantB weiter verweigert. Kein neuer RMM-Job: Windows vor/nach
|
||||
0Jobs/0Outbox/0Grants/0offen; Linux unverändert30/30/26/0. Zentrale Rootpolicy
|
||||
unverändert. Beide realen Serverrollen danach mit Faultflagfalse und ohne
|
||||
konfigurierten Fault-Dateipfad; exakte ursprüngliche WSS-Konfigurationsbytes und
|
||||
ACLs auf Windows restauriert, wieder zwei frische WSS-Heartbeats/ACK0.
|
||||
Dies ist keine Behauptung eines automatischen HTTPS→WSS-Switchbacks: Rückkehr
|
||||
folgte aus der ausdrücklichen operativen Wiederherstellung der Konfiguration.
|
||||
|
||||
Ausgeführt: `python3 deploy/windows/auto_transport_acceptance.py start
|
||||
--https-case 3c60e1a8-7ab7-4720-8b1a-f89f4f0d7458`.
|
||||
Sechs gezielte lokale Guards ergänzen den nativen Nachweis; kein neuer
|
||||
Clientbuild und keine Windows-Syncbereitschaft erfunden. Geschützt:
|
||||
`devstate/windows-client/auto-transport/2ff2e1aa-0037-4831-9bc2-31218bf1461c/result.json`,
|
||||
verifiziert. Am Ende dieses Testfalls lief der Dienst wieder mit ursprünglichem
|
||||
WSS. Die anschließende dauerhafte Auto-Umstellung ist oben separat dokumentiert.
|
||||
|
||||
## TLS-Negativfälle auf Windows nativ bestanden — 2026-11-13
|
||||
|
||||
Feste getrennte Fixture `7b190a5c-c928-4348-bd0d-c9698dad5417`, Schlüssel auf
|
||||
Windows erzeugt und dort behalten. Nur öffentliche CSR zum bestehenden
|
||||
Cloudsignierer, ausschließlich öffentliche CA-/Clientzertifikate zurück.
|
||||
Unregistrierte gültige Kontrolle vor und nach den Negativfällen: tatsächliches
|
||||
HTTP401 nach erfolgreichem TLS. Falsche CA: `TLS_UNKNOWN_ISSUER`; falscher
|
||||
Servername: `TLS_SERVER_NAME_MISMATCH`; abgelaufenes Clientzertifikat:
|
||||
`TLS_PEER_CERTIFICATE_EXPIRED`, jeweils ohne HTTP-Antwort. Alle fünf nativen
|
||||
Probeprozesse mit dem gemeinsamen `https_channel::mtls_client` bestanden.
|
||||
|
||||
Dies sind ausdrücklich Admin-TLS-Proben, keine LocalService- oder
|
||||
Rotationsabnahme. Der tatsächliche LocalService-HTTPS-Pfad ist separat unten
|
||||
nachgewiesen. Permanenter Dienst samt PID/Startkonto, Identität, öffentliche
|
||||
Zertifikatsdateien und private Schlüsseldateimetadaten vor/nach identisch.
|
||||
Keine Dienstoperation, Registrierung, Jobs, Uhränderung oder TLS-Ausnahme.
|
||||
|
||||
Erster Lauf blieb bei unbekannt klassifiziertem CA-Fehler sicher verweigert.
|
||||
Typinformation wurde in verschachtelten io::Error-Quellen übersprungen;
|
||||
gezielter get_ref-Fix samt Test erkennt den echten Rustlsfehler, ohne Timeout,
|
||||
Reset oder Fehlertexte als Zertifikatsablehnung zu werten. Ein Retest wurde
|
||||
vor TLS durch einen Bootstrap-Witness-Timeout unterbrochen. Kurzer begrenzter
|
||||
Witness und erneute Prüfung derselben unveränderten öffentlichen Fixtures
|
||||
bestanden, ohne neue CSR/Signierung/Keyerzeugung. Alte Ergebnisse bleiben erhalten.
|
||||
|
||||
Verifiziertes Ergebnis unter
|
||||
`devstate/windows-client/tls-negative/7b190a5c-c928-4348-bd0d-c9698dad5417/typed-retest-6dd51cc0-deb5-4020-afee-58dbb716cdbb/result.json`.
|
||||
Qualifizierte Probe SHA256
|
||||
`33eb56500908a88e3ff30cc1e61f9416e38d94fbf27633ac6dfaf9903cd4ef1b`:
|
||||
gelockter Windows-GNU-Releasebuild, Clippy mit-Dwarnings, gezielter verschachtelter
|
||||
TLS-Fehlertest und Python-/PowerShell-Parserprüfungen bestanden.
|
||||
Ausgeführt: `python3 deploy/windows/tls_acceptance.py --execute-native-tls-negative
|
||||
--artifact devstate/windows-client/WindowsTlsProbe.exe --resume-case
|
||||
7b190a5c-c928-4348-bd0d-c9698dad5417`.
|
||||
|
||||
## Native HTTPS-Abnahme zusätzlich bestanden — 2026-11-13
|
||||
|
||||
Der bestehende LocalService-Agent wurde im festen Fall
|
||||
`3c60e1a8-7ab7-4720-8b1a-f89f4f0d7458` administrativ und versioniert von WSS auf
|
||||
explizites HTTPS umgestellt. Keine neue Identität, kein Enrollment, kein RMM-Job.
|
||||
Tatsächlicher serverseitiger Transport `https`, zwei frische Heartbeats um
|
||||
22:21:14.183598 und22:21:45.234313 UTC. Der native Readonly-Journalbeleg bestätigt
|
||||
Integrität, gleiche Identität, monotone Sequenz935→941 und0 ausstehende
|
||||
Inventarereignisse nach konkretem ACK. Tatsächlicher Prozessowner `S-1-5-19`
|
||||
(LocalService); unverändertes qualifiziertes Programm, CA, Zertifikat, privater
|
||||
Geräteschlüssel und deren ACLs. Private Schlüssel blieben auf der VM.
|
||||
|
||||
Anschließend exakt ursprüngliche WSS-Konfigurationsbytes und ACLs wiederhergestellt,
|
||||
zweimal frischer WSS-Kontakt sowie abgeschlossener Inventar-ACK nachgewiesen.
|
||||
Beide fremden Tenantzugriffe verweigert; vorher/nachher0Jobs/0Outbox/0Grants/
|
||||
0offene Versuche. `result.json` ist verifiziert. Geschützte Belege:
|
||||
`devstate/windows-client/transport/3c60e1a8-7ab7-4720-8b1a-f89f4f0d7458/`.
|
||||
|
||||
Ausgeführt: `python3 deploy/windows/transport_acceptance.py start`.
|
||||
Der Runner verwendet einen per Hash und SFTP gepinnten Bootstrap-PowerShellcode;
|
||||
prozessbezogenes RemoteSigned ändert keine Maschinen-/Gruppenrichtlinie und
|
||||
keine RMM-Jobausführung. Sieben gezielte lokale Runner-Guards und drei
|
||||
PowerShell-Parserprüfungen bestanden; kein neuer Clientbuild für diese Abnahme.
|
||||
TLS-Negativfälle und automatischer Fallback sind oben separat nativ abgenommen.
|
||||
PowerShell-Jobs bleiben bis zu [ihren Voraussetzungen](../../docs/windows-job-boundary.md)
|
||||
gesperrt. Die folgenden Erstnachweise bleiben historisch erhalten.
|
||||
|
||||
## Tatsächlich nachgewiesen
|
||||
|
||||
`rmm-agent-windows` als eigene Plattform-Crate mit gemeinsamen Domain-/Protobuf-
|
||||
Verträgen und direkt wiederverwendeten WSS-/HTTPS-/TLS-Modulen des Linux-Agenten.
|
||||
Isolierter Docker-Crossbuild mit Rust 1.99.1 für `x86_64-pc-windows-gnu`:
|
||||
Debug und Release erfolgreich; Windows-target Clippy über alle Targets mit
|
||||
`-D warnings` erfolgreich. Zwei gezielte Domain-Tests prüfen die unveränderte
|
||||
Linux-Validierung, Windows ohne erfundene Inodes und abgewiesene Plattformmischung.
|
||||
Das sind ergänzende lokale Prüfungen, keine nativen Windows-Dienstnachweise.
|
||||
|
||||
Releaseartefakt SHA256
|
||||
`31e360e50b177b4d5729d24e436d4f25aeed7b1a7bd35f2a129841ba1abffd37`
|
||||
auf der tatsächlichen Windows-11-Pro-VM (Version 10.0.26300, x64) gestartet:
|
||||
`--native-probe` erfolgreich. Hostname und Systemvolume tatsächlich über Win32
|
||||
lesbar; Bootkennung aus `Win32_OperatingSystem.LastBootUpTime` abgeleitet statt
|
||||
bei jedem Agentstart neu erzeugt. Inodes ausdrücklich `null`/nicht anwendbar.
|
||||
Keine Schlüssel oder realen Hostnamen in der veröffentlichten Probeausgabe.
|
||||
|
||||
Binärtransfer über bestehendes, hostkeygeprüftes SFTP mit SHA256-Nachprüfung.
|
||||
Große PowerShell-Console-JSON-Eingaben waren als Bootstraptransport ungeeignet
|
||||
(Timeout/Console-Reader-Ausnahme); deshalb nur kleine zeilenbegrenzte Metadaten
|
||||
über stdin. SSH-/Hostkeyprüfung und Reverse-Portgrenzen bleiben unverändert.
|
||||
Artefaktverzeichnisse werden nach Hash neu angelegt, keine vorhandene Identität
|
||||
oder Historie gelöscht. Private Evidenz: `devstate/windows-client/`.
|
||||
|
||||
## Nativer Dienst, Inventar und verbleibender Umfang
|
||||
|
||||
- Nativer SCM-Dienstlebenszyklus als `LocalService` mit eigenem
|
||||
Service-SID-Zugriff auf Zustand und ausschließlich lesbarem Programm/Config.
|
||||
- Windows prüft Owner/DACL und verweigert Reparse-Points/breite ACLs. Geräteschlüssel
|
||||
werden nur auf Windows erzeugt; Enrollment über CA- und namensgeprüftes TLS,
|
||||
danach mTLS. Ein verlorener Enrollmentnachweis löst keinen Identitätsreset aus.
|
||||
- SQLite mit FULL-Synchronisierung, Prozesssperre, monotoner persistenter Sequenz,
|
||||
konkretem ACK und begrenzter Telemetriequeue. Kein Löschen für Platzgewinn.
|
||||
- Separate `windows.base`-Beobachtungen mit Erhebungszeit/Quelle/Qualität; Server
|
||||
bindet den Scope an die authentisierte Verbindung und deren Capability.
|
||||
Geräte-API zeigt die gespeicherte Quelle statt eines festen Linuxlabels.
|
||||
- Ausschließlich `windows.base/1` und `heartbeat/1` werden angeboten.
|
||||
**Kein Jobexecutor, keine PowerShell-Jobfähigkeit, kein privilegierter Helper.**
|
||||
Angebote/Startgrants werden verweigert. Es gibt keine Genehmigungsabkürzung.
|
||||
|
||||
Tatsächlich installiert und gestartet: nativer SCM-Dienst mit eigenem Service-SID
|
||||
unter `NT AUTHORITY\LocalService`; tatsächlicher Prozessowner `S-1-5-19`, nicht
|
||||
Administrator/SYSTEM. Eigener Geräteschlüssel auf Windows erzeugt, einmaliges
|
||||
Enrollment erfolgreich und Tokenkopie entfernt; mTLS-Hello und frischer Heartbeat
|
||||
serverseitig bestätigt. Der erste `.ps1`-Aufruf wurde durch die lokale
|
||||
Ausführungsrichtlinie vor jeder Installerwirkung verweigert. Verzeichnis, Dienst
|
||||
und Identität waren nachweislich nicht angelegt; erst danach kontrollierte
|
||||
Fortsetzung mit explizit **prozessbezogenem** `RemoteSigned` wie beim ursprünglichen
|
||||
Bootstrap. Keine Änderung der Maschinen-/Gruppenrichtlinie, keine Jobausnahme.
|
||||
|
||||
Native Rust-Testprogramme direkt über den gepinnten SSH-Zugang ausgeführt:
|
||||
**3 Transporttests + 3 Bibliothekstests + 1 ACL-Integrationstest bestanden**. Diese prüfen Namens-/URL-
|
||||
Validierung und sichere Fallbackauswahl, echte Windows-Inventardaten, zwei
|
||||
unabhängige stabile Bootabfragen sowie SQLite-Reopen, monotone Sequenz,
|
||||
Prozesssperre, gezielten ACK und Identitätsbindung. Der zusätzliche native ACL-Test
|
||||
weist korrekte ACLs nach und verweigert breite ACLs, NULL-DACLs, falschen Pfadtyp
|
||||
und Reparse-Points an ausschließlich neu erzeugten nichtgeheimen Tempfixtures. PowerShell-Pipelinewrapper
|
||||
warteten bei nativen Testprogrammen; direkte native Ausführung lieferte Exit 0.
|
||||
|
||||
Der tatsächliche Online-Lauf fand eine weitere echte Grenze: Migration 0001
|
||||
beschränkte `observations.source_id` auf `linux.base`. Daher bisher Heartbeats,
|
||||
aber kein gespeichertes Windowsinventar. Additive Migration 0013 erweitert nur
|
||||
diesen CHECK auf die beiden validierten Basisscopes. Echter isolierter PostgreSQL-
|
||||
Test der Migrationen 1–13 bestanden: alte Linuxzeile bytegleich, Windows erlaubt,
|
||||
beliebiger Scope verweigert, RLS bei fremdem/fehlendem Kontext und zusammengesetzter
|
||||
Geräte-FK erhalten, keine Jobs/Outbox/Grants. Cloudmigration 0013 anschließend tatsächlich erfolgreich. Der ursprüngliche
|
||||
Windows-Journaleintrag wurde ohne Neuerhebung/Identitätsreset erneut zugestellt
|
||||
und gespeichert: ursprüngliches `observed_at` bleibt erhalten, `received_at` ist
|
||||
separat. Geräte-API/MCP melden `source_id=windows.base`, korrektes Windowsinventar
|
||||
und Inodes `null`; zwei verschiedene frische Heartbeats und `online` belegt.
|
||||
Mandant B wurde sowohl für den A-Kontext als auch für seine eigene Mandantensicht
|
||||
mit der fremden Asset-ID abgewiesen. Gerätespezifisch **0 Jobs / 0 Outbox /
|
||||
0 Startgrants / 0 offene Versuche**. Keine WebUI-Genehmigung ausgeführt, weil diese
|
||||
Strecke ausschließlich passive Standardbeobachtungen verarbeitet.
|
||||
|
||||
Dieser erste Entwicklungsbuild ist **unsigniert**. Kein produktiver signierter
|
||||
Installer/MSVC-Supportnachweis, keine Zertifikatsrotations-/Widerrufs-/Proxy- oder
|
||||
Windows-Paket-/Dienstaktionsabnahme. Der erste native Onlinenachweis verwendete WSS. Explizites HTTPS und automatischer Fallback sind inzwischen oben separat nativ
|
||||
abgenommen. Die passive SCM-/Enrollment-/mTLS-/Inventar-/Mandantentrennungsstrecke sowie
|
||||
die oben benannten nativen Tests sind nun tatsächlich getrennt belegt.
|
||||
Dies ist keine vollständige Windows-/Linux-MVP-Abnahme.
|
||||
|
||||
## Ausgeführte und geplante Befehle
|
||||
|
||||
Tatsächlich ausgeführt: Docker-Build und gezielte Rust-Prüfungen oben sowie
|
||||
`python3 deploy/windows/client_bootstrap.py upload-agent --artifact <Release-EXE>`
|
||||
und `python3 deploy/windows/client_bootstrap.py probe` gegen ausschließlich den
|
||||
Windows-Gast. Keine RMM-Jobs oder Genehmigungen wurden dabei erzeugt.
|
||||
|
||||
Zusätzlich tatsächlich ausgeführt: native `test-lib`/`test-bin`/`test-acl`, Installer nach
|
||||
nachgewiesenem Nichtstart mit `install-after-nonstart` und die oben benannte
|
||||
PostgreSQL-Migrationsprüfung sowie `passive-acceptance` gegen den Cloudserver
|
||||
mit gespeichertem Inventar, zwei Heartbeats, Tenant-B-Verweigerung und Null-Jobgate.
|
||||
Installation ist create-only; bei Teilfehlern Zustand inspizieren und erhalten,
|
||||
nicht blind neu enrollen oder den Bootstrap wiederholen.
|
||||
|
||||
Native ergänzende Receiptprüfung: das separate Entwicklungstool
|
||||
`examples/passive_state.rs` öffnete ausschließlich die vorhandene Windows-SQLite
|
||||
im Read-only-Modus. Integrität `ok`, feste Geräteidentität identisch, Sequenz 59,
|
||||
**0 ausstehende Inventarereignisse**: der konkrete Server-ACK wurde lokal verbucht.
|
||||
Keine neue Erhebung, kein Journalreset und kein neues Enrollment für diesen Nachweis.
|
||||
|
||||
Bekannte Darstellungsgrenze des ersten Collectors: `os` enthält den tatsächlich
|
||||
ausgelesenen Registry-Produktnamen samt DisplayVersion/Build. Auf dieser Windows-
|
||||
11-Pro-VM lautet der historische Registrywert noch `Windows 10 Pro`, mit
|
||||
`DisplayVersion=26H2; Build=26300`. Die unabhängige native CIM-Probe bestätigt
|
||||
Windows 11 Pro. Der Registrywert wird nicht stillschweigend als Marketingversion
|
||||
uminterpretiert; eine einheitliche, quellenbewusste OS-Bezeichnung ist noch offen.
|
||||
Die aktuelle Capability bleibt deshalb ausdrücklich partielles Basisinventar.
|
||||
+22
-128
@@ -1,144 +1,38 @@
|
||||
# Windows-11-Entwicklungszugang
|
||||
# Windows-Agent betreiben
|
||||
|
||||
**Historischer Erstbootstrap und Einrichtungsnachweise. Nicht erneut ausführen.**
|
||||
Aktueller Einstieg für vorhandene Zugänge am 17. November 2026:
|
||||
[Zugangsanleitung](../../docs/operations-access.md) und
|
||||
[Übergabe](../../docs/handover.md).
|
||||
Die Aussagen „noch kein Client“, frühere24-Stunden-Fristen und alte
|
||||
Download-/Repairabläufe unten gelten nur für ihren jeweiligen historischen Stand.
|
||||
Der permanente Entwicklungstransport ist eingerichtet, heute aber ohne aktiven
|
||||
Server-Reverselistener; vorhandene Schlüssel/Identität erhalten.
|
||||
Der offizielle Windows-x64-Kanal verwendet das GNU-Ziel `x86_64-pc-windows-gnu`. Der Dienst `RmmDiscoveryWindows` läuft als LocalService. Er meldet sich ausgehend per mTLS, liefert Inventar und führt genehmigte PowerShell-Skripte aus. Für Aufträge als SYSTEM verwendet er den pro Installation eingerichteten `RmmDiscoverySystemHelper`.
|
||||
|
||||
## Installation
|
||||
|
||||
Userentscheidung 2026-11-13 / Spezifikation 1.8: Windows darf parallel zur noch
|
||||
offenen Linux-MVP-Abnahme entwickelt werden. Notebook-Host bleibt ohne Agent.
|
||||
Dieser Bootstrap schafft SSH-Zugang zum Windows-Gast, keine RMM-Installation
|
||||
und keine Ausnahme von der späteren WebUI-Jobgenehmigung.
|
||||
1. In der WebUI den Kunden wählen und unter **Gerät aufnehmen** einen Einmalcode erzeugen. Auf der Windows-Maschine die 64-Bit-Windows-PowerShell 5.1 als Administrator öffnen.
|
||||
2. Den angezeigten Windows-Befehlsblock für das GNU-Paket ausführen. Er lädt `/install/windows.ps1` per HTTPS und übergibt den Bootstrap-Ursprung. Den Code auf die Frage „One-time enrollment token“ eingeben.
|
||||
3. Für administrative Skripte die Administratoroption im Aufnahmeformular wählen. Der zusätzliche Schalter `-EnableAdministratorScripts` richtet den SYSTEM-Helper mit Gerätebindung, lokalem Journal und signiertem Agent-/Helperpaar ein. Auf einem bereits aufgenommenen Gerät lässt sich derselbe Installer mit dem bisherigen Ursprung und diesem Schalter ausführen.
|
||||
4. Im Gerätedetail den frischen Kontakt und die Agentversion prüfen. Für SYSTEM-Aufträge müssen der SYSTEM-Kontext gemeldet und die zentrale Geräteregel eingerichtet sein. Für MCP kommt das plattformspezifische Tokenrecht hinzu. [Installer](../../crates/server/src/bootstrap/install.ps1) · [MCP-Zugang](../../docs/public-access.md)
|
||||
|
||||
## Vorbereitet und tatsächlich geprüft
|
||||
## Dienste und Selbstupdate
|
||||
|
||||
`python3 deploy/windows/prepare_dev_access.py` hat auf dem endgültigen Server
|
||||
das separate Systemkonto `rmm-win-tunnel` und dessen SSH-Matchprofil angelegt.
|
||||
`sshd -t` und effektive Benutzerkonfiguration bestanden; Root-SSH-Konfiguration
|
||||
vor/nach identisch. Nur Remote-TCP-Forwarding auf `127.0.0.1:22240`, keine
|
||||
Shell/SFTP/Sitzungen (`MaxSessions 0`), keine Local-/Streamlocal-/Agentforwards,
|
||||
keine Passwortanmeldung. Noch kein Windows-Key hinterlegt, kein Windows-
|
||||
Tunnel/Administrationszugang nachgewiesen. Keine neue öffentliche Portfreigabe.
|
||||
`RmmDiscoveryReleasePull` prüft nach erfolgreichem Lauf regulär nach fünf Minuten erneut auf einen veröffentlichten Release. Er verifiziert Signatur, Plattform und Paketinhalt und stimmt den Wechsel mit laufenden Aufträgen ab. Ein neuer Release muss sich unter derselben Geräteidentität zurückmelden. Scheitert die Aktivierung, wählt der Updater den Vorgänger. Programmdateien liegen unter `%ProgramFiles%\RustDiscovery`. Konfiguration, Identität und Journale liegen unter `%ProgramData%\RustDiscovery`. [Nativer Release-Abruf](../../crates/agent-windows/src/release_service.rs) · [HTTPS-Aufnahme und Selbstupdate](../../docs/evidence/windows-gnu-official-vm-20261118.json)
|
||||
|
||||
Public-only Paket lokal unter `devstate/windows-bootstrap/windows-dev-access.zip`:
|
||||
dieses Skript und `bootstrap-public.json` mit Notebook-Public-Key, bereits
|
||||
unabhängig geprüftem Server-ED25519-Hostkey und 24-Stunden-Frist. Kein privater
|
||||
Schlüssel und kein Cloud-Rootzugang werden verteilt. Der neue Tunnelschlüssel
|
||||
wird ausschließlich auf der Windows-VM erzeugt und verlässt sie nicht.
|
||||
|
||||
PowerShell-Parserprüfung mit offiziellem PowerShell 7.7.0 auf dem Notebook:
|
||||
bestanden. **Kein nativer Windows-Ausführungs-/OpenSSH-/ACL-/Tasknachweis.**
|
||||
Das Skript verwendet PowerShell-5.1-Syntax; die Ausführung auf Windows 11 muss
|
||||
noch durch den User erfolgen. Vorhandene laufende SSH-Installation, gleichnamiger
|
||||
Account/Task oder Teilbootstrap werden verweigert statt überschrieben.
|
||||
|
||||
## In der Windows-Test-VM ausführen (geplant, noch nicht nachgewiesen)
|
||||
|
||||
Paket auf die VM kopieren und entpacken. Erhöhte **64-Bit-PowerShell** im
|
||||
entpackten Verzeichnis öffnen, Skript prüfen und dann:
|
||||
Diese Befehle zeigen in einer administrativen PowerShell die beiden Standarddienste und den letzten Updaterstatus.
|
||||
|
||||
```powershell
|
||||
Unblock-File -LiteralPath .\Bootstrap-DevAccess.ps1
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\Bootstrap-DevAccess.ps1
|
||||
Get-Service -Name RmmDiscoveryWindows,RmmDiscoveryReleasePull
|
||||
Get-Content -Raw (Join-Path $env:ProgramData 'RustDiscovery\release-state\release-status.json')
|
||||
```
|
||||
|
||||
`RemoteSigned` gilt ausschließlich für den gestarteten Prozess; keine Änderung
|
||||
der systemweiten Ausführungsrichtlinie und kein Umgehen einer Gruppenrichtlinie.
|
||||
Es installiert nötigenfalls ausschließlich die optionalen OpenSSH-Funktionen.
|
||||
`RestartNeeded` stoppt die Vorbereitung; kein automatischer Neustart/OS-Update.
|
||||
Bei eingerichtetem SYSTEM-Kontext zusätzlich `Get-Service -Name RmmDiscoverySystemHelper` prüfen. In der WebUI lassen sich für den konkreten Auftrag der gebundene Skripttext, der Exitcode und die Ausgabe nachlesen. Bei Windows-Updates „Windows-Updates installieren“ als SYSTEM planen. Die PowerShell-Vorlage meldet die Ergebnisse der Installation und den Neustartbedarf. [Abnahme einer echten Updateinstallation](../../docs/evidence/windows-update-installation-20261117.json)
|
||||
|
||||
Es erstellt den bis zur Paketfrist gültigen lokalen Administrator `rmm-dev`
|
||||
mit zufälligem, ausschließlich VM-internem Passwort und Public-Key-only-SSH.
|
||||
Authorized-Keys und Bootstrapstate sind nur für SYSTEM/Administratoren zugänglich
|
||||
(SIDs statt sprachabhängiger Namen). Windows-SSH lauscht ausschließlich auf
|
||||
`127.0.0.1:22222`; Standard-OpenSSH-Firewallregel wird deaktiviert. Konfigurations-
|
||||
und Keydateien einer vorhandenen gestoppten Installation werden gesichert.
|
||||
## Neustart und Wiederanmeldung prüfen
|
||||
|
||||
Ein SYSTEM-Task verbindet ausgehend zum bekannten Server und prüft dessen
|
||||
Hostkey strikt. Reverse-Listener dort nur Loopback. Wiederverbindung alle 30s
|
||||
ist ausschließlich Bootstraptransport, kein RMM-Job-Retry. Task beendet seinen
|
||||
eigenen SSH-Prozess nach Frist; kein Reboot. Bestehende RMM-Policies bleiben.
|
||||
|
||||
Das Skript druckt ausschließlich öffentliche Registrierungsdaten:
|
||||
`windows_user`, `tunnel_public_key`, `windows_host_public_key`, `expires_at`,
|
||||
`windows_architecture` sowie Hostkeyfingerprint. Diese Ausgabe von der tatsächlichen
|
||||
VM-Konsole zurückgeben; keine privaten Schlüssel/Passwörter übertragen.
|
||||
Nach Hinterlegung des Tunnel-Public-Keys und Prüfung/Pinnen des Windows-Hostkeys
|
||||
kann der Entwicklungsrechner über den Cloudserver mit seinem vorhandenen Key
|
||||
auf den Windows-Administrator zugreifen. Native Nachweise folgen erst dann.
|
||||
|
||||
Grundlagen: [Microsoft OpenSSH-Installation](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse),
|
||||
[Windows-Konfiguration und Administrator-Key-ACL](https://learn.microsoft.com/en-us/windows-server/administration/openssh/openssh-server-configuration).
|
||||
|
||||
## Öffentlicher Download auf dem Cloudserver — tatsächlich geprüft
|
||||
|
||||
Auf Userwunsch Public-only Paket separat auf HTTPS **8443**, ausschließlich ein
|
||||
exakter Downloadpfad bis Paketablauf. Gültige öffentliche Let's-Encrypt-Kette
|
||||
mit normalem externem Truststore geprüft; heruntergeladene Bytes SHA256-identisch.
|
||||
RMM-TLS/mTLS auf 443, Verwaltungszugang und Client-Truststores unverändert.
|
||||
Keine Secrets im Bundle. Link und Belege geschützt unter
|
||||
`devstate/windows-bootstrap/{publication.json,published-verified.json}`.
|
||||
|
||||
`deploy/windows/publish_bootstrap.py`: ACME mit gepinntem, geprüftem
|
||||
acme-tiny-Commit `dc2c102314a56580facafce2249b292cebcfc42b`; Account-/Domainkeys
|
||||
bleiben auf dem Server in rootgeschütztem Verzeichnis. HTTP80 nur für ACME,
|
||||
danach tatsächlich gestoppt und Firewallregel entfernt. Downloadserver mit
|
||||
DynamicUser, readonly System, separaten systemd-Credentials für TLS-Key und
|
||||
maximal 16 gleichzeitigen Verbindungen. Kein beliebiges Dateisystemhosting.
|
||||
|
||||
Ein späterer Verbindungsversuch traf zunächst auf eine blockierende TLS-Annahme.
|
||||
Server korrigiert: Timeout/Handshake je begrenztem Worker, Listener blockiert
|
||||
nicht mehr. Danach externer HTTPS-Download während gleichzeitig offener langsamer
|
||||
TCP-Verbindung erfolgreich; `/`, `/etc/passwd`, `/auth/config` und codierter
|
||||
Traversalpfad jeweils 404. Drei lokale Pfad-/Frist-/ACME-Guards bestanden.
|
||||
|
||||
Öffentliche Freigabe endet **2026-11-14 12:55:31 UTC**. Aktiver persistenter
|
||||
systemd-Timer stoppt den eigenen Downloadservice und schließt dessen Firewallport
|
||||
8443; auch die Anwendung verweigert nach Frist weitere Downloads. Dies ist
|
||||
Bootstrapwartung auf dem Server, kein autorisierender RMM-Job oder VM-Reboot.
|
||||
Windows-Ausführung weiterhin nicht nachgewiesen.
|
||||
|
||||
## Tatsächlich hergestellter Zugang / Reparaturen
|
||||
|
||||
Der User führte das erste Paket auf Windows aus. Dienst zunächst Exit 1067,
|
||||
Vordergrundstart dagegen erfolgreich. `Repair-DevAccess.ps1` prüft die bestehenden
|
||||
Skripte/Config gegen die ursprünglichen Hashes, sichert ACLs, setzt SYSTEM als
|
||||
Eigentümer und SYSTEM/Administratoren als einzige Zugriffsberechtigte für
|
||||
SSH-Verzeichnis, Config und Hostprivatekeys. Keine Schlüssel-/Kontoneuerzeugung.
|
||||
Danach Dienst tatsächlich `Running`, Hostkey unverändert. Erstbootstrap-Quelle
|
||||
für neue Pakete entsprechend korrigiert; historisches Public-ZIP unverändert,
|
||||
separates Repair-ZIP mit eigener expliziter Downloadroute veröffentlicht.
|
||||
|
||||
Cloud-Public-Key registriert; anfänglich ungültige Option `permitopen="none"`
|
||||
aus `authorized_keys` entfernt. Sie ist ausschließlich im sshd-Matchprofil gültig
|
||||
und dort unverändert aktiv. Zusätzlich öffentliche `.ssh`-Directorymodi explizit
|
||||
gesetzt, statt sie einer umask zu überlassen. Remote-only/PermitListen/MaxSessions
|
||||
bleiben erhalten. Private Keys wurden nicht übertragen.
|
||||
|
||||
Windows-Tunnel anschließend automatisch durch den Hintergrundtask aufgebaut.
|
||||
Notebook-SSH über Cloud-Loopback mit unabhängig aus der VM-Konsole bestätigtem
|
||||
Hostkey und vorhandenem Notebook-Key erfolgreich. Echt beobachtet: **Windows 11
|
||||
Pro, Build 26300, 64 Bit, Administrator=true**. Zugangsdaten nur unter
|
||||
`credentials/windows-dev-access.json`, Belege unter `devstate/windows-bootstrap/`.
|
||||
**Noch kein RMM-Windows-Client installiert/enrolled/abgenommen.** Keine Änderung
|
||||
am Notebook-Host als reinem Entwicklungsrechner.
|
||||
|
||||
## Zugang bei Bedarf stoppen
|
||||
|
||||
Auf der Windows-VM als Administrator, ausschließlich eigene Bootstrapressourcen:
|
||||
Die Bibliotheksrevision „Windows neu starten“ Version 2 verwendet das systemeigene `shutdown.exe` mit einer Minute Vorlauf. Die folgende Abfrage vor und nach dem Neustart ausführen und den Startzeitpunkt des jüngsten Kernel-General-Ereignisses 12 vergleichen.
|
||||
|
||||
```powershell
|
||||
Stop-ScheduledTask -TaskName RmmDevReverseTunnel
|
||||
Unregister-ScheduledTask -TaskName RmmDevReverseTunnel -Confirm:$false
|
||||
Disable-LocalUser -Name rmm-dev
|
||||
Stop-Service -Name sshd
|
||||
$event = Get-WinEvent -FilterHashtable @{LogName='System'; ProviderName='Microsoft-Windows-Kernel-General'; Id=12} -MaxEvents 1
|
||||
(([xml]$event.ToXml()).Event.EventData.Data | Where-Object Name -eq 'StartTime').InnerText
|
||||
```
|
||||
|
||||
Backups/Hostkeys und Zustandsdateien erhalten. Cloud-Tunnelkey separat sperren;
|
||||
keine pauschale Änderung anderer SSH-Zugänge. Vollständige Entfernung einer
|
||||
vorherigen SSH-Konfiguration ist ein eigener kontrollierter Vorgang.
|
||||
Nach dem Bootwechsel den authentisierten Kontakt derselben Installation und einen Folgeauftrag mit Ergebnis prüfen. Bei einem Gatewaywechsel kann sich der Agent vorübergehend bereits melden, während er den signierten Zeit- und Journalabgleich für ausführbare Aufträge erneuert. Bei dauerhaft ausstehendem Abgleich den letzten authentisierten Kontakt, die Windows-Zeitsynchronisation (`w32tm /query /status`) und die Bereitschaft von Agent und optionalem Helper prüfen. Nach einer bestätigten Ergebnismeldung kann der Helper seinen Abgleich wieder aufnehmen. [Zeitabgleich](../../docs/evidence/windows-gateway-clock-recovery-20261117.json) · [Helper-Abgleich](../../docs/evidence/windows-helper-result-recovery-20261118.json) · [Native MCP-Abnahme](../../docs/evidence/mcp-scoped-script-requests-20261118.json)
|
||||
|
||||
Für Störungen zwischen Agent und SYSTEM-Helper beschreibt die [Pipe-Dokumentation](../../docs/windows-helper-pipe-drain.md) die lokale Transportbestätigung. Für den Entwicklungsgast ohne dauerhaften Helper enthält das [Runbook für befristete Windows-Updatefenster](../../docs/windows-update-dev-window.md) die Voraussetzungen und den Rückbau.
|
||||
|
||||
Build, Veröffentlichung und Entwicklungsbereitstellung stehen im [Entwicklungsweg](../../docs/development.md).
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
# Native Windows MSVC build
|
||||
|
||||
Prepared 2026-11-14. The native `Prepare` phase was attempted in the retained
|
||||
case `b208282f-d950-4f5a-bc5e-9e071ccb4d93` and stopped before any download or
|
||||
installer: `SETUP_PREEXISTING_REBOOT_PENDING`. Separate read-only inspection
|
||||
confirmed both the CBS `RebootPending` and Windows Update `RebootRequired` keys
|
||||
already existed; PendingFileRenameOperations had24 entries (contents not read
|
||||
into the report). No compiler installation, Windows update, restart, trust-store
|
||||
change, daemon replacement or RMM job was performed. Agent PID5140 and helper
|
||||
PID6240 remained running; W32Time remained stopped. This is an incomplete
|
||||
prerequisite, not a successful MSVC qualification. No flag is cleared or ignored.
|
||||
|
||||
`Build-NativeMsvc.ps1` is a development build runner, not an installer. Run it in
|
||||
64-bit Windows PowerShell5.1 from a source bundle containing the exact repository
|
||||
sources and this script. `Preflight` inventories installed tools and records
|
||||
private source/tool hashes. `Build` requires an explicitly selected successful
|
||||
preflight receipt, creates a different private case, and builds an isolated
|
||||
source copy. It never reuses a partial build case.
|
||||
|
||||
## Required native tools
|
||||
|
||||
- Rust `1.99.1-x86_64-pc-windows-msvc`, including `cargo`, `rustc`, `rustdoc`,
|
||||
`clippy-driver`, `rustfmt`, supplied by the official rustup installation.
|
||||
- Installed Visual Studio C++ tools in the selected range `[17.14,19.0)`;
|
||||
VS2022 or VS2026 is selected by its signed `vswhere.exe`. The actual product,
|
||||
compiler version, signer thumbprints and tool hashes are recorded. The current
|
||||
official [VS release history](https://learn.microsoft.com/en-us/visualstudio/releases/2026/release-history)
|
||||
includes VS2026; the runner does not download a mutable latest bootstrapper.
|
||||
- The x64 `cl.exe`, `link.exe`, `lib.exe`, `dumpbin.exe`, and Windows SDK
|
||||
`10.0.26100.0` x64 `midl.exe`. Microsoft signatures must be valid. The selected
|
||||
SDK is explicit through `vcvarsall.bat amd64 10.0.26100.0`; see Microsoft's
|
||||
[native build environment](https://learn.microsoft.com/en-us/cpp/build/building-on-the-command-line?view=msvc-170).
|
||||
- At least20GiB available on the evidence/build volume by default. This is the
|
||||
runner's conservative admission threshold, not a measured installation size.
|
||||
- The locked Cargo dependencies must already be available in the build user's
|
||||
registry cache. Builds are `--locked --offline`. A missing crate is a failed
|
||||
prerequisite, never a reason for an automatic online retry. An explicit
|
||||
development preparation can populate the public dependencies with
|
||||
`cargo +1.99.1-x86_64-pc-windows-msvc fetch --locked --target x86_64-pc-windows-msvc`.
|
||||
Do not transfer an entire Cargo home containing credentials or configuration.
|
||||
|
||||
The parent's actual read-only VM report
|
||||
`devstate/windows-client/native-msvc-tools-readonly-20261114.json` now records
|
||||
103300169728 free bytes, x64, no `vswhere`, no `rustup`, no SDK directories,
|
||||
W32Time stopped and all execution-policy scopes undefined. No installation was
|
||||
performed by this preparation. No extra private key, server token or production
|
||||
signing certificate is needed for source build.
|
||||
[Rust's MSVC target contract](https://doc.rust-lang.org/rustc/platform-support/windows-msvc.html)
|
||||
defines native Windows support, Microsoft calling conventions and PE/COFF output.
|
||||
|
||||
## Explicit tool-setup plan, not executed
|
||||
|
||||
If preflight reports missing C++ tools, first select a **fixed-version** Build
|
||||
Tools bootstrapper from Microsoft's release history, retain its download URL,
|
||||
SHA-256, ProductVersion, valid Microsoft Authenticode signature and thumbprint.
|
||||
Verify the intended absent/new install directory and sufficient disk before
|
||||
starting setup. Reuse a suitable existing installation rather than updating it.
|
||||
The exact required component IDs are:
|
||||
|
||||
```text
|
||||
Microsoft.VisualStudio.Workload.VCTools
|
||||
Microsoft.VisualStudio.Component.VC.Tools.x86.x64
|
||||
Microsoft.VisualStudio.Component.Windows11SDK.26100
|
||||
```
|
||||
|
||||
The planned bootstrapper arguments are:
|
||||
|
||||
```text
|
||||
--wait --passive --norestart --installPath C:\RmmBuildTools
|
||||
--add Microsoft.VisualStudio.Workload.VCTools
|
||||
--add Microsoft.VisualStudio.Component.VC.Tools.x86.x64
|
||||
--add Microsoft.VisualStudio.Component.Windows11SDK.26100
|
||||
```
|
||||
|
||||
There is no `--force`, repair, OS update, automatic retry or reboot. Persist the
|
||||
actual setup process/result before returning a bootstrap reply. `0` completes
|
||||
the setup operation; `3010` means installation requires a restart **before use**,
|
||||
so stop without building, clearing the flag or implicitly rebooting. `1641`
|
||||
means a reboot was initiated and violates this no-restart plan. `1618`/`1001`
|
||||
mean another installation is active; preserve the case and inspect, never kill
|
||||
the other installer or blindly rerun. A lost SSH reply permits only process/log
|
||||
readback of that same setup. The build runner itself never launches setup.
|
||||
[Microsoft component IDs](https://learn.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools?view=visualstudio),
|
||||
[parameters and actual exit-code semantics](https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2022).
|
||||
|
||||
## Build invocation and evidence
|
||||
|
||||
Planned, not executed:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Build-NativeMsvc.ps1 -Mode Preflight -SourceRoot C:\Source\rust-discovery
|
||||
# Review that exact private preflight.json, then use a NEW build case:
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Build-NativeMsvc.ps1 -Mode Build -SourceRoot C:\Source\rust-discovery `
|
||||
-ExpectedPreflight C:\Users\Administrator\RmmNativeBuilds\<preflight-id>\preflight.json
|
||||
```
|
||||
|
||||
The runner imports only selected developer environment values, rejects caller
|
||||
compiler flags/wrappers, pins the native compiler/linker/MIDL paths, and keeps
|
||||
each process's stdout/stderr private. It copies only explicit source extensions
|
||||
under `crates/` and `proto/`, root Cargo/toolchain files and the MSVC runner/probe;
|
||||
no `credentials/`, `devstate/`, client key material, repository metadata or local
|
||||
server state. A protected build root and new protected case prevent unrelated
|
||||
service users from changing the copied inputs. Source/tool hashes must match
|
||||
before and after the build.
|
||||
|
||||
Before Cargo, Microsoft MIDL generates the real IDL with `/env amd64 /Oicf
|
||||
/robust /Zp8`; `win64` is intentionally avoided because MIDL documents it as
|
||||
IA64. The native C probe asserts Microsoft LLP64, numeric Rust ABI64 bytes,
|
||||
wire-status ABI120 bytes and explicit field offsets. It raises/catches only a
|
||||
local RPC exception1722 using the same SDK SEH macros/filter; it does not query
|
||||
W32Time, contact RPC or claim trusted time. There is no vendored WIDL stub or
|
||||
SEH workaround. [MIDL AMD64/packing](https://learn.microsoft.com/en-us/windows/win32/midl/-env),
|
||||
[robust NDR checking](https://learn.microsoft.com/en-us/windows/win32/midl/-robust),
|
||||
[C11 assertions](https://learn.microsoft.com/en-us/cpp/c-language/static-assert-c?view=msvc-170),
|
||||
[SDK RPC SEH](https://learn.microsoft.com/en-us/windows/win32/rpc/rpctryexcept).
|
||||
|
||||
The product build script adds only the native MSVC branch, preserving the GNU
|
||||
WIDL/clang branch and the C exception boundary. Both still compile the actual
|
||||
clock sources and preserve their static assertions; SDK or compiler failure is
|
||||
fatal. The Clock readiness gate stays unqualified. The separate native
|
||||
service-SID authentication candidate is not qualified by an ABI or build pass.
|
||||
|
||||
Cargo then checks Windows Clippy with warnings denied, builds agent/helper and
|
||||
examples in release, and **links without running** Windows/core unit tests.
|
||||
The runner records AMD64 PE headers, artifact hashes, generated RPC hashes,
|
||||
dependency listings and actual Authenticode status. Development output may be
|
||||
unsigned; this is no signing/installer/production-PKI acceptance. Native unit
|
||||
execution, LocalService/SYSTEM behavior and a preserving daemon deployment
|
||||
remain separate explicit gates. A timeout retains its exact process/evidence;
|
||||
no process-tree kill or retry is implied.
|
||||
|
||||
Locally executed preparation checks: PowerShell AST parse; isolated compilation
|
||||
and Clippy of `build.rs` using locked-version `cc1.11.1`; rustfmt/source checks.
|
||||
These checks do not prove that Microsoft MIDL, MSVC, the ABI probe or the final
|
||||
agent/helper builds have run successfully on Windows.
|
||||
|
||||
## Concrete native tool bootstrap, prepared separately
|
||||
|
||||
`Install-NativeBuildTools.ps1` supplies separate `Prepare`, `InstallVs`,
|
||||
`InstallRust`, and read-only `Read` phases. Only `Prepare` has been attempted;
|
||||
the pre-existing reboot need blocked it before downloads. Neither install phase
|
||||
has run. Both install calls consume create-only start intents
|
||||
before launching their fixed worker. Each worker runs in its own protected,
|
||||
demand-only Task Scheduler entry as SYSTEM, without a trigger, automatic retry
|
||||
or autostart; a second worker entry refuses before installation. This keeps a
|
||||
long setup independent of the40s SSH/bootstrap reply limit. Results, actual
|
||||
installer PID and exit code are retained, and the task is disabled after its
|
||||
worker result. Lost reply/timeout permits readback only. These are explicitly
|
||||
authorized development-tool bootstrap tasks, never WebUI/RMM jobs or a generic
|
||||
SYSTEM execution provider. [Task registration](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/register-scheduledtask?view=windowsserver2025-ps),
|
||||
[fixed service-account principal](https://learn.microsoft.com/en-us/powershell/module/scheduledtasks/new-scheduledtaskprincipal?view=windowsserver2025-ps).
|
||||
|
||||
Inputs are fixed official TLS URLs with ordinary certificate/name validation:
|
||||
|
||||
| Input | Pinned SHA-256 |
|
||||
|---|---|
|
||||
| Microsoft Build Tools18.11.4 LTSC bootstrapper, file version18.11.12405.450 | `386b5d9a3d6576eab3772c1ecaa7c107ded38146a9c483f41679c194ae1e63b4` |
|
||||
| rustup1.29.3 Windows x64 MSVC bootstrapper | `38027d51d69a5d05493627a0634dbea52d6cd793c8f072d2373d3f4163eec7db` |
|
||||
| Rust1.99.1 official distribution manifest | `fb152be80975c194aa5fc684b2aec3a6e14e2b855efe2faa4e5f8ae6e590f463` |
|
||||
|
||||
The Microsoft EXE additionally requires valid Microsoft Authenticode and the
|
||||
exact product/file version. Rustup is checked against its exact
|
||||
[official archived checksum](https://static.rust-lang.org/rustup/archive/1.29.3/x86_64-pc-windows-msvc/rustup-init.exe.sha256),
|
||||
with [official archive/install options](https://rust-lang.github.io/rustup/installation/other.html).
|
||||
Its homes are private case subdirectories; `--no-modify-path`,
|
||||
`--no-update-default-toolchain`, minimal profile and exactly clippy/rustfmt keep
|
||||
the developer's default Rust installation/profile/PATH untouched. The fixed
|
||||
Rust distribution origin is set only for that worker process. Using isolated
|
||||
homes is an [official rustup option](https://rust-lang.github.io/rustup/installation/index.html).
|
||||
|
||||
VS setup uses only `--wait --quiet --norestart --noUpdateInstaller`, the new
|
||||
fixed target `C:\RmmBuildTools`, and the three components above. It relies on the
|
||||
official installer's standard Microsoft metadata/package verification. No
|
||||
custom channel/catalog, checksum override, certificate import or weaker
|
||||
verification flag is supplied. Installed VS version must then match exactly
|
||||
18.11.12405.450 and SDK26100 must be present; drift remains incomplete. Setup's
|
||||
required transitive development dependencies remain Microsoft's responsibility;
|
||||
this is no general production-installer trust acceptance. No Windows Update
|
||||
command is invoked. Boot/OS build, machine trust-store fingerprints, machine
|
||||
PATH, execution policies, W32Time and both exact RMM service states/PIDs are
|
||||
observed before/after. Detected changes, unexpected setup version,3010/1641 or
|
||||
restart need stop completion without resetting/undoing or retrying anything.
|
||||
|
||||
Scope decision2026-11-14: an initial **custom manual catalog-bundle** design was
|
||||
rejected. Its channel declared catalog size31851991 and hash
|
||||
`ef56e369d92855a9667cd03602019375f42b3cd2145041df31cacc071a40e1af`;
|
||||
the exact official URL instead returned18733589 bytes with hash
|
||||
`805d16fd14a370cbeb6568179950826ba0cdc6e2cffa44936fddc408ef05cba3`.
|
||||
Those inputs and rejected source remain privately retained; no mismatching
|
||||
catalog was accepted or installed. The extra manual bundle was our design,
|
||||
not an AGENTS/product requirement. The selected replacement uses the supported,
|
||||
independently hash/Authenticode-pinned official EXE and its own verification,
|
||||
not a checksum exception or undocumented JSON-signature workaround.
|
||||
Microsoft documents [standard acquisition and fixed-version bootstrappers](https://learn.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio?view=vs-2022).
|
||||
|
||||
Future successful-case sequence; installation and build remain **not executed**.
|
||||
The failed case above is retained and must not be reused after a prerequisite
|
||||
change. A manual VM restart has been requested for later coordination; it is
|
||||
neither implicitly authorized nor an RMM reboot acceptance.
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Install-NativeBuildTools.ps1 -Phase Prepare
|
||||
# Review that exact printed private case and its prepared.json first:
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Install-NativeBuildTools.ps1 -Phase InstallVs -CaseDirectory <case>
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Install-NativeBuildTools.ps1 -Phase Read -CaseDirectory <case>
|
||||
# Continue only after verified VS exit0 and no restart need:
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Install-NativeBuildTools.ps1 -Phase InstallRust -CaseDirectory <same-case>
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Install-NativeBuildTools.ps1 -Phase Read -CaseDirectory <same-case>
|
||||
```
|
||||
|
||||
This uses the already authorized **development/bootstrap-only** process option
|
||||
`-ExecutionPolicy RemoteSigned`, as in the previous Windows dev-access and
|
||||
passive-client bootstrap. The worker uses that same process option and invokes
|
||||
the hash-checked `.ps1` file normally with `& $p`; it never executes file content
|
||||
through `ScriptBlock::Create`. A small encoded hash launcher is only transport
|
||||
for that ordinary file invocation. There is no `Set-ExecutionPolicy`, registry
|
||||
policy write, Machine/User/GPO change or Bypass option. Persistent scopes stay
|
||||
unchanged; process scopes are consistently RemoteSigned and GPO precedence is
|
||||
retained. This permission does **not** decide or authorize the separate RMM
|
||||
PowerShell job executor's still-unqualified policy contract.
|
||||
|
||||
After actual successful setup, pass the recorded private homes to the builder:
|
||||
|
||||
```powershell
|
||||
powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File .\deploy\windows\Build-NativeMsvc.ps1 -Mode Preflight -SourceRoot C:\Source\rust-discovery `
|
||||
-RustupExe <case>\cargo_home\bin\rustup.exe -RustupHome <case>\rustup_home -CargoHome <case>\cargo_home
|
||||
```
|
||||
|
||||
Use those same arguments with `-Mode Build -ExpectedPreflight <actual-receipt>`.
|
||||
Populate the isolated public Cargo cache explicitly before an offline build;
|
||||
there is no automatic fetch/retry in the builder. Native setup, native MIDL/ABI,
|
||||
unit execution and deployment results are still outstanding until actually run.
|
||||
|
||||
On November 15, 2026 a read-only check on the running Windows test VM found
|
||||
both CBS and Windows Update restart markers, 96 GiB free on C:, no vswhere
|
||||
at its standard installer path, and no rustc on the development user's PATH.
|
||||
No installer was launched. This check does not determine why the markers are
|
||||
present. Receipt `04a56e7d8a8bf00a110558344248fbb0ca0c2234c5c1ea6e347306bcc84d5c55`.
|
||||
@@ -1,119 +0,0 @@
|
||||
# Agentabbruch nach möglicher Wirkung: native Abnahme bestanden
|
||||
|
||||
Stand2026-11-13. Tatsächlicher Cloudfall
|
||||
`644c06eb-24b0-41b0-9a90-f60ea1fe38a9` bestanden. Feste tatsächliche
|
||||
dev/test-WebUI-Genehmigung0/0/0→1/1/1, ein Rootzähler-Effekt vor dem gezielten
|
||||
SIGKILL ausschließlich des binär-/PID-/Startzeit-gebundenen Agentprozesses.
|
||||
Unabhängiger Generalhelper blieb derselbe Prozess und bearbeitete den bereits
|
||||
verbrauchten Versuch weiter. Native Agent-/Zentralzustände tatsächlich
|
||||
unknown/revision2/`AGENT_PROCESS_INTERRUPTED`, kein zweiter Verbrauch/Effekt.
|
||||
|
||||
Originalgrant`a3cbc544-0582-4d64-8237-017a82d7cddf`/Root16 anschließend über
|
||||
independentes Helperergebnis und **gewöhnlichen signierten RootSync** desselben
|
||||
Versuchs succeeded geschlossen. Eigener zweiter fester UI-Leseplan1/1/1
|
||||
bestätigte Zähler1; dies ist keine zweite Wirkung des ursprünglichen Jobs.
|
||||
Beide Genehmigungsaudits sichtbar simuliert, Root-Testpolicy danach geschlossen.
|
||||
Agent702/Helperbbd/Provider1dc unverändert, kein Paket-/Identitäts-/Journalreset.
|
||||
|
||||
Geschützter verifizierter vollständiger Beleg:
|
||||
`devstate/cloud-crash/644c06eb-24b0-41b0-9a90-f60ea1fe38a9/checkpoint.json`.
|
||||
Der folgende Entwurf beschreibt die tatsächlich benutzte Strecke; bisherige
|
||||
lokale Prüfungen bleiben von dieser nativen Abnahme getrennt. Reboot und
|
||||
Endaudit sind noch offen.
|
||||
|
||||
## Gefundene Lücke und minimale Korrektur
|
||||
|
||||
`Agent::start_sync` wartet zuerst auf einen unabhängig authentisierten
|
||||
Helper-Snapshot. Der Roothelper bearbeitet IPC seriell und hält den gemeinsamen
|
||||
Executorlock während der Wirkung; ein Snapshot wartet deshalb oder läuft nach
|
||||
10 Sekunden in einen Timeout. Nach Ende der Wirkung importiert
|
||||
`reconcile::prepare` das gespeicherte Helperergebnis **vor** seiner bisherigen
|
||||
Unknown-Konvertierung. Ein früherer Test hätte deshalb möglicherweise direkt
|
||||
Erfolg statt eines nachweisbar dauerhaften Unknown ergeben.
|
||||
|
||||
Der Agent hält nun genau einmal beim **neuen Prozessstart**, vor der ersten
|
||||
Verbindung und jedem Helperzugriff, unterbrochene Versuche dauerhaft fest:
|
||||
|
||||
- `running`/`verifying` mit bekanntem Grant: unveränderten Offer und ursprünglich
|
||||
signierten Startrequest gegen tatsächlichen Verbrauch und Gerätebindung prüfen;
|
||||
danach regulärer dauerhafter `JobResult=unknown`, eigener Fehlercode
|
||||
`AGENT_PROCESS_INTERRUPTED`, höhere Revision, keine erfundene Wirkung/Ausgabe.
|
||||
- `requesting` ohne bekannten Grant: nur lokal Unknown; keinen Grant oder
|
||||
grantgebundenen Ergebnisnachweis erfinden. Der normale Sync bleibt zuständig.
|
||||
- Verbrauch, Startnachweis und Ressourcensperre bleiben erhalten. Kein `finish`,
|
||||
kein erneuter Permitrequest, keine Änderung erfolgreicher Endzustände.
|
||||
- Normale erste Kanalwiedergabe sendet den dauerhaften Unknown vor dem
|
||||
blockierenden Snapshot. Reconnect desselben Prozesses ruft diese Korrektur
|
||||
nicht auf. Wiederholte Prozessstarts verändern einen vorhandenen Unknown
|
||||
einschließlich Nachrichten-ID und Revision nicht erneut.
|
||||
|
||||
Der Abschluss verwendet ausschließlich den vorhandenen Pfad: unabhängiger
|
||||
Roothelper schreibt `finish` **vor** seiner IPC-Antwort; authentisierter Snapshot
|
||||
importiert denselben ursprünglichen Request und dessen tatsächliches Ergebnis;
|
||||
normaler signierter Sync bindet Revision, Ergebnis-/Plan-/Payloadhash, Agent,
|
||||
Versuch und Grant und öffnet erst danach die Sperre. Eine neue Recovery-API,
|
||||
administrative Ergebnisinjektion oder erneute Skriptausführung existiert nicht.
|
||||
|
||||
Tatsächlich lokal bestanden: gezielter Dispatcher-/SQLite-Test für dauerhaften
|
||||
Unknown vor jedem Helper-I/O, abgewiesene fremde Verbrauchsidentität,
|
||||
grantlosen Antrag, erhaltene Verbrauchssperre und idempotenten Neustart;
|
||||
vorhandener Integrationstest für authentisierten Helperimport als neuen
|
||||
Ergebnisnachweis ohne erneute Wirkung; Agent-Clippy aller Targets mit
|
||||
`-D warnings`. Dies sind keine VM-Nachweise.
|
||||
|
||||
Ein qualifiziert gebautes x86-64-Releaseartefakt liegt geschützt unter
|
||||
`devstate/cloud-apt-recovery/agent-interruption-recovery`, SHA-256
|
||||
`adc4ac0b35f7992300d82b0f263970246fdc0eaec0d2104e4ade22ae3f74d7b6`.
|
||||
ELF-/Abhängigkeitsprüfung: x86-64, höchste benötigte GLIBC-Version 2.34,
|
||||
OpenSSL 3. Noch nicht auf die VM übertragen oder dort gestartet.
|
||||
|
||||
Vorbereitet, **nicht ausgeführt**: `deploy/cloud_crash_acceptance.py` mit
|
||||
echtem zweiphasigem Browserablauf, `deploy/browser/cloud_crash_acceptance.cjs`
|
||||
und exakt sichtbarem Payload `deploy/linux/agent-crash-counter.py`.
|
||||
Python-/Node-Syntax sowie exakte Python-/Browser-Payloadgleichheit und
|
||||
Shell-Parsing ohne Ausführung wurden lokal geprüft. Der Runner verlangt
|
||||
unabhängig bekannte Agent-/Helper-SHAs und den bisherigen geschlossenen
|
||||
Policyhash; er verändert weder Runtimeartefakte noch Providerpins.
|
||||
|
||||
## Geplanter nativer Versuch, noch nicht ausgeführt
|
||||
|
||||
1. Genau die vorhandene Cloud-VM und Geräteidentität verwenden. Zentral und im
|
||||
erhaltenen Journal keine offenen Versuche, qualifizierter neuer Agent,
|
||||
unveränderter gesunder Roothelper. Keine parallele VM-/Imageänderung.
|
||||
2. Fester Root-RunScript-Plan erzeugt einen einmaligen privaten Testzähler unter
|
||||
dem beschreibbaren Helper-StateDirectory, hält danach begrenzt 60–90 Sekunden
|
||||
an und endet mit fest erwarteter Ausgabe bei Laufzeitlimit 120 Sekunden.
|
||||
Alle Bytes, Ziel und Fristen stehen vor der tatsächlichen WebUI-Genehmigung
|
||||
fest; vorher 0 Jobs / 0 Outbox / 0 Grants. Keine Paketmanagerwirkung.
|
||||
3. Nach gespeichertem Verbrauch/Start und dem vom genehmigten Skript dauerhaft
|
||||
geschriebenen Zähler den **exakten Agentprozess** kontrolliert beenden;
|
||||
PID-/Startzeit-/Artefaktbindung prüfen, keinen Prozessbaum oder ganzen
|
||||
systemd-Cgroup beenden. Roothelper und dessen Skript bleiben unbeeinflusst.
|
||||
Die gespeicherten Test-/Ledgerdaten dienen nur der Fehlerorchestrierung.
|
||||
4. Der vorhandene Agentdienst startet automatisch neu. Während der Helper noch
|
||||
arbeitet, lokalen dauerhaften Unknown und dessen tatsächliche zentrale
|
||||
Jobansicht erfassen: gleicher Versuch/Grant, höhere Revision, keine neue
|
||||
Wirkung/Starterlaubnis. Startcapability-Probes können zusätzlich bis zu
|
||||
10 Sekunden Helper-Policy und zweimal 5 Sekunden APT-Probe benötigen; den
|
||||
Zeitpuffer vorab berücksichtigen, keine Wartezeit als Ergebnis erfinden.
|
||||
5. Roothelper darf genau einmal regulär fertig werden. Sein tatsächliches
|
||||
gespeichertes Ergebnis, authentisierten Import, signierten Sync und endgültige
|
||||
identische Ergebnisbindung nachweisen. Beide Journale/Tombstones behalten;
|
||||
kein manueller Unlock und keine Wiederholung nach Fehler.
|
||||
6. Ein **separater** fester WebUI-genehmigter Lesejob prüft abschließend den
|
||||
erhaltenen Zähler exakt 1. Eigenen Antrag/Genehmigungs-/Grantnachweis getrennt
|
||||
vom ursprünglichen Versuch führen. Erst bei keiner offenen Wirkung abnehmen,
|
||||
dokumentieren und pushen.
|
||||
|
||||
Ein frei laufendes `agent_service`-Skript, dessen Prozess vor dauerhafter
|
||||
Ergebnisspeicherung stirbt, hat heute keinen unabhängigen Abschlussbeleg.
|
||||
`expected_stdout` allein rekonstruiert weder Exitstatus noch Wirkung. Diesen
|
||||
Versuch daher **nicht** als Ersatz ausführen. Der vorbereitete Roothelperfall
|
||||
weist genau den Agentprozessabbruch bei unabhängig weiterlaufendem Executor
|
||||
nach; ein gleichzeitiger Helper-/Maschinenabsturz bleibt ein anderer Fehlerfall.
|
||||
|
||||
Nachfolgender Runtime-Stand: die tatsächlich auf Cloud installierte Variante
|
||||
`agent-journal-capacity` (`2ce885cf…`) enthält dieselbe Startupkorrektur plus die
|
||||
endliche Journalbudgetkorrektur. Normaler Sync und kopierte Sandboxprobe mit
|
||||
erhaltener Historie bestanden. Das ist weiterhin **kein** nativer Crashversuch;
|
||||
der oben beschriebene kontrollierte Versuch bleibt ein eigenes Gate.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user