Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1136707c11 | ||
|
|
287a784c8f | ||
|
|
c5b767136a | ||
|
|
66e77ad83e | ||
|
|
66c1855056 | ||
|
|
6b03b222e6 | ||
|
|
e6fe4cd285 | ||
|
|
4a2fbef9ac | ||
|
|
8caa9a0478 | ||
|
|
9d98d0c603 | ||
|
|
9ddb18d9e0 | ||
|
|
c393b6bdd2 | ||
|
|
eb38b4b209 | ||
|
|
5656431ebf | ||
|
|
d532ff0ffd | ||
|
|
abea4eb4d9 |
@@ -1,6 +1,6 @@
|
||||
# Rust RMM: Architektur und Implementierungsspezifikation
|
||||
|
||||
Version 1.18 · 2026-11-14 · Sprache: Deutsch
|
||||
Version 1.19 · 2026-11-14 · Sprache: Deutsch
|
||||
|
||||
**Zweck:** Vollständige, eigenständig nutzbare Grundlage für die Implementierung einer mandantenfähigen Plattform zur Inventarisierung, Überwachung und Fernadministration von Kundengeräten durch eine Coding-KI und ein Entwicklungsteam.
|
||||
|
||||
@@ -15,6 +15,12 @@ Version 1.18 · 2026-11-14 · Sprache: Deutsch
|
||||
lokaler Helperpolicy präzisiert. Keine Vererbung von Linux-Rootrechten, keine
|
||||
Windowsfähigkeit aus einer bloßen Quellen-/Build-/Linux-Unitqualifikation.
|
||||
|
||||
1.18 → 1.19 (2026-11-14): Nächster Windows-M4-Schnitt als ausdrücklicher
|
||||
Opt-in für zwei eigene feste MSI-Rezepte (1.0 und1.0→1.1) präzisiert:
|
||||
unveränderlicher Tenantkatalog, exakte automatische Job-/Artefaktbindung,
|
||||
getrennte SYSTEM-Paketerlaubnis und unabhängige Nachbedingungen. Kein freier
|
||||
Installer, kein automatisches Update/Repair, keine implizite EXE-/Rebootfreigabe.
|
||||
|
||||
1.17 → 1.18 (2026-11-14): Ausdrückliche Userfreigabe für die feste, vor der
|
||||
WebUI-Genehmigung sichtbare RemoteSigned-Option je Windows-PowerShell5.1-
|
||||
Jobprozess, gezieltes Starten des bestehenden W32Time ohne Konfigurationsänderung
|
||||
@@ -141,6 +147,50 @@ keinen Rebootjob-Abnahmenachweis. Dokumentierte Freigaben sind keine bereits
|
||||
ausgeführten Schritte. Neue Capabilities werden erst nach ihrer getrennten
|
||||
nativen Qualifikation eröffnet.
|
||||
|
||||
**Technische Präzisierung Version1.19 — enger Windows-M4-MSI-Schnitt:**
|
||||
Nach dem getrennten SCM-Vertrag wird `ensure_package` ausschließlich für die
|
||||
eigenen festen Machine-/x64-MSI-Rezepte1.0 und1.0→1.1 erweitert. Keine freie
|
||||
SYSTEM-Shell, URL, Transformdatei, Propertyliste oder Ableitung von Linux-Root.
|
||||
Ein optionales, bei Vorhandensein streng typisiertes `windows_msi_manifest`
|
||||
bindet das vollständige kanonische Rezept samt Hash in der Action; fehlend bleibt
|
||||
bei alten Linuxjobs ausgelassen. APT- und Windowsmanifest schließen einander aus.
|
||||
Äußere Paket-/Versions-/Kontextfelder, Plattform und SYSTEM-Identität müssen
|
||||
exakt zum Rezept passen. Sämtliche historischen Linux-Codecbytes bleiben erhalten.
|
||||
|
||||
Der Windowskatalog ist eigenständig, unveränderlich und mandantengetrennt; seine
|
||||
Artefaktreferenz benötigt denselben Tenant. Pro konkretem Job/Versuch entsteht
|
||||
automatisch genau die eine Referenz aus dem genehmigten Rezept: Artefakt-ID,
|
||||
SHA256 und Länge. Freie zusätzliche Artefakt-IDs sind im MSI-Pfad verweigert.
|
||||
Fehlende, zusätzliche oder doppelte Referenzen verweigern Revalidation,
|
||||
Startgrant und Download. Der bestehende geräte-mTLS-/Job-/Versuch-gebundene
|
||||
Artefaktendpoint bleibt maßgeblich; Bootstrap-SFTP ist keine Paketabnahme.
|
||||
|
||||
Zentrale und lokale SYSTEM-Policy erweitern ihre bisherige SCM-Erlaubnis nur
|
||||
ausdrücklich versioniert um exakte MSI-Rezepthashes und eigene Paketrechte/
|
||||
Capabilities. Alte SCM-only-Profile erteilen keine Paketerlaubnis. Vor WebUI-
|
||||
Genehmigung stehen SYSTEM/Machine/x64, Rezept-/Artefakthashes, Produkt-/Upgrade-
|
||||
und beim1.1-Rezept PackageCode, feste Version/Nutzdatei, Vorgänger, feste Argumente und
|
||||
No-Reboot-Vertrag sichtbar aus den unveränderlichen Planbytes fest. Clock,
|
||||
signierter unabhängiger Helpersync, Plan/Grant und dauerhafter Einmalverbrauch
|
||||
bleiben vor Installerwirkung zwingend. Der Helper kopiert ausschließlich gegen
|
||||
das signierte Rezept geprüfte Bytes in seinen geschützten Cache; keine vom
|
||||
Netzwerkagenten frei gewählten Pfade/Programme oder allgemeinen Schreiboperationen.
|
||||
|
||||
Der getrennte Nichtdispatch-/Abandon-/RawMirror-Vertrag gilt additiv auch für
|
||||
diese konkrete typisierte Action, ohne Cache-/Provider-/Installerwirkung durch
|
||||
Abandon. Nach möglicher Übergabe gibt es keinen Execute-Retry. MSI0/3010 ist
|
||||
nur mit unabhängiger innerhalb des ursprünglichen Budgets beobachteter
|
||||
Nachbedingung erfolgreich;3010 meldet Neustartbedarf ohne Neustartstart.
|
||||
1641 bleibt Unknown,1618 bekannter Konflikt ohne Retry. Unklarer Timeout/Abbruch
|
||||
bleibt Unknown; kein globales Beenden von Windows Installer. Auch Noop benötigt
|
||||
gültige Clock/Fence, Abbruchprüfung und rechtzeitigen unabhängigen Beleg.
|
||||
Upgrade1.1 setzt genau den bekannten1.0-Vorgänger voraus; danach1.1 installiert,
|
||||
1.0 entfernt und Nutzdatei exakt. Derselbe1.1-Rezept-/PackageCode erlaubt einen
|
||||
separat genehmigten echten Noop, kein implizites Repair/Downgrade/Fresh1.1.
|
||||
Quellen, Builds und Units eröffnen keine Capability oder Policy. Native
|
||||
Installation/Upgrade/Noop erfolgen jeweils ausschließlich nach tatsächlicher
|
||||
WebUI-Genehmigung auf der Windows-VM; Linux-first-Vertragsnachweise zuerst.
|
||||
|
||||
**Technische Präzisierung Version 1.17 — Nichtstart vor SYSTEM-Delegation:**
|
||||
Vor jeder Socketübergabe bindet ein dauerhafter Intent die unveränderten
|
||||
Originalrequest-/Job-/Grant-/Signaturbytes, Plan/Autorisierung, Gerät und
|
||||
|
||||
@@ -33,8 +33,8 @@ impl Binding {
|
||||
);
|
||||
ensure!(
|
||||
j.action.validate()
|
||||
&& (1..=3600).contains(&j.max_runtime_seconds)
|
||||
&& (1..=262144).contains(&j.max_output_bytes)
|
||||
&& j.action
|
||||
.valid_job_limits(j.max_runtime_seconds, j.max_output_bytes)
|
||||
&& j.not_before < j.start_before,
|
||||
"INVALID_JOB"
|
||||
);
|
||||
@@ -72,8 +72,7 @@ impl Binding {
|
||||
ensure!(permit_window(&job, &permit), "PERMIT_TIME");
|
||||
ensure!(
|
||||
job.execution_identity == identity.as_str()
|
||||
&& matches!(&job.action, rmm_domain::jobs::Action::SetServiceState { state, .. }
|
||||
if matches!(state.as_str(), "running" | "stopped")),
|
||||
&& job.action.valid_helper_denial_shape(identity.as_str()),
|
||||
"DENIAL_HELPER_SCOPE"
|
||||
);
|
||||
Ok(VerifiedHistoricalDenial {
|
||||
|
||||
@@ -40,6 +40,7 @@ fn fixture() -> (Binding, Request, ExecutionPermitPayload, DateTime<Utc>) {
|
||||
script_utf8: "printf 'Hello\\n'\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\n".into()),
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - Duration::minutes(1),
|
||||
@@ -170,6 +171,69 @@ fn exact_permit_bytes_time_and_all_identity_hash_bindings_are_required() {
|
||||
let mut changed = request;
|
||||
changed.signature.truncate(63);
|
||||
assert!(binding.verify(&changed, now).is_err());
|
||||
// Changing only the process policy is a payload mutation, even with the
|
||||
// same script/attempt and a still valid original signature.
|
||||
let (_, mut request, mut permit, _) = fixture();
|
||||
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
|
||||
job.action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'Hello'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
|
||||
binding.verify(&request, now).unwrap();
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
*windows_execution_profile =
|
||||
Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
}
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
assert!(binding.verify(&request, now).is_err());
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
|
||||
binding.verify(&request, now).unwrap();
|
||||
// The exact fixed Event Log source/window/limits are original signed bytes.
|
||||
job.action = Action::QueryLogs {
|
||||
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - chrono::Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
};
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.action = job.action.name().into();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = key.sign(&request.permit_bytes).to_bytes().to_vec();
|
||||
binding.verify(&request, now).unwrap();
|
||||
let mut wrong_source = job.clone();
|
||||
if let Action::QueryLogs { unit, .. } = &mut wrong_source.action {
|
||||
*unit = "Security".into();
|
||||
}
|
||||
let mut changed = request.clone();
|
||||
changed.job_bytes = encode(&wrong_source).unwrap();
|
||||
assert!(binding.verify(&changed, now).is_err());
|
||||
for (runtime, bytes) in [(9, 4096), (121, 4096), (10, 1023), (10, 65537)] {
|
||||
let mut changed_job = job.clone();
|
||||
changed_job.max_runtime_seconds = runtime;
|
||||
changed_job.max_output_bytes = bytes;
|
||||
let mut changed_permit = permit.clone();
|
||||
changed_permit.max_runtime_seconds = runtime;
|
||||
let mut changed = request.clone();
|
||||
changed.job_bytes = encode(&changed_job).unwrap();
|
||||
changed_permit.job_payload_hash = hash(&changed.job_bytes);
|
||||
changed.permit_bytes = encode(&changed_permit).unwrap();
|
||||
changed.signature = key.sign(&changed.permit_bytes).to_bytes().to_vec();
|
||||
assert!(binding.verify(&changed, now).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -416,3 +480,96 @@ fn completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evid
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority() {
|
||||
use rmm_agent_core::auth::HelperIdentity;
|
||||
use rmm_domain::windows_execution::*;
|
||||
let (binding, mut request, mut permit, now) = fixture();
|
||||
let mut job: JobPayload = serde_json::from_slice(&request.job_bytes).unwrap();
|
||||
let recipe = WindowsMsiRecipe {
|
||||
schema_version: 1,
|
||||
recipe_id: MSI_RECIPE_ID.into(),
|
||||
recipe_version: "1".into(),
|
||||
platform: "windows".into(),
|
||||
upgrade_code: MSI_UPGRADE_CODE.into(),
|
||||
architecture: Architecture::X64,
|
||||
context: InstallContext::Machine,
|
||||
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
|
||||
artifact: MsiArtifact {
|
||||
artifact_id: Uuid::from_u128(19),
|
||||
sha256: "ab".repeat(32),
|
||||
bytes: 32,
|
||||
},
|
||||
postcondition: MsiPostcondition {
|
||||
product_code: MSI_PRODUCT_CODE.into(),
|
||||
product_version: MSI_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: None,
|
||||
predecessor: None,
|
||||
};
|
||||
let manifest = ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
};
|
||||
job.action = Action::EnsurePackage {
|
||||
provider: "msi".into(),
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: MSI_VERSION.into(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: "1".into(),
|
||||
installation_context: "machine".into(),
|
||||
recipe_id: Some(MSI_RECIPE_ID.into()),
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: Some(Box::new(manifest)),
|
||||
};
|
||||
job.execution_identity = "system".into();
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
permit.action = "ensure_package".into();
|
||||
permit.execution_identity = "system".into();
|
||||
permit.job_payload_hash = hash(&request.job_bytes);
|
||||
request.permit_bytes = encode(&permit).unwrap();
|
||||
request.signature = SigningKey::from_bytes(&[9; 32])
|
||||
.sign(&request.permit_bytes)
|
||||
.to_bytes()
|
||||
.to_vec();
|
||||
binding
|
||||
.verify_historical_for_denial_with(
|
||||
&request,
|
||||
HelperIdentity::System,
|
||||
&rmm_agent_core::crypto::DalekVerifier,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
binding
|
||||
.verify_historical_for_denial_with(
|
||||
&request,
|
||||
HelperIdentity::Root,
|
||||
&rmm_agent_core::crypto::DalekVerifier
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(binding.verify(&request, now + Duration::hours(1)).is_err()); // historical denial is never live authorization
|
||||
if let Action::EnsurePackage {
|
||||
windows_msi_manifest: Some(m),
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
m.recipe.artifact.bytes += 1;
|
||||
m.recipe_sha256 = m.recipe.sha256().unwrap();
|
||||
}
|
||||
request.job_bytes = encode(&job).unwrap();
|
||||
assert!(
|
||||
binding
|
||||
.verify_historical_for_denial_with(
|
||||
&request,
|
||||
HelperIdentity::System,
|
||||
&rmm_agent_core::crypto::DalekVerifier
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -867,6 +867,7 @@ fn script() -> Action {
|
||||
script_utf8: "printf hello".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -605,6 +605,7 @@ fn script() -> Action {
|
||||
script_utf8: "printf hello".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -39,4 +39,4 @@ rcgen = { version = "=0.14.10", default-features = false, features = ["crypto",
|
||||
cc = "=1.11.1"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||
windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_ApplicationInstallationAndServicing", "Win32_System_EventLog", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Pipes", "Win32_System_SystemInformation", "Win32_System_Registry", "Win32_System_Memory", "Win32_System_Services", "Win32_System_Threading"] }
|
||||
|
||||
@@ -157,6 +157,7 @@ mod service {
|
||||
let clock = super::clock::NativeClock::new();
|
||||
STAGE.store(30, Ordering::SeqCst);
|
||||
let pipe = super::clock::named_pipe_diagnostic();
|
||||
let status_rpc = super::clock::status_rpc_diagnostic();
|
||||
let first = clock.report();
|
||||
std::thread::sleep(Duration::from_millis(750));
|
||||
STAGE.store(31, Ordering::SeqCst);
|
||||
@@ -164,7 +165,7 @@ mod service {
|
||||
let identity_controls = super::clock::identity_controls();
|
||||
STAGE.store(40, Ordering::SeqCst);
|
||||
let data = serde_json::to_vec_pretty(
|
||||
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
||||
&serde_json::json!({"schema":1,"case_id":case,"service_name":NAME,"token_sid":"S-1-5-19","elevated":token.elevation_flag!=0,"token":token,"endpoints":endpoints,"named_pipe_diagnostic":pipe,"status_rpc_diagnostic":status_rpc,"identity_controls":identity_controls,"source":"MS-W32T:4.1:Opnum6:ncalrpc:SID19:W32Time:V5_descriptor:MUTUAL_AUTH:WINNT:PKT_PRIVACY","read_only":true,"samples":[first,second]}),
|
||||
)?;
|
||||
ensure!(data.len() < 16384, "READINESS_REPORT_SIZE");
|
||||
STAGE.store(41, Ordering::SeqCst);
|
||||
@@ -259,6 +260,6 @@ fn main() -> anyhow::Result<()> {
|
||||
fn main() {
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
|
||||
serde_json::to_string(&serde_json::json!({"clock":clock::NativeClock::new().report(),"endpoints":clock::endpoint_report(),"named_pipe_diagnostic":clock::named_pipe_diagnostic(),"status_rpc_diagnostic":clock::status_rpc_diagnostic(),"identity_controls":clock::identity_controls()})).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -71,20 +71,47 @@ typedef struct {
|
||||
} RmmClockStatus;
|
||||
_Static_assert(sizeof(RmmClockStatus) == 64, "Rust numeric clock ABI");
|
||||
_Static_assert(sizeof(RMM_W32TIME_STATUS) == 120, "MS-W32T x64 structure ABI");
|
||||
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
|
||||
/* Diagnostic-only numeric ABI. No strings, names, pointers or remote arrays
|
||||
* leave C. A zero native return is meaningful only when return_present is1.
|
||||
* Stages:10 compose,20 binding,30 auth,40 call-timeout,50 arena,
|
||||
* 60 invoking,61 returned,62 raw numeric status,70 local guard,80 mapped,
|
||||
* 90 contained RPC/SEH exception. Never used by the clock trust evaluator.
|
||||
*/
|
||||
typedef struct {
|
||||
uint32_t stage, native_rpc_return, native_rpc_return_present, rpc_exception;
|
||||
uint32_t status_present, ul_size, c_entries, p_entries_present;
|
||||
} RmmClockTrace;
|
||||
_Static_assert(sizeof(RmmClockTrace) == 32, "Rust numeric diagnostic ABI");
|
||||
static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out, RmmClockTrace *trace) {
|
||||
RMM_W32TIME_STATUS *status = NULL;
|
||||
unsigned long result = 0;
|
||||
Arena arena = {0};
|
||||
if (trace) trace->stage = 50;
|
||||
if (!result && !InitOnceExecuteOnce(&arena_once, initialize_arena, NULL, NULL)) result = ERROR_NOT_ENOUGH_MEMORY;
|
||||
if (!result && TlsGetValue(arena_index)) result = ERROR_BUSY;
|
||||
if (!result && !TlsSetValue(arena_index, &arena)) result = GetLastError();
|
||||
if (!result) {
|
||||
RpcTryExcept {
|
||||
if (trace) trace->stage = 60;
|
||||
result = RmmW32TimeQueryStatus(binding, &status);
|
||||
if (trace) {
|
||||
trace->stage = 61; trace->native_rpc_return_present = 1;
|
||||
trace->native_rpc_return = result;
|
||||
}
|
||||
if (!result) {
|
||||
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries)
|
||||
if (trace) {
|
||||
trace->stage = 62; trace->status_present = status != NULL;
|
||||
if (status) {
|
||||
trace->ul_size = status->ulSize; trace->c_entries = status->cEntries;
|
||||
trace->p_entries_present = status->pEntries != NULL;
|
||||
}
|
||||
}
|
||||
if (!status || status->ulSize != sizeof(*status) || status->cEntries || status->pEntries) {
|
||||
if (trace) trace->stage = 70;
|
||||
result = RPC_X_BAD_STUB_DATA;
|
||||
}
|
||||
else {
|
||||
if (trace) trace->stage = 80;
|
||||
out->leap = status->eLeapIndicator; out->stratum = status->nStratum;
|
||||
out->state = status->ulLcState; out->flags = status->ulTSFlags;
|
||||
out->last_result = status->eLastSyncResult; out->size = status->ulSize;
|
||||
@@ -95,21 +122,24 @@ static uint32_t invoke_status(RPC_BINDING_HANDLE binding, RmmClockStatus *out) {
|
||||
}
|
||||
} RpcExcept(RpcExceptionFilter(RpcExceptionCode())) {
|
||||
result = RpcExceptionCode();
|
||||
if (trace) {trace->stage = 90; trace->rpc_exception = result;}
|
||||
} RpcEndExcept
|
||||
release_allocations(&arena);
|
||||
TlsSetValue(arena_index, NULL);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
uint32_t rmm_clock_query(RmmClockStatus *out) {
|
||||
static uint32_t pipe_query(RmmClockStatus *out, RmmClockTrace *trace) {
|
||||
RPC_WSTR text = NULL;
|
||||
RPC_BINDING_HANDLE binding = NULL;
|
||||
RPC_SECURITY_QOS qos = {0};
|
||||
unsigned long result;
|
||||
memset(out, 0, sizeof(*out));
|
||||
if (trace) trace->stage = 10;
|
||||
result = RpcStringBindingComposeW(NULL, (RPC_WSTR)L"ncacn_np", NULL,
|
||||
(RPC_WSTR)L"\\pipe\\W32TIME_ALT", NULL, &text);
|
||||
if (result) return result;
|
||||
if (trace) trace->stage = 20;
|
||||
result = RpcBindingFromStringBindingW(text, &binding);
|
||||
RpcStringFreeW(&text);
|
||||
if (result) return result;
|
||||
@@ -117,13 +147,23 @@ uint32_t rmm_clock_query(RmmClockStatus *out) {
|
||||
qos.Capabilities = RPC_C_QOS_CAPABILITIES_DEFAULT;
|
||||
qos.IdentityTracking = RPC_C_QOS_IDENTITY_STATIC;
|
||||
qos.ImpersonationType = RPC_C_IMP_LEVEL_IDENTIFY;
|
||||
if (trace) trace->stage = 30;
|
||||
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, &qos);
|
||||
if (!result) result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||
if (!result) result = invoke_status(binding, out);
|
||||
if (!result) {
|
||||
if (trace) trace->stage = 40;
|
||||
result = RpcBindingSetOption(binding, RPC_C_OPT_CALL_TIMEOUT, 1500);
|
||||
}
|
||||
if (!result) result = invoke_status(binding, out, trace);
|
||||
RpcBindingFree(&binding);
|
||||
return result;
|
||||
}
|
||||
uint32_t rmm_clock_query(RmmClockStatus *out) { return pipe_query(out, NULL); }
|
||||
uint32_t rmm_clock_query_trace(RmmClockTrace *trace) {
|
||||
RmmClockStatus ignored = {0};
|
||||
memset(trace, 0, sizeof(*trace));
|
||||
return pipe_query(&ignored, trace);
|
||||
}
|
||||
/* Kernel-authenticated ALPC only. No automatic fallback to named pipes.
|
||||
* The expected SID is fixed locally, never adopted from endpoint metadata.
|
||||
*/
|
||||
@@ -188,7 +228,7 @@ static uint32_t alpc_query(RmmClockStatus *out, unsigned control) {
|
||||
qos.ServerSecurityDescriptor = &descriptor;
|
||||
result = RpcBindingSetAuthInfoExW(binding, NULL, RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
|
||||
RPC_C_AUTHN_WINNT, NULL, RPC_C_AUTHZ_NONE, (RPC_SECURITY_QOS *)&qos);
|
||||
if (!result) result = invoke_status(binding, out);
|
||||
if (!result) result = invoke_status(binding, out, NULL);
|
||||
}
|
||||
RpcBindingFree(&binding);
|
||||
break; /* no retry, alternate identity, endpoint or weaker transport */
|
||||
|
||||
@@ -31,6 +31,11 @@ typedef struct {
|
||||
unsigned long cEntries;
|
||||
[size_is(cEntries)] RMM_W32TIME_ENTRY *pEntries;
|
||||
} RMM_W32TIME_STATUS;
|
||||
/* Microsoft declares PW32TIME_STATUS_INFO separately. Keep the inner pointer
|
||||
* explicitly unique; the out parameter's outer pointer defaults to ref.
|
||||
* WIDL 7 propagates a parameter-level [ref] through a direct ** declaration.
|
||||
*/
|
||||
typedef [unique] RMM_W32TIME_STATUS *RMM_PW32TIME_STATUS;
|
||||
[uuid(8fb6d884-2388-11d0-8c35-00c04fda2795), version(4.1), pointer_default(unique)]
|
||||
interface RmmW32Time {
|
||||
unsigned long RmmUnusedSlot0([in] handle_t binding);
|
||||
@@ -39,5 +44,5 @@ interface RmmW32Time {
|
||||
unsigned long RmmUnusedSlot3([in] handle_t binding);
|
||||
unsigned long RmmUnusedSlot4([in] handle_t binding);
|
||||
unsigned long RmmUnusedSlot5([in] handle_t binding);
|
||||
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out, ref] RMM_W32TIME_STATUS **status);
|
||||
unsigned long RmmW32TimeQueryStatus([in] handle_t binding, [out] RMM_PW32TIME_STATUS *status);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! consumption are supplied by the shared core and the runtime, never bypassed.
|
||||
use anyhow::{Result, ensure};
|
||||
use rmm_agent_core::auth::Outcome;
|
||||
use rmm_domain::jobs::{Action, JobPayload, hash};
|
||||
use rmm_domain::jobs::{Action, JobPayload, WindowsExecutionProfile, hash};
|
||||
use std::{
|
||||
ffi::OsString,
|
||||
fs::{File, OpenOptions},
|
||||
@@ -11,6 +11,41 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::atomic::AtomicBool,
|
||||
};
|
||||
/// Implemented contract name only. Runtime publication still requires its own
|
||||
/// native clock/boot/job qualification; this constant grants no capability.
|
||||
pub const REMOTE_SIGNED_PROFILE_CAPABILITY: &str = "script.powershell.process_remote_signed/1";
|
||||
|
||||
fn script_arguments(job: &JobPayload, path: &Path) -> Result<Vec<OsString>> {
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
arguments,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("SCRIPT_REQUIRED")
|
||||
};
|
||||
ensure!(
|
||||
job.execution_identity == "agent_service"
|
||||
&& interpreter == "powershell"
|
||||
&& job.action.validate(),
|
||||
"WINDOWS_SCRIPT_PROFILE_BINDING"
|
||||
);
|
||||
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive"]
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect();
|
||||
if let Some(WindowsExecutionProfile::PowerShell51RemoteSigned) = windows_execution_profile {
|
||||
args.extend([
|
||||
OsString::from("-ExecutionPolicy"),
|
||||
OsString::from("RemoteSigned"),
|
||||
]);
|
||||
}
|
||||
args.push(OsString::from("-File"));
|
||||
args.push(path.as_os_str().into());
|
||||
args.extend(arguments.iter().map(OsString::from));
|
||||
Ok(args)
|
||||
}
|
||||
use windows_sys::Win32::{
|
||||
Storage::FileSystem::{
|
||||
FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ,
|
||||
@@ -36,10 +71,45 @@ pub fn supported(job: &JobPayload) -> bool {
|
||||
interpreter == "powershell" && powershell().is_ok()
|
||||
}
|
||||
Action::RefreshInventory { scope } => scope == "windows.base",
|
||||
Action::QueryLogs { .. } => crate::event_log::for_job(job).is_ok(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each prepared operation retains its own typed binding; no non-script action
|
||||
/// can fall through to inventory or borrow the PowerShell execution profile.
|
||||
pub enum PreparedAction {
|
||||
Script(Script),
|
||||
Inventory,
|
||||
EventLog(crate::event_log_job::Prepared),
|
||||
}
|
||||
impl PreparedAction {
|
||||
pub fn prepare(
|
||||
job: &JobPayload,
|
||||
directory: &Path,
|
||||
grant: uuid::Uuid,
|
||||
request: &rmm_agent_core::auth::Request,
|
||||
boot: uuid::Uuid,
|
||||
) -> Result<Self> {
|
||||
ensure!(supported(job), "UNSUPPORTED_CAPABILITY");
|
||||
match &job.action {
|
||||
Action::RunScript { .. } => Ok(Self::Script(Script::prepare(job, directory, grant)?)),
|
||||
Action::RefreshInventory { scope } if scope == "windows.base" => Ok(Self::Inventory),
|
||||
Action::QueryLogs { .. } => Ok(Self::EventLog(
|
||||
crate::event_log_job::Prepared::prepare(job, directory, request, grant, boot)?,
|
||||
)),
|
||||
_ => anyhow::bail!("UNSUPPORTED_CAPABILITY"),
|
||||
}
|
||||
}
|
||||
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||
match self {
|
||||
Self::Script(script) => script.run(job, cancel),
|
||||
Self::Inventory => inventory(job),
|
||||
Self::EventLog(log) => log.run(job, cancel),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Script {
|
||||
executable: PathBuf,
|
||||
path: PathBuf,
|
||||
@@ -47,6 +117,7 @@ pub struct Script {
|
||||
_file: File,
|
||||
cwd: PathBuf,
|
||||
arguments: Vec<OsString>,
|
||||
profile: Option<WindowsExecutionProfile>,
|
||||
}
|
||||
impl Script {
|
||||
/// Preparation creates only a protected copy of approved bytes, no child.
|
||||
@@ -56,7 +127,7 @@ impl Script {
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
@@ -95,18 +166,14 @@ impl Script {
|
||||
hash(&std::fs::read(&path)?) == hash(script_utf8.as_bytes()),
|
||||
"SCRIPT_BYTES_CHANGED"
|
||||
);
|
||||
let mut args: Vec<OsString> = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File"]
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect();
|
||||
args.push(path.clone().into_os_string());
|
||||
args.extend(arguments.iter().map(OsString::from));
|
||||
let args = script_arguments(job, &path)?;
|
||||
Ok(Self {
|
||||
executable: powershell()?,
|
||||
path,
|
||||
_file: file,
|
||||
cwd: directory.to_path_buf(),
|
||||
arguments: args,
|
||||
profile: *windows_execution_profile,
|
||||
})
|
||||
}
|
||||
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||
@@ -115,6 +182,7 @@ impl Script {
|
||||
let Action::RunScript {
|
||||
script_utf8,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
@@ -124,6 +192,11 @@ impl Script {
|
||||
std::fs::read(&self.path)? == script_utf8.as_bytes(),
|
||||
"SCRIPT_BYTES_CHANGED"
|
||||
);
|
||||
ensure!(
|
||||
self.profile == *windows_execution_profile
|
||||
&& self.arguments == script_arguments(job, &self.path)?,
|
||||
"WINDOWS_SCRIPT_PROFILE_CHANGED"
|
||||
);
|
||||
let output = crate::process::run(
|
||||
&self.executable,
|
||||
&self.arguments,
|
||||
@@ -159,6 +232,17 @@ impl Script {
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let mut evidence = serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
|
||||
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
|
||||
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
|
||||
"execution_policy":"inherited","process_tree_bounded":true,
|
||||
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted});
|
||||
if self.profile.is_some() {
|
||||
evidence["windows_execution_profile"] = serde_json::to_value(self.profile)?;
|
||||
evidence["execution_policy"] = serde_json::json!("process_remote_signed_requested");
|
||||
evidence["execution_policy_requested"] = serde_json::json!("RemoteSigned");
|
||||
evidence["execution_policy_scope"] = serde_json::json!("process");
|
||||
}
|
||||
Ok(Outcome {
|
||||
state: state.into(),
|
||||
stdout: output.stdout,
|
||||
@@ -167,11 +251,7 @@ impl Script {
|
||||
output_truncated: output.truncated,
|
||||
reboot_required: false,
|
||||
error_code: code.into(),
|
||||
evidence: serde_json::json!({"postconditions_passed":success,"interpreter":"powershell",
|
||||
"script_sha256":hash(script_utf8.as_bytes()),"execution_sid":"S-1-5-19",
|
||||
"output_encoding":"raw_native_bytes","comparison":"exact_utf8_bytes",
|
||||
"execution_policy":"inherited","process_tree_bounded":true,
|
||||
"cancel_requested":output.cancelled,"termination_does_not_prove_absence_of_effects":output.interrupted}),
|
||||
evidence,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -200,3 +280,88 @@ pub fn inventory(job: &JobPayload) -> Result<Outcome> {
|
||||
"observed_at":chrono::Utc::now(),"completeness":"partial","execution_sid":"S-1-5-19"}),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
let mut 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: Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'fixed'\r\n".into(),
|
||||
arguments: vec!["-ExecutionPolicy".into(), "Bypass".into()],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::seconds(60),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let path = Path::new(r"C:\fixed state\approved.ps1");
|
||||
let inherited = script_arguments(&job, path).unwrap();
|
||||
assert_eq!(
|
||||
inherited,
|
||||
vec![
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-File",
|
||||
r"C:\fixed state\approved.ps1",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass"
|
||||
]
|
||||
.into_iter()
|
||||
.map(OsString::from)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut job.action
|
||||
{
|
||||
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
}
|
||||
let args = script_arguments(&job, path).unwrap();
|
||||
assert_eq!(
|
||||
args[..6],
|
||||
[
|
||||
"-NoLogo",
|
||||
"-NoProfile",
|
||||
"-NonInteractive",
|
||||
"-ExecutionPolicy",
|
||||
"RemoteSigned",
|
||||
"-File"
|
||||
]
|
||||
.map(OsString::from)
|
||||
);
|
||||
assert_eq!(args[6], path.as_os_str()); // approved arguments remain AFTER -File
|
||||
assert_ne!(inherited, args);
|
||||
let mut unknown = serde_json::to_value(&job.action).unwrap();
|
||||
unknown["windows_execution_profile"] = serde_json::json!("Bypass");
|
||||
assert!(serde_json::from_value::<Action>(unknown).is_err());
|
||||
for identity in ["root", "system"] {
|
||||
job.execution_identity = identity.into();
|
||||
assert!(script_arguments(&job, path).is_err());
|
||||
}
|
||||
job.execution_identity = "agent_service".into();
|
||||
for other in ["posix_sh", "bash", "pwsh"] {
|
||||
if let Action::RunScript { interpreter, .. } = &mut job.action {
|
||||
*interpreter = other.into();
|
||||
}
|
||||
assert!(script_arguments(&job, path).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,6 +259,87 @@ pub fn named_pipe_diagnostic() -> ClockReport {
|
||||
}
|
||||
.report()
|
||||
}
|
||||
/// Diagnostic-only ABI captured before the existing C layout guard. Presence
|
||||
/// flags are numeric0/1; no remote pointers, names or returned entries escape.
|
||||
#[derive(Clone, Copy, Debug, Default, Serialize)]
|
||||
#[repr(C)]
|
||||
pub struct StatusRpcTrace {
|
||||
pub stage: u32,
|
||||
pub native_rpc_return: u32,
|
||||
pub native_rpc_return_present: u32,
|
||||
pub rpc_exception: u32,
|
||||
pub status_present: u32,
|
||||
pub ul_size: u32,
|
||||
pub c_entries: u32,
|
||||
pub p_entries_present: u32,
|
||||
}
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct StatusRpcDiagnostic {
|
||||
pub rpc_code: u32,
|
||||
pub independent_call: bool,
|
||||
pub trace: Option<StatusRpcTrace>,
|
||||
pub diagnostic_only: bool,
|
||||
pub adapter_qualified: bool,
|
||||
pub trusted: bool,
|
||||
}
|
||||
/// The fixed authenticated named-pipe call is observed separately. It never
|
||||
/// selects a production transport or supplies a trusted timestamp. One worker,
|
||||
/// one outstanding call and no replacement/retry after a local timeout.
|
||||
pub fn status_rpc_diagnostic() -> StatusRpcDiagnostic {
|
||||
#[cfg(windows)]
|
||||
let (rpc_code, trace) = {
|
||||
type Reply = std::sync::mpsc::SyncSender<(u32, StatusRpcTrace)>;
|
||||
type Requests = std::sync::mpsc::SyncSender<Reply>;
|
||||
static WORKER: std::sync::OnceLock<Mutex<Option<Requests>>> = std::sync::OnceLock::new();
|
||||
let worker = WORKER.get_or_init(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::sync_channel::<Reply>(1);
|
||||
let created = std::thread::Builder::new()
|
||||
.name("rmm-clock-status-diag".into())
|
||||
.spawn(move || {
|
||||
#[link(name = "rmm_clock_rpc", kind = "static")]
|
||||
#[link(name = "rpcrt4")]
|
||||
#[link(name = "advapi32")]
|
||||
unsafe extern "C" {
|
||||
fn rmm_clock_query_trace(trace: *mut StatusRpcTrace) -> u32;
|
||||
}
|
||||
while let Ok(reply) = receiver.recv() {
|
||||
let mut trace = StatusRpcTrace::default();
|
||||
// SAFETY: fixed8*u32 C ABI; SEH stays contained inside C.
|
||||
let code = unsafe { rmm_clock_query_trace(&mut trace) };
|
||||
let _ = reply.send((code, trace));
|
||||
}
|
||||
})
|
||||
.is_ok();
|
||||
Mutex::new(created.then_some(sender))
|
||||
});
|
||||
if let Ok(mut worker) = worker.try_lock() {
|
||||
let (reply, receiver) = std::sync::mpsc::sync_channel(1);
|
||||
let sent = worker
|
||||
.as_ref()
|
||||
.is_some_and(|sender| sender.try_send(reply).is_ok());
|
||||
if sent
|
||||
&& let Ok((code, trace)) = receiver.recv_timeout(std::time::Duration::from_secs(2))
|
||||
{
|
||||
(code, Some(trace))
|
||||
} else {
|
||||
*worker = None;
|
||||
(1818, None)
|
||||
}
|
||||
} else {
|
||||
(170, None)
|
||||
}
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let (rpc_code, trace) = (50, None);
|
||||
StatusRpcDiagnostic {
|
||||
rpc_code,
|
||||
independent_call: true,
|
||||
trace,
|
||||
diagnostic_only: true,
|
||||
adapter_qualified: false,
|
||||
trusted: false,
|
||||
}
|
||||
}
|
||||
/// Read-only negative controls for the separate native readiness program.
|
||||
/// Neither control can produce clock authority, even if the OS accepts it.
|
||||
/// Rejection without a successful genuine status query is not identity proof.
|
||||
@@ -443,6 +524,7 @@ mod tests {
|
||||
}
|
||||
#[test]
|
||||
fn production_clock_stays_closed_until_native_adapter_qualification() {
|
||||
assert_eq!(std::mem::size_of::<StatusRpcTrace>(), 32);
|
||||
assert_eq!(
|
||||
NativeClock::new().now().unwrap_err().to_string(),
|
||||
"CLOCK_ADAPTER_UNQUALIFIED"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Bounded, local, fixture-only live Event Log query; not wired into any job.
|
||||
//! Bounded, local, fixture-only Event Log provider. Only the authorized native
|
||||
//! job worker may call the Windows provider; this module confers no authority.
|
||||
//!
|
||||
//! EvtQuery/EvtRender have no per-call timeout. The monotonic deadline below is
|
||||
//! cooperative between Win32 calls; the eventual executor must also supervise
|
||||
@@ -12,8 +13,9 @@ use chrono::{DateTime, SecondsFormat, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
pub const CHANNEL: &str = "Application";
|
||||
pub const PROVIDER: &str = "RustDiscovery-MVP-Test";
|
||||
pub use rmm_domain::jobs::{
|
||||
WINDOWS_EVENT_LOG_FIXTURE_CHANNEL as CHANNEL, WINDOWS_EVENT_LOG_FIXTURE_PROVIDER as PROVIDER,
|
||||
};
|
||||
const MAX_BYTES: usize = 256 * 1024;
|
||||
#[cfg(any(windows, test))]
|
||||
const REPORT_RESERVE: usize = 256;
|
||||
@@ -57,7 +59,42 @@ impl Query {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
/// Pure job-to-provider binding. Never opens a channel or touches a bookmark.
|
||||
pub fn for_job(job: &rmm_domain::jobs::JobPayload) -> Result<Query> {
|
||||
use rmm_domain::jobs::{Action, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
|
||||
let Action::QueryLogs {
|
||||
unit,
|
||||
since,
|
||||
until,
|
||||
max_lines,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("EVENT_LOG_ACTION_REQUIRED")
|
||||
};
|
||||
ensure!(
|
||||
job.execution_identity == "agent_service"
|
||||
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes),
|
||||
"EVENT_LOG_JOB_BINDING"
|
||||
);
|
||||
let q = Query {
|
||||
channel: CHANNEL.into(),
|
||||
provider: PROVIDER.into(),
|
||||
start_utc: *since,
|
||||
end_utc: *until,
|
||||
max_events: *max_lines,
|
||||
max_output_bytes: job.max_output_bytes,
|
||||
timeout_ms: 5000,
|
||||
};
|
||||
q.xpath()?;
|
||||
Ok(q)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Event {
|
||||
pub channel: String,
|
||||
pub provider: String,
|
||||
@@ -501,6 +538,53 @@ mod tests {
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits() {
|
||||
use rmm_domain::jobs::{Action, JobPayload, WINDOWS_EVENT_LOG_FIXTURE_SOURCE};
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
let mut 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: Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now,
|
||||
until: now + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::seconds(60),
|
||||
max_runtime_seconds: 10,
|
||||
max_output_bytes: 65536,
|
||||
};
|
||||
let q = for_job(&job).unwrap();
|
||||
assert_eq!(
|
||||
(q.channel.as_str(), q.provider.as_str()),
|
||||
(CHANNEL, PROVIDER)
|
||||
);
|
||||
assert_eq!(q.max_output_bytes, 65536);
|
||||
for identity in ["root", "system"] {
|
||||
job.execution_identity = identity.into();
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
job.execution_identity = "agent_service".into();
|
||||
for bytes in [1023, 65537] {
|
||||
job.max_output_bytes = bytes;
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
job.max_output_bytes = 65536;
|
||||
if let Action::QueryLogs { until, .. } = &mut job.action {
|
||||
*until += chrono::Duration::nanoseconds(1);
|
||||
}
|
||||
assert!(for_job(&job).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn serialized_byte_budget_includes_xml_escaping_and_metadata() {
|
||||
let q = request();
|
||||
let mut report = Report::new(&q);
|
||||
|
||||
@@ -0,0 +1,778 @@
|
||||
//! Fixed, authorized Event Log subprocess. A command-line mode is not a live
|
||||
//! query API: the child authenticates its real SCM parent, original signed
|
||||
//! request, protected public trust, and an already committed consumption/start.
|
||||
//! Request/grant bytes remain in a private, create-once job file, never argv.
|
||||
use crate::{event_log, native};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_agent_core::auth::{Binding, Outcome, Request};
|
||||
use rmm_domain::jobs::{ExecutionPermitPayload, JobPayload, hash};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
mem::{size_of, size_of_val, zeroed},
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle, OwnedHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
sync::atomic::AtomicBool,
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
Security::{self, *},
|
||||
Storage::FileSystem::*,
|
||||
System::{Diagnostics::ToolHelp::*, Services::*, Threading::*},
|
||||
};
|
||||
|
||||
pub const MODE: &str = "--eventlog-worker";
|
||||
const CONFIG: &str = r"C:\ProgramData\RustDiscovery\config.json";
|
||||
const TICKET_LIMIT: u64 = 128 * 1024;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct FileId {
|
||||
volume: u64,
|
||||
id: [u8; 16],
|
||||
}
|
||||
fn file_id(handle: HANDLE) -> Result<FileId> {
|
||||
let mut info: FILE_ID_INFO = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
GetFileInformationByHandleEx(
|
||||
handle,
|
||||
FileIdInfo,
|
||||
(&mut info as *mut FILE_ID_INFO).cast(),
|
||||
size_of::<FILE_ID_INFO>() as u32,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_FILE_ID"
|
||||
);
|
||||
Ok(FileId {
|
||||
volume: info.VolumeSerialNumber,
|
||||
id: info.FileId.Identifier,
|
||||
})
|
||||
}
|
||||
fn owned(handle: HANDLE) -> Result<OwnedHandle> {
|
||||
ensure!(
|
||||
!handle.is_null() && handle != INVALID_HANDLE_VALUE,
|
||||
"EVENT_LOG_HANDLE"
|
||||
);
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
fn birth(handle: HANDLE) -> Result<u64> {
|
||||
let (mut c, mut e, mut k, mut u) = unsafe { (zeroed(), zeroed(), zeroed(), zeroed()) };
|
||||
ensure!(
|
||||
unsafe { GetProcessTimes(handle, &mut c, &mut e, &mut k, &mut u) } != 0,
|
||||
"EVENT_LOG_PROCESS_TIME"
|
||||
);
|
||||
Ok((u64::from(c.dwHighDateTime) << 32) | u64::from(c.dwLowDateTime))
|
||||
}
|
||||
fn text(value: *const u16) -> Result<String> {
|
||||
ensure!(!value.is_null(), "EVENT_LOG_NATIVE_STRING");
|
||||
let mut length = 0;
|
||||
while length < 32768 && unsafe { *value.add(length) } != 0 {
|
||||
length += 1;
|
||||
}
|
||||
ensure!(length < 32768, "EVENT_LOG_NATIVE_STRING_SIZE");
|
||||
Ok(String::from_utf16(unsafe {
|
||||
std::slice::from_raw_parts(value, length)
|
||||
})?)
|
||||
}
|
||||
fn process_image(handle: HANDLE) -> Result<PathBuf> {
|
||||
let mut buffer = vec![0u16; 32768];
|
||||
let mut len = buffer.len() as u32;
|
||||
ensure!(
|
||||
unsafe { QueryFullProcessImageNameW(handle, 0, buffer.as_mut_ptr(), &mut len) } != 0,
|
||||
"EVENT_LOG_PARENT_IMAGE"
|
||||
);
|
||||
Ok(String::from_utf16(&buffer[..len as usize])?.into())
|
||||
}
|
||||
struct Service(SC_HANDLE);
|
||||
impl Drop for Service {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
CloseServiceHandle(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn agent_pid(image: &Path) -> Result<u32> {
|
||||
let manager = Service(unsafe { OpenSCManagerW(ptr::null(), ptr::null(), SC_MANAGER_CONNECT) });
|
||||
ensure!(!manager.0.is_null(), "EVENT_LOG_SCM");
|
||||
let service = Service(unsafe {
|
||||
OpenServiceW(
|
||||
manager.0,
|
||||
native::wide(crate::SERVICE_NAME).as_ptr(),
|
||||
SERVICE_QUERY_CONFIG | SERVICE_QUERY_STATUS,
|
||||
)
|
||||
});
|
||||
ensure!(!service.0.is_null(), "EVENT_LOG_AGENT_SERVICE");
|
||||
let mut bytes = 0;
|
||||
unsafe {
|
||||
QueryServiceConfigW(service.0, ptr::null_mut(), 0, &mut bytes);
|
||||
}
|
||||
ensure!((1..=32768).contains(&bytes), "EVENT_LOG_AGENT_CONFIG_SIZE");
|
||||
let mut storage = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { QueryServiceConfigW(service.0, storage.as_mut_ptr().cast(), bytes, &mut bytes) }
|
||||
!= 0,
|
||||
"EVENT_LOG_AGENT_CONFIG"
|
||||
);
|
||||
let config = unsafe { &*storage.as_ptr().cast::<QUERY_SERVICE_CONFIGW>() };
|
||||
ensure!(
|
||||
config.dwServiceType == SERVICE_WIN32_OWN_PROCESS
|
||||
&& text(config.lpBinaryPathName)?
|
||||
== format!("\"{}\" --service --config \"{CONFIG}\"", image.display())
|
||||
&& text(config.lpServiceStartName)?.eq_ignore_ascii_case(r"NT AUTHORITY\LocalService"),
|
||||
"EVENT_LOG_AGENT_CONFIG_BINDING"
|
||||
);
|
||||
let mut status: SERVICE_STATUS_PROCESS = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe {
|
||||
QueryServiceStatusEx(
|
||||
service.0,
|
||||
SC_STATUS_PROCESS_INFO,
|
||||
(&mut status as *mut SERVICE_STATUS_PROCESS).cast(),
|
||||
size_of::<SERVICE_STATUS_PROCESS>() as u32,
|
||||
&mut bytes,
|
||||
)
|
||||
} != 0
|
||||
&& status.dwCurrentState == SERVICE_RUNNING
|
||||
&& status.dwProcessId > 0,
|
||||
"EVENT_LOG_AGENT_NOT_RUNNING"
|
||||
);
|
||||
Ok(status.dwProcessId)
|
||||
}
|
||||
fn token_info(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<usize>> {
|
||||
let mut bytes = 0;
|
||||
unsafe {
|
||||
GetTokenInformation(token, class, ptr::null_mut(), 0, &mut bytes);
|
||||
}
|
||||
ensure!((1..=65536).contains(&bytes), "EVENT_LOG_TOKEN_SIZE");
|
||||
let mut data = vec![0usize; (bytes as usize).div_ceil(size_of::<usize>())];
|
||||
ensure!(
|
||||
unsafe { GetTokenInformation(token, class, data.as_mut_ptr().cast(), bytes, &mut bytes) }
|
||||
!= 0,
|
||||
"EVENT_LOG_TOKEN"
|
||||
);
|
||||
Ok(data)
|
||||
}
|
||||
fn service_token(process: HANDLE) -> Result<()> {
|
||||
let mut token = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) } != 0,
|
||||
"EVENT_LOG_TOKEN_OPEN"
|
||||
);
|
||||
let token = owned(token)?;
|
||||
let user = token_info(token.as_raw_handle(), TokenUser)?;
|
||||
let mut service_sid = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe {
|
||||
Security::Authorization::ConvertStringSidToSidW(
|
||||
native::wide(native::service_sid()?).as_ptr(),
|
||||
&mut service_sid,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_SERVICE_SID"
|
||||
);
|
||||
struct Sid(PSID);
|
||||
impl Drop for Sid {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
LocalFree(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let service_sid = Sid(service_sid);
|
||||
let mut ls = [0usize; 16];
|
||||
let mut size = size_of_val(&ls) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinLocalServiceSid,
|
||||
ptr::null_mut(),
|
||||
ls.as_mut_ptr().cast(),
|
||||
&mut size,
|
||||
)
|
||||
} != 0
|
||||
&& unsafe {
|
||||
EqualSid(
|
||||
(*user.as_ptr().cast::<TOKEN_USER>()).User.Sid,
|
||||
ls.as_ptr().cast_mut().cast(),
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_LOCAL_SERVICE_REQUIRED"
|
||||
);
|
||||
let groups = token_info(token.as_raw_handle(), TokenGroups)?;
|
||||
let g = unsafe { &*groups.as_ptr().cast::<TOKEN_GROUPS>() };
|
||||
let offset = std::mem::offset_of!(TOKEN_GROUPS, Groups);
|
||||
ensure!(
|
||||
g.GroupCount <= 1024
|
||||
&& offset + g.GroupCount as usize * size_of::<SID_AND_ATTRIBUTES>()
|
||||
<= groups.len() * size_of::<usize>(),
|
||||
"EVENT_LOG_TOKEN_GROUPS_SIZE"
|
||||
);
|
||||
let entries = unsafe { std::slice::from_raw_parts(g.Groups.as_ptr(), g.GroupCount as usize) };
|
||||
let mut admins = [0usize; 16];
|
||||
let mut admin_bytes = size_of_val(&admins) as u32;
|
||||
ensure!(
|
||||
unsafe {
|
||||
CreateWellKnownSid(
|
||||
WinBuiltinAdministratorsSid,
|
||||
ptr::null_mut(),
|
||||
admins.as_mut_ptr().cast(),
|
||||
&mut admin_bytes,
|
||||
)
|
||||
} != 0,
|
||||
"EVENT_LOG_ADMIN_SID"
|
||||
);
|
||||
ensure!(
|
||||
!entries
|
||||
.iter()
|
||||
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
||||
&& unsafe { EqualSid(entry.Sid, admins.as_ptr().cast_mut().cast()) } != 0),
|
||||
"EVENT_LOG_ADMINISTRATOR_FORBIDDEN"
|
||||
);
|
||||
// TOKEN_GROUPS enabled/deny-only bits from winnt.h, as in the pipe peer proof.
|
||||
ensure!(
|
||||
entries
|
||||
.iter()
|
||||
.any(|entry| entry.Attributes & 0x0000_0004 != 0
|
||||
&& entry.Attributes & 0x0000_0010 == 0
|
||||
&& unsafe { EqualSid(entry.Sid, service_sid.0) } != 0),
|
||||
"EVENT_LOG_AGENT_SID_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn parent_pid() -> Result<u32> {
|
||||
let snapshot = owned(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })?;
|
||||
let mut entry: PROCESSENTRY32W = unsafe { zeroed() };
|
||||
entry.dwSize = size_of::<PROCESSENTRY32W>() as u32;
|
||||
let mut ok = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) };
|
||||
while ok != 0 {
|
||||
if entry.th32ProcessID == std::process::id() {
|
||||
return Ok(entry.th32ParentProcessID);
|
||||
}
|
||||
ok = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) };
|
||||
}
|
||||
anyhow::bail!("EVENT_LOG_PARENT_UNVERIFIED")
|
||||
}
|
||||
fn open_private(path: &Path, share_write: bool) -> Result<File> {
|
||||
ensure!(
|
||||
path.is_absolute() && !path.to_string_lossy().starts_with(r"\\"),
|
||||
"EVENT_LOG_LOCAL_PATH"
|
||||
);
|
||||
for parent in path.ancestors().skip(1) {
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
ensure!(
|
||||
std::fs::symlink_metadata(parent)?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT
|
||||
== 0,
|
||||
"EVENT_LOG_REPARSE_ANCESTOR"
|
||||
);
|
||||
}
|
||||
native::private_path(path, false)?;
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ | if share_write { FILE_SHARE_WRITE } else { 0 })
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
ensure!(
|
||||
file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0,
|
||||
"EVENT_LOG_REPARSE_FILE"
|
||||
);
|
||||
Ok(file)
|
||||
}
|
||||
fn read(file: &mut File, limit: u64) -> Result<Vec<u8>> {
|
||||
ensure!(
|
||||
file.metadata()?.len() <= limit,
|
||||
"EVENT_LOG_PRIVATE_FILE_LIMIT"
|
||||
);
|
||||
let mut value = Vec::new();
|
||||
file.take(limit + 1).read_to_end(&mut value)?;
|
||||
ensure!(value.len() as u64 <= limit, "EVENT_LOG_PRIVATE_FILE_LIMIT");
|
||||
Ok(value)
|
||||
}
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Ticket {
|
||||
request: Request,
|
||||
parent_pid: u32,
|
||||
parent_birth: u64,
|
||||
boot: Uuid,
|
||||
ledger: FileId,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct WorkerConfig {
|
||||
state_directory: PathBuf,
|
||||
job_binding_file: PathBuf,
|
||||
enable_jobs: bool,
|
||||
}
|
||||
fn ticket_name(permit: &ExecutionPermitPayload) -> String {
|
||||
format!("eventlog-{}.json", hash(permit.grant_id.as_bytes()))
|
||||
}
|
||||
/// Prepared data only. No query, worker or Evt handle exists before run.
|
||||
pub struct Prepared {
|
||||
path: PathBuf,
|
||||
_file: File,
|
||||
ticket_hash: String,
|
||||
job_bytes: Vec<u8>,
|
||||
}
|
||||
impl Prepared {
|
||||
pub fn prepare(
|
||||
job: &JobPayload,
|
||||
directory: &Path,
|
||||
request: &Request,
|
||||
grant: Uuid,
|
||||
boot: Uuid,
|
||||
) -> Result<Self> {
|
||||
event_log::for_job(job)?;
|
||||
native::require_local_service()?;
|
||||
service_token(unsafe { GetCurrentProcess() })?;
|
||||
let image = std::env::current_exe()?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == std::process::id(),
|
||||
"EVENT_LOG_REAL_AGENT_REQUIRED"
|
||||
);
|
||||
let permit: ExecutionPermitPayload = serde_json::from_slice(&request.permit_bytes)?;
|
||||
ensure!(
|
||||
permit.grant_id == grant && !boot.is_nil(),
|
||||
"EVENT_LOG_GRANT_BINDING"
|
||||
);
|
||||
native::private_path(directory, true)?;
|
||||
let ledger = open_private(
|
||||
&directory
|
||||
.parent()
|
||||
.context("EVENT_LOG_STATE_DIRECTORY")?
|
||||
.join("consumption.sqlite"),
|
||||
true,
|
||||
)?;
|
||||
let ticket = Ticket {
|
||||
request: request.clone(),
|
||||
parent_pid: std::process::id(),
|
||||
parent_birth: birth(unsafe { GetCurrentProcess() })?,
|
||||
boot,
|
||||
ledger: file_id(ledger.as_raw_handle())?,
|
||||
};
|
||||
let bytes = serde_json::to_vec(&ticket)?;
|
||||
ensure!(bytes.len() as u64 <= TICKET_LIMIT, "EVENT_LOG_TICKET_LIMIT");
|
||||
let path = directory.join(ticket_name(&permit));
|
||||
let mut writer = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.share_mode(0)
|
||||
.open(&path)?;
|
||||
writer.write_all(&bytes)?;
|
||||
writer.sync_all()?;
|
||||
drop(writer);
|
||||
let mut file = open_private(&path, false)?;
|
||||
ensure!(
|
||||
read(&mut file, TICKET_LIMIT)? == bytes,
|
||||
"EVENT_LOG_TICKET_CHANGED"
|
||||
);
|
||||
Ok(Self {
|
||||
path,
|
||||
_file: file,
|
||||
ticket_hash: hash(&bytes),
|
||||
job_bytes: request.job_bytes.clone(),
|
||||
})
|
||||
}
|
||||
pub fn run(self, job: &JobPayload, cancel: &AtomicBool) -> Result<Outcome> {
|
||||
event_log::for_job(job)?;
|
||||
ensure!(
|
||||
serde_json::from_slice::<serde_json::Value>(&self.job_bytes)?
|
||||
== serde_json::to_value(job)?,
|
||||
"EVENT_LOG_JOB_CHANGED"
|
||||
);
|
||||
let mut file = open_private(&self.path, false)?;
|
||||
ensure!(
|
||||
hash(&read(&mut file, TICKET_LIMIT)?) == self.ticket_hash,
|
||||
"EVENT_LOG_TICKET_CHANGED"
|
||||
);
|
||||
let output = crate::process::run(
|
||||
&std::env::current_exe()?,
|
||||
&[MODE.into(), self.path.as_os_str().into()],
|
||||
self.path.parent().context("EVENT_LOG_JOB_DIRECTORY")?,
|
||||
job.max_runtime_seconds,
|
||||
job.max_output_bytes as usize,
|
||||
cancel,
|
||||
)?;
|
||||
if output.interrupted {
|
||||
return Ok(Outcome::unknown(if output.cancelled {
|
||||
"EVENT_LOG_CANCELLED_RESULT_UNKNOWN"
|
||||
} else {
|
||||
"EVENT_LOG_TIMEOUT_RESULT_UNKNOWN"
|
||||
}));
|
||||
}
|
||||
ensure!(
|
||||
output.exit_code == Some(0) && !output.truncated && output.stderr.is_empty(),
|
||||
"EVENT_LOG_WORKER_RESULT_UNVERIFIED"
|
||||
);
|
||||
outcome(job, output.stdout)
|
||||
}
|
||||
}
|
||||
|
||||
fn consumed(
|
||||
db: &rusqlite::Connection,
|
||||
binding: &Binding,
|
||||
ticket: &Ticket,
|
||||
permit: &ExecutionPermitPayload,
|
||||
) -> Result<()> {
|
||||
let length: u64 = db.query_row("SELECT length(e.start) FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1", [permit.grant_id.to_string()], |r| r.get(0))?;
|
||||
ensure!(length <= TICKET_LIMIT, "EVENT_LOG_START_SIZE");
|
||||
type Row = (String, u64, String, String, bool, Vec<u8>, bool);
|
||||
let row: Row = db.query_row("SELECT c.agent,c.generation,c.job,c.attempt,c.result IS NULL,e.start,e.outcome IS NULL FROM consumed c JOIN execution_evidence e USING(grant_id) WHERE c.grant_id=?1",
|
||||
[permit.grant_id.to_string()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?)))?;
|
||||
ensure!(
|
||||
row.0 == binding.agent_id.to_string()
|
||||
&& row.1 == binding.enrollment_generation
|
||||
&& row.2 == permit.job_id.to_string()
|
||||
&& row.3 == permit.attempt_id.to_string()
|
||||
&& row.4
|
||||
&& row.6,
|
||||
"EVENT_LOG_CONSUMPTION_BINDING"
|
||||
);
|
||||
let start: serde_json::Value = serde_json::from_slice(&row.5)?;
|
||||
ensure!(
|
||||
start["previous_boot_id"] == ticket.boot.to_string()
|
||||
&& serde_json::to_vec(&serde_json::from_value::<Request>(
|
||||
start["request"].clone()
|
||||
)?)? == serde_json::to_vec(&ticket.request)?,
|
||||
"EVENT_LOG_ORIGINAL_START_BINDING"
|
||||
);
|
||||
let identity: String = db.query_row(
|
||||
"SELECT identity FROM windows_binding WHERE length(identity)<=512",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
identity
|
||||
== format!(
|
||||
"{}:{}:{}:{}:{}",
|
||||
binding.tenant_id,
|
||||
binding.asset_id,
|
||||
binding.agent_id,
|
||||
binding.enrollment_generation,
|
||||
binding.assignment_version
|
||||
),
|
||||
"EVENT_LOG_LEDGER_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn validate_ticket_path(path: &Path, directory: &Path) -> Result<()> {
|
||||
let name = path
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.context("EVENT_LOG_TICKET_NAME")?;
|
||||
let hash_name = name
|
||||
.strip_prefix("eventlog-")
|
||||
.and_then(|s| s.strip_suffix(".json"))
|
||||
.context("EVENT_LOG_TICKET_NAME")?;
|
||||
ensure!(
|
||||
path.parent() == Some(directory)
|
||||
&& hash_name.len() == 64
|
||||
&& hash_name
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)),
|
||||
"EVENT_LOG_TICKET_PATH_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Internal mode admission. Failure emits only the main executable's fixed
|
||||
/// initialization error; no request, query XML or private Win32 error is logged.
|
||||
pub fn worker(path: &Path) -> Result<()> {
|
||||
native::require_local_service()?;
|
||||
service_token(unsafe { GetCurrentProcess() })?;
|
||||
let image = std::env::current_exe()?;
|
||||
let actual_parent = parent_pid()?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == actual_parent,
|
||||
"EVENT_LOG_REAL_PARENT_REQUIRED"
|
||||
);
|
||||
let parent = owned(unsafe {
|
||||
OpenProcess(
|
||||
PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE,
|
||||
0,
|
||||
actual_parent,
|
||||
)
|
||||
})?;
|
||||
let parent_birth = birth(parent.as_raw_handle())?;
|
||||
ensure!(
|
||||
process_image(parent.as_raw_handle())? == image
|
||||
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
||||
"EVENT_LOG_PARENT_INSTANCE"
|
||||
);
|
||||
service_token(parent.as_raw_handle())?;
|
||||
crate::job_binding::check_admin_readonly(Path::new(CONFIG))?;
|
||||
let mut config_file = open_private(Path::new(CONFIG), false)?;
|
||||
let config: WorkerConfig = serde_json::from_slice(&read(&mut config_file, 32768)?)?;
|
||||
ensure!(
|
||||
config.enable_jobs && config.state_directory.is_absolute(),
|
||||
"EVENT_LOG_JOBS_NOT_ENABLED"
|
||||
);
|
||||
let directory = config.state_directory.join("jobs");
|
||||
native::private_path(&directory, true)?;
|
||||
validate_ticket_path(path, &directory)?;
|
||||
// Only the exact jobs leaf is read; PKI/keys and arbitrary private files
|
||||
// cannot be passed to this mode, even by another LocalService process.
|
||||
let mut ticket_file = open_private(path, false)?;
|
||||
let ticket: Ticket = serde_json::from_slice(&read(&mut ticket_file, TICKET_LIMIT)?)?;
|
||||
ensure!(
|
||||
ticket.parent_pid == actual_parent && ticket.parent_birth == parent_birth,
|
||||
"EVENT_LOG_PARENT_INSTANCE"
|
||||
);
|
||||
let binding = crate::job_binding::readonly_binding(&config.job_binding_file)?;
|
||||
let clock = crate::clock::NativeClock::new();
|
||||
let now = clock.now()?;
|
||||
let (job, permit) = binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
||||
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
||||
let query = event_log::for_job(&job)?;
|
||||
let expected = config
|
||||
.state_directory
|
||||
.join("jobs")
|
||||
.join(ticket_name(&permit));
|
||||
ensure!(path == expected, "EVENT_LOG_TICKET_PATH_BINDING");
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
ensure!(
|
||||
Uuid::parse_str(&runtime.block_on(native::boot_id())?)? == ticket.boot,
|
||||
"EVENT_LOG_ORIGINAL_BOOT_REQUIRED"
|
||||
);
|
||||
let ledger_path = config.state_directory.join("consumption.sqlite");
|
||||
let ledger_file = open_private(&ledger_path, true)?;
|
||||
ensure!(
|
||||
file_id(ledger_file.as_raw_handle())? == ticket.ledger,
|
||||
"EVENT_LOG_LEDGER_FILE_CHANGED"
|
||||
);
|
||||
let db = rusqlite::Connection::open_with_flags(
|
||||
&ledger_path,
|
||||
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)?;
|
||||
db.busy_timeout(Duration::from_millis(100))?;
|
||||
let mut sqlite_handle: HANDLE = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe {
|
||||
rusqlite::ffi::sqlite3_file_control(
|
||||
db.handle(),
|
||||
c"main".as_ptr(),
|
||||
rusqlite::ffi::SQLITE_FCNTL_WIN32_GET_HANDLE,
|
||||
(&mut sqlite_handle as *mut HANDLE).cast(),
|
||||
)
|
||||
} == rusqlite::ffi::SQLITE_OK
|
||||
&& file_id(sqlite_handle)? == ticket.ledger,
|
||||
"EVENT_LOG_CONNECTED_LEDGER_FILE"
|
||||
);
|
||||
db.execute_batch("PRAGMA query_only=ON; BEGIN;")?;
|
||||
consumed(&db, &binding, &ticket, &permit)?;
|
||||
// Per-grant durable CAS prevents worker re-entry after a lost child reply.
|
||||
let marker = path.with_extension("started");
|
||||
let mut once = OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.share_mode(0)
|
||||
.open(&marker)?;
|
||||
once.write_all(b"event-log-dispatch-v1\n")?;
|
||||
once.sync_all()?;
|
||||
native::private_path(&marker, false)?;
|
||||
// File I/O, CIM and child scheduling cannot extend the signed start window.
|
||||
let now = clock.now()?;
|
||||
binding.verify(&ticket.request, now - chrono::Duration::seconds(2))?;
|
||||
binding.verify(&ticket.request, now + chrono::Duration::seconds(2))?;
|
||||
ensure!(
|
||||
agent_pid(&image)? == actual_parent
|
||||
&& birth(parent.as_raw_handle())? == ticket.parent_birth
|
||||
&& unsafe { WaitForSingleObject(parent.as_raw_handle(), 0) } == WAIT_TIMEOUT,
|
||||
"EVENT_LOG_PARENT_CHANGED"
|
||||
);
|
||||
consumed(&db, &binding, &ticket, &permit)?;
|
||||
let report = event_log::query(&query, &AtomicBool::new(false))?;
|
||||
let bytes = serde_json::to_vec(&report)?;
|
||||
ensure!(
|
||||
bytes.len() <= job.max_output_bytes as usize,
|
||||
"EVENT_LOG_OUTPUT_LIMIT"
|
||||
);
|
||||
std::io::stdout().lock().write_all(&bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WireReport {
|
||||
channel: String,
|
||||
provider: String,
|
||||
start_utc: DateTime<Utc>,
|
||||
end_utc: DateTime<Utc>,
|
||||
quality: String,
|
||||
completeness: String,
|
||||
truncated: bool,
|
||||
error_code: Option<String>,
|
||||
win32_error: Option<u32>,
|
||||
events: Vec<event_log::Event>,
|
||||
bookmark_updated: bool,
|
||||
deadline_enforcement: String,
|
||||
}
|
||||
fn outcome(job: &JobPayload, bytes: Vec<u8>) -> Result<Outcome> {
|
||||
let q = event_log::for_job(job)?;
|
||||
ensure!(
|
||||
bytes.len() <= q.max_output_bytes as usize,
|
||||
"EVENT_LOG_OUTPUT_LIMIT"
|
||||
);
|
||||
let report: WireReport = serde_json::from_slice(&bytes)?;
|
||||
ensure!(
|
||||
report.channel == q.channel
|
||||
&& report.provider == q.provider
|
||||
&& report.start_utc == q.start_utc
|
||||
&& report.end_utc == q.end_utc
|
||||
&& !report.bookmark_updated
|
||||
&& report.events.len() <= q.max_events as usize
|
||||
&& report.deadline_enforcement == "cooperative_between_win32_calls",
|
||||
"EVENT_LOG_REPORT_BINDING"
|
||||
);
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for event in &report.events {
|
||||
ensure!(
|
||||
event.channel == q.channel
|
||||
&& event.provider == q.provider
|
||||
&& event.record_id > 0
|
||||
&& ids.insert(event.record_id)
|
||||
&& event.created_utc >= q.start_utc
|
||||
&& event.created_utc < q.end_utc
|
||||
&& event.xml.len() <= 64 * 1024
|
||||
&& !event.xml.contains('\0'),
|
||||
"EVENT_LOG_EVENT_BINDING"
|
||||
);
|
||||
}
|
||||
let complete =
|
||||
report.completeness == "complete" && !report.truncated && report.error_code.is_none();
|
||||
let partial = report.completeness == "partial"
|
||||
&& report.truncated
|
||||
&& matches!(
|
||||
report.error_code.as_deref(),
|
||||
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
|
||||
);
|
||||
let success =
|
||||
report.quality == "valid" && report.win32_error.is_none() && (complete || partial);
|
||||
let error =
|
||||
report
|
||||
.error_code
|
||||
.as_deref()
|
||||
.unwrap_or(if success { "" } else { "EVENT_LOG_INCOMPLETE" });
|
||||
Ok(Outcome {
|
||||
state: if success { "succeeded" } else { "failed" }.into(),
|
||||
stdout: bytes,
|
||||
stderr: vec![],
|
||||
exit_code: None,
|
||||
output_truncated: report.truncated,
|
||||
reboot_required: false,
|
||||
error_code: if success { String::new() } else { error.into() },
|
||||
evidence: serde_json::json!({"postconditions_passed":success,
|
||||
"source_id":rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE,
|
||||
"channel":q.channel,"provider":q.provider,"start_utc":q.start_utc,"end_utc":q.end_utc,
|
||||
"max_events":q.max_events,"max_output_bytes":q.max_output_bytes,
|
||||
"quality":report.quality,"completeness":report.completeness,"truncated":report.truncated,
|
||||
"error_code":report.error_code,"win32_error":report.win32_error,
|
||||
"bookmark_updated":false,"execution_sid":"S-1-5-19","process_tree_bounded":true,
|
||||
"cursor_status":"not_advanced_no_ack_contract","observed_at":Utc::now()}),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn job() -> JobPayload {
|
||||
let id = Uuid::new_v4();
|
||||
let now = DateTime::from_timestamp(1_700_000_000, 0).unwrap();
|
||||
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::QueryLogs {
|
||||
unit: rmm_domain::jobs::WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now,
|
||||
until: now + chrono::Duration::minutes(5),
|
||||
max_lines: 2,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::seconds(60),
|
||||
max_runtime_seconds: 10,
|
||||
max_output_bytes: 4096,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves() {
|
||||
let directory = Path::new(r"C:\ProgramData\RustDiscovery\state\jobs");
|
||||
let leaf = format!("eventlog-{}.json", "a".repeat(64));
|
||||
assert!(validate_ticket_path(&directory.join(&leaf), directory).is_ok());
|
||||
for path in [
|
||||
PathBuf::from(r"C:\ProgramData\RustDiscovery\state\device-key.pem"),
|
||||
directory.join("..\\jobs").join(&leaf),
|
||||
directory.join(format!("eventlog-{}.json", "A".repeat(64))),
|
||||
directory.join(format!("eventlog-{}.json", "a".repeat(63))),
|
||||
directory.join(format!("eventlog-{}.json:stream", "a".repeat(64))),
|
||||
directory.join("other.json"),
|
||||
] {
|
||||
assert!(
|
||||
validate_ticket_path(&path, directory).is_err(),
|
||||
"{}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success() {
|
||||
let job = job();
|
||||
let q = event_log::for_job(&job).unwrap();
|
||||
let mut report = serde_json::json!({"channel":q.channel,"provider":q.provider,
|
||||
"start_utc":q.start_utc,"end_utc":q.end_utc,"quality":"valid",
|
||||
"completeness":"complete","truncated":false,"error_code":null,"win32_error":null,
|
||||
"events":[],"bookmark_updated":false,"deadline_enforcement":"cooperative_between_win32_calls"});
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&report).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"succeeded"
|
||||
);
|
||||
for code in [
|
||||
"EVENT_LOG_TIME_LIMIT",
|
||||
"EVENT_LOG_CANCELLED",
|
||||
"EVENT_LOG_API_ERROR",
|
||||
] {
|
||||
let mut partial = report.clone();
|
||||
partial["truncated"] = true.into();
|
||||
partial["completeness"] = "unknown".into();
|
||||
partial["error_code"] = code.into();
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&partial).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"failed"
|
||||
);
|
||||
}
|
||||
report["truncated"] = true.into();
|
||||
report["completeness"] = "partial".into();
|
||||
report["error_code"] = "EVENT_LOG_BYTE_LIMIT".into();
|
||||
let bounded = outcome(&job, serde_json::to_vec(&report).unwrap()).unwrap();
|
||||
assert_eq!(bounded.state, "succeeded");
|
||||
assert!(bounded.output_truncated);
|
||||
report["quality"] = "permission_denied".into();
|
||||
report["win32_error"] = 5.into();
|
||||
assert_eq!(
|
||||
outcome(&job, serde_json::to_vec(&report).unwrap())
|
||||
.unwrap()
|
||||
.state,
|
||||
"failed"
|
||||
);
|
||||
report["provider"] = "another-provider".into();
|
||||
assert!(outcome(&job, serde_json::to_vec(&report).unwrap()).is_err());
|
||||
}
|
||||
}
|
||||
@@ -16,16 +16,67 @@ pub const ROOT: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents";
|
||||
pub const DB: &str = r"C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite";
|
||||
const ACTOR_RW: u32 = 0x0012_019f;
|
||||
const SCHEMA:&str="CREATE TABLE IF NOT EXISTS system_intent_meta(id INTEGER PRIMARY KEY CHECK(id=1),file_identity BLOB NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1)),UNIQUE(job,attempt));
|
||||
CREATE TABLE IF NOT EXISTS system_intent_mirrors(id TEXT PRIMARY KEY,outcome_sha256 TEXT NOT NULL,mirror_observed_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS system_intent_denial_resumes(id TEXT NOT NULL,agent_instance TEXT NOT NULL,observed_at TEXT NOT NULL,PRIMARY KEY(id,agent_instance));
|
||||
CREATE TRIGGER IF NOT EXISTS system_intents_no_delete BEFORE DELETE ON system_intents BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR NOT ((NEW.phase=OLD.phase AND NEW.cancel_requested=1 AND OLD.cancel_requested IN (0,1)) OR (OLD.phase='prepared' AND NEW.phase IN ('known_no_dispatch','may_have_dispatched') AND NEW.cancel_requested=OLD.cancel_requested)) BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_delete BEFORE DELETE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_mirrors_no_update BEFORE UPDATE ON system_intent_mirrors BEGIN SELECT RAISE(ABORT,'SYSTEM_MIRROR_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_delete BEFORE DELETE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;
|
||||
CREATE TRIGGER IF NOT EXISTS system_denial_resumes_no_update BEFORE UPDATE ON system_intent_denial_resumes BEGIN SELECT RAISE(ABORT,'SYSTEM_DENIAL_RESUME_IMMUTABLE');END;";
|
||||
const LEGACY_INTENTS_TABLE: &str = "CREATE TABLE IF NOT EXISTS system_intents(id TEXT PRIMARY KEY,job TEXT NOT NULL,attempt TEXT NOT NULL,grant_id TEXT NOT NULL UNIQUE,body BLOB NOT NULL CHECK(length(body)<=196608),digest TEXT NOT NULL,phase TEXT NOT NULL CHECK(phase IN ('prepared','known_no_dispatch','may_have_dispatched')),UNIQUE(job,attempt));";
|
||||
const LEGACY_MONOTONIC: &str = "CREATE TRIGGER IF NOT EXISTS system_intents_monotonic BEFORE UPDATE ON system_intents WHEN NEW.id!=OLD.id OR NEW.job!=OLD.job OR NEW.attempt!=OLD.attempt OR NEW.grant_id!=OLD.grant_id OR NEW.body!=OLD.body OR NEW.digest!=OLD.digest OR OLD.phase!='prepared' OR NEW.phase NOT IN ('known_no_dispatch','may_have_dispatched') BEGIN SELECT RAISE(ABORT,'SYSTEM_INTENT_IMMUTABLE');END;";
|
||||
const CLAIM_RESUME: &str = "INSERT OR IGNORE INTO system_intent_denial_resumes(id,agent_instance,observed_at) VALUES(?1,?2,?3)";
|
||||
fn initialize_schema(db: &mut Connection) -> Result<()> {
|
||||
let exists: bool = db.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='system_intents')",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
if exists {
|
||||
let columns = db
|
||||
.prepare("PRAGMA table_info(system_intents)")?
|
||||
.query_map([], |r| r.get::<_, String>(1))?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
if !columns.iter().any(|name| name == "cancel_requested") {
|
||||
ensure!(
|
||||
columns
|
||||
== [
|
||||
"id", "job", "attempt", "grant_id", "body", "digest", "phase"
|
||||
],
|
||||
"SYSTEM_INTENT_LEGACY_SCHEMA"
|
||||
);
|
||||
let old:String=db.query_row("SELECT sql FROM sqlite_master WHERE type='trigger' AND name='system_intents_monotonic'",[],|r|r.get(0))?;
|
||||
let normalize = |s: &str| {
|
||||
s.replace("IF NOT EXISTS ", "")
|
||||
.trim_end_matches(';')
|
||||
.split_whitespace()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
};
|
||||
ensure!(
|
||||
normalize(&old) == normalize(LEGACY_MONOTONIC),
|
||||
"SYSTEM_INTENT_LEGACY_TRIGGER"
|
||||
);
|
||||
let table: String = db.query_row(
|
||||
"SELECT sql FROM sqlite_master WHERE type='table' AND name='system_intents'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(
|
||||
normalize(&table) == normalize(LEGACY_INTENTS_TABLE),
|
||||
"SYSTEM_INTENT_LEGACY_SCHEMA"
|
||||
);
|
||||
let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
tx.execute_batch("ALTER TABLE system_intents ADD COLUMN cancel_requested INTEGER NOT NULL DEFAULT 0 CHECK(cancel_requested IN (0,1));DROP TRIGGER system_intents_monotonic;")?;
|
||||
tx.execute_batch(SCHEMA)?;
|
||||
tx.commit()?;
|
||||
}
|
||||
}
|
||||
db.execute_batch(SCHEMA)?;
|
||||
Ok(())
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Intent {
|
||||
@@ -148,14 +199,14 @@ impl Store {
|
||||
} else {
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY
|
||||
};
|
||||
let db = Connection::open_with_flags(DB, flags)?;
|
||||
let mut db = Connection::open_with_flags(DB, flags)?;
|
||||
db.busy_timeout(Duration::from_millis(250))?;
|
||||
if write {
|
||||
rmm_agent_core::ledger::bounded_journal_capacity(&db)?;
|
||||
let mode: String = db.query_row("PRAGMA journal_mode=PERSIST", [], |r| r.get(0))?;
|
||||
ensure!(mode == "persist", "SYSTEM_INTENT_JOURNAL_MODE");
|
||||
db.execute_batch("PRAGMA synchronous=FULL;PRAGMA temp_store=MEMORY;PRAGMA journal_size_limit=1048576;")?;
|
||||
db.execute_batch(SCHEMA)?;
|
||||
initialize_schema(&mut db)?;
|
||||
db.execute(
|
||||
"INSERT OR IGNORE INTO system_intent_meta VALUES(1,?1)",
|
||||
[serde_json::to_vec(&identity)?],
|
||||
@@ -241,10 +292,60 @@ impl Store {
|
||||
}
|
||||
pub fn cancel_before_dispatch(&mut self, id: Uuid) -> Result<Phase> {
|
||||
self.check()?;
|
||||
self.db.execute(
|
||||
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
|
||||
[id.to_string()],
|
||||
)?;
|
||||
let (_, phase) = advance(&mut self.db, id, Phase::KnownNoDispatch)?;
|
||||
self.check()?;
|
||||
Ok(phase)
|
||||
}
|
||||
/// Denial only. Original phase/request/anchor never changes, even after IPC.
|
||||
pub fn deny(&mut self, original: &Request, boot: Uuid) -> Result<()> {
|
||||
self.check()?;
|
||||
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
|
||||
let intent = self.by_grant(permit.grant_id)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
|
||||
&& intent.original_boot_id == boot,
|
||||
"SYSTEM_CANCEL_ORIGINAL_BINDING"
|
||||
);
|
||||
self.db.execute(
|
||||
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
|
||||
[intent.id.to_string()],
|
||||
)?;
|
||||
self.check()
|
||||
}
|
||||
/// Open a new ordinary RO connection for each observation. No long-lived
|
||||
/// SQLite read transaction or immutable-mode shortcut may hide actor denial.
|
||||
pub fn require_not_denied(
|
||||
original: &Request,
|
||||
boot: Uuid,
|
||||
generation: u64,
|
||||
policy: &str,
|
||||
binary: &str,
|
||||
) -> Result<()> {
|
||||
let mut store = Self::open(false)?;
|
||||
let permit: ExecutionPermitPayload = serde_json::from_slice(&original.permit_bytes)?;
|
||||
let intent = store.by_grant(permit.grant_id)?;
|
||||
let (_, phase) = store.load(intent.id)?;
|
||||
ensure!(
|
||||
serde_json::to_vec(&intent.request)? == serde_json::to_vec(original)?
|
||||
&& intent.original_boot_id == boot
|
||||
&& intent.connection_generation == generation
|
||||
&& phase == Phase::MayHaveDispatched
|
||||
&& intent.policy_sha256 == policy
|
||||
&& intent.helper_binary_sha256 == binary,
|
||||
"SYSTEM_CANCEL_ORIGINAL_BINDING"
|
||||
);
|
||||
let denied: i64 = store.db.query_row(
|
||||
"SELECT cancel_requested FROM system_intents WHERE id=?1",
|
||||
[intent.id.to_string()],
|
||||
|r| r.get(0),
|
||||
)?;
|
||||
ensure!(denied == 0, "SYSTEM_MSI_CANCELLED_OR_FENCED");
|
||||
store.check()
|
||||
}
|
||||
pub fn pending(&self) -> Result<Vec<Intent>> {
|
||||
let mut rows=self.db.prepare("SELECT i.id FROM system_intents i WHERE NOT EXISTS(SELECT 1 FROM system_intent_mirrors m WHERE m.id=i.id) ORDER BY i.rowid LIMIT 2")?;
|
||||
let ids = rows
|
||||
@@ -356,7 +457,7 @@ mod tests {
|
||||
let dispatched = Uuid::new_v4();
|
||||
for id in [cancelled, dispatched] {
|
||||
db.execute(
|
||||
"INSERT INTO system_intents VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
|
||||
"INSERT INTO system_intents(id,job,attempt,grant_id,body,digest,phase) VALUES(?1,?1,?1,?1,x'01','immutable','prepared')",
|
||||
[id.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -377,6 +478,29 @@ mod tests {
|
||||
advance(&mut db, dispatched, Phase::KnownNoDispatch).unwrap(),
|
||||
(0, Phase::MayHaveDispatched)
|
||||
);
|
||||
for _ in 0..2 {
|
||||
db.execute(
|
||||
"UPDATE system_intents SET cancel_requested=1 WHERE id=?1",
|
||||
[dispatched.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
db.query_row(
|
||||
"SELECT phase,cancel_requested FROM system_intents WHERE id=?1",
|
||||
[dispatched.to_string()],
|
||||
|r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?))
|
||||
)
|
||||
.unwrap(),
|
||||
("may_have_dispatched".into(), 1)
|
||||
);
|
||||
assert!(
|
||||
db.execute(
|
||||
"UPDATE system_intents SET cancel_requested=0 WHERE id=?1",
|
||||
[dispatched.to_string()]
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
db.execute(
|
||||
"UPDATE system_intents SET phase='prepared' WHERE id=?1",
|
||||
@@ -411,4 +535,45 @@ mod tests {
|
||||
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 1);
|
||||
assert_eq!(db.execute(CLAIM_RESUME, args).unwrap(), 0);
|
||||
}
|
||||
#[test]
|
||||
fn additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger() {
|
||||
let mut db = Connection::open_in_memory().unwrap();
|
||||
db.execute_batch(LEGACY_INTENTS_TABLE).unwrap();
|
||||
db.execute_batch(LEGACY_MONOTONIC).unwrap();
|
||||
db.execute("INSERT INTO system_intents VALUES('id','job','attempt','grant',x'0102','original','may_have_dispatched')",[]).unwrap();
|
||||
initialize_schema(&mut db).unwrap();
|
||||
initialize_schema(&mut db).unwrap();
|
||||
assert_eq!(
|
||||
db.query_row(
|
||||
"SELECT body,digest,phase,cancel_requested FROM system_intents",
|
||||
[],
|
||||
|r| Ok((
|
||||
r.get::<_, Vec<u8>>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
r.get::<_, i64>(3)?
|
||||
))
|
||||
)
|
||||
.unwrap(),
|
||||
(
|
||||
vec![1, 2],
|
||||
"original".into(),
|
||||
"may_have_dispatched".into(),
|
||||
0
|
||||
)
|
||||
);
|
||||
db.execute("UPDATE system_intents SET cancel_requested=1", [])
|
||||
.unwrap();
|
||||
assert!(
|
||||
db.execute("UPDATE system_intents SET body=x'03'", [])
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
db.execute("UPDATE system_intents SET cancel_requested=0", [])
|
||||
.is_err()
|
||||
);
|
||||
let mut foreign = Connection::open_in_memory().unwrap();
|
||||
foreign.execute_batch("CREATE TABLE system_intents(id,job,attempt,grant_id,body,digest,phase);CREATE TRIGGER system_intents_monotonic BEFORE UPDATE ON system_intents BEGIN SELECT 1;END;").unwrap();
|
||||
assert!(initialize_schema(&mut foreign).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ use rmm_agent_core::{
|
||||
};
|
||||
use rmm_domain::jobs::hash;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
ffi::c_void,
|
||||
fs::File,
|
||||
@@ -29,7 +30,13 @@ use windows_sys::Win32::{
|
||||
};
|
||||
|
||||
pub const HELPER_SERVICE: &str = "RmmDiscoverySystemHelper";
|
||||
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v1";
|
||||
// Framing v2 is deliberately a separate endpoint. Old peers cannot send a
|
||||
// v1 call to this server or interpret the drain receipt as another reply.
|
||||
pub const PIPE_NAME: &str = r"\\.\pipe\RustDiscovery-System-v2";
|
||||
const FRAME_TAG: [u8; 8] = *b"RDPIPC02";
|
||||
const DRAIN_TAG: [u8; 8] = *b"RDPACK02";
|
||||
const FRAME_HEADER_LEN: usize = 12;
|
||||
const DRAIN_RECEIPT_LEN: usize = 56;
|
||||
pub const FRAME_LIMIT: usize = 1024 * 1024;
|
||||
pub const CLIENT_PIPE_RIGHTS: u32 = 0x0012_0083; // data R/W, attributes R, RC, synchronize; no bit4
|
||||
const READ_MASK: u32 = 0x0012_00a9;
|
||||
@@ -44,6 +51,7 @@ pub enum Stage {
|
||||
ClientSendFrame,
|
||||
ClientReadReply,
|
||||
ClientReplyBinding,
|
||||
ClientDrainReceipt,
|
||||
ClientReport,
|
||||
ServerConnect,
|
||||
ServerReadHeader,
|
||||
@@ -54,6 +62,7 @@ pub enum Stage {
|
||||
ServerCallBinding,
|
||||
ServerRecheckPeer,
|
||||
ServerReply,
|
||||
ServerDrainReceipt,
|
||||
Unclassified,
|
||||
}
|
||||
impl Stage {
|
||||
@@ -66,6 +75,7 @@ impl Stage {
|
||||
Self::ClientSendFrame => "client_send_frame",
|
||||
Self::ClientReadReply => "client_read_reply",
|
||||
Self::ClientReplyBinding => "client_reply_binding",
|
||||
Self::ClientDrainReceipt => "client_drain_receipt",
|
||||
Self::ClientReport => "client_report",
|
||||
Self::ServerConnect => "server_connect",
|
||||
Self::ServerReadHeader => "server_read_header",
|
||||
@@ -76,6 +86,7 @@ impl Stage {
|
||||
Self::ServerCallBinding => "server_call_binding",
|
||||
Self::ServerRecheckPeer => "server_recheck_peer",
|
||||
Self::ServerReply => "server_reply",
|
||||
Self::ServerDrainReceipt => "server_drain_receipt",
|
||||
Self::Unclassified => "unclassified",
|
||||
}
|
||||
}
|
||||
@@ -123,6 +134,8 @@ fn known_code(text: &str) -> Option<&'static str> {
|
||||
"HELPER_FRAME_CAPACITY",
|
||||
"HELPER_FRAME_EMPTY",
|
||||
"HELPER_FRAME_LENGTH",
|
||||
"HELPER_FRAME_VERSION",
|
||||
"HELPER_DRAIN_RECEIPT",
|
||||
"HELPER_HANDLE",
|
||||
"HELPER_IMAGE_PARENT",
|
||||
"HELPER_IMAGE_SIZE",
|
||||
@@ -1189,27 +1202,60 @@ fn encode(value: &impl Serialize) -> Result<Vec<u8>> {
|
||||
ensure!(!writer.0.is_empty(), "HELPER_FRAME_EMPTY");
|
||||
Ok(writer.0)
|
||||
}
|
||||
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
|
||||
let mut bytes = encode(value)?;
|
||||
let mut header = u32::try_from(bytes.len())?.to_be_bytes();
|
||||
transfer(pipe, &mut header, true, deadline)?;
|
||||
transfer(pipe, &mut bytes, true, deadline)
|
||||
fn frame_header(len: usize) -> Result<[u8; FRAME_HEADER_LEN]> {
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
let mut header = [0; FRAME_HEADER_LEN];
|
||||
header[..8].copy_from_slice(&FRAME_TAG);
|
||||
header[8..].copy_from_slice(&u32::try_from(len)?.to_be_bytes());
|
||||
Ok(header)
|
||||
}
|
||||
fn frame_length(header: [u8; 4]) -> Result<usize> {
|
||||
let len = u32::from_be_bytes(header) as usize;
|
||||
fn send_bytes(pipe: HANDLE, bytes: &mut [u8], deadline: Instant) -> Result<()> {
|
||||
let mut header = frame_header(bytes.len())?;
|
||||
transfer(pipe, &mut header, true, deadline)?;
|
||||
transfer(pipe, bytes, true, deadline)
|
||||
}
|
||||
fn send(pipe: HANDLE, value: &impl Serialize, deadline: Instant) -> Result<()> {
|
||||
send_bytes(pipe, &mut encode(value)?, deadline)
|
||||
}
|
||||
fn frame_length(header: [u8; FRAME_HEADER_LEN]) -> Result<usize> {
|
||||
ensure!(header[..8] == FRAME_TAG, "HELPER_FRAME_VERSION");
|
||||
let len = u32::from_be_bytes(header[8..].try_into()?) as usize;
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
Ok(len)
|
||||
}
|
||||
fn length(pipe: HANDLE, deadline: Instant) -> Result<usize> {
|
||||
let mut header = [0u8; 4];
|
||||
let mut header = [0u8; FRAME_HEADER_LEN];
|
||||
transfer(pipe, &mut header, false, deadline)?;
|
||||
frame_length(header)
|
||||
}
|
||||
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
|
||||
fn body_bytes(pipe: HANDLE, len: usize, deadline: Instant) -> Result<Vec<u8>> {
|
||||
ensure!((1..=FRAME_LIMIT).contains(&len), "HELPER_FRAME_LENGTH");
|
||||
let mut bytes = vec![0u8; len];
|
||||
transfer(pipe, &mut bytes, false, deadline)?;
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
Ok(bytes)
|
||||
}
|
||||
fn body<T: DeserializeOwned>(pipe: HANDLE, len: usize, deadline: Instant) -> Result<T> {
|
||||
Ok(serde_json::from_slice(&body_bytes(pipe, len, deadline)?)?)
|
||||
}
|
||||
// This fixed-size receipt only acknowledges receipt of these transport bytes.
|
||||
// It never acknowledges durable evidence, clears state, or permits an effect.
|
||||
fn drain_receipt(challenge: Uuid, reply_bytes: &[u8]) -> [u8; DRAIN_RECEIPT_LEN] {
|
||||
let mut receipt = [0; DRAIN_RECEIPT_LEN];
|
||||
receipt[..8].copy_from_slice(&DRAIN_TAG);
|
||||
receipt[8..24].copy_from_slice(challenge.as_bytes());
|
||||
receipt[24..].copy_from_slice(&Sha256::digest(reply_bytes));
|
||||
receipt
|
||||
}
|
||||
fn verify_drain_receipt(
|
||||
receipt: &[u8; DRAIN_RECEIPT_LEN],
|
||||
challenge: Uuid,
|
||||
reply_bytes: &[u8],
|
||||
) -> Result<()> {
|
||||
ensure!(
|
||||
*receipt == drain_receipt(challenge, reply_bytes),
|
||||
"HELPER_DRAIN_RECEIPT"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct Server {
|
||||
@@ -1305,13 +1351,24 @@ impl Server {
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
Ok(Some(Received { call, peer }))
|
||||
}
|
||||
pub fn reply(&self, value: &Reply) -> Result<()> {
|
||||
send(
|
||||
self.pipe.as_raw_handle(),
|
||||
value,
|
||||
Instant::now() + Duration::from_secs(5),
|
||||
)
|
||||
.context(Stage::ServerReply)
|
||||
pub fn reply(&self, value: &Reply, peer: &mut PeerProof) -> Result<()> {
|
||||
// Do not disconnect after WriteFile merely copied bytes into a pipe
|
||||
// buffer. Wait for a receipt from the same fully pinned peer within
|
||||
// the original reply deadline, without an unbounded FlushFileBuffers.
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
let mut bytes = encode(value).context(Stage::ServerReply)?;
|
||||
send_bytes(self.pipe.as_raw_handle(), &mut bytes, deadline).context(Stage::ServerReply)?;
|
||||
let mut receipt = [0; DRAIN_RECEIPT_LEN];
|
||||
transfer(self.pipe.as_raw_handle(), &mut receipt, false, deadline)
|
||||
.context(Stage::ServerDrainReceipt)?;
|
||||
verify_drain_receipt(&receipt, value.challenge, &bytes)
|
||||
.context(Stage::ServerDrainReceipt)?;
|
||||
peer.check().context(Stage::ServerRecheckPeer)?;
|
||||
if Instant::now() >= deadline {
|
||||
return Err(anyhow::anyhow!("HELPER_PIPE_TIMEOUT")).context(Stage::ServerDrainReceipt);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn disconnect(&self) {
|
||||
unsafe {
|
||||
@@ -1345,7 +1402,9 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
|
||||
.context(Stage::ClientHelperPeer)?;
|
||||
send(pipe.as_raw_handle(), call, deadline).context(Stage::ClientSendFrame)?;
|
||||
let len = length(pipe.as_raw_handle(), deadline).context(Stage::ClientReadReply)?;
|
||||
let reply: Reply = body(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
|
||||
let reply_bytes =
|
||||
body_bytes(pipe.as_raw_handle(), len, deadline).context(Stage::ClientReadReply)?;
|
||||
let reply: Reply = serde_json::from_slice(&reply_bytes).context(Stage::ClientReadReply)?;
|
||||
peer.check().context(Stage::ClientHelperPeer)?;
|
||||
if !(reply.schema_version == 1
|
||||
&& reply.challenge == call.challenge
|
||||
@@ -1366,6 +1425,11 @@ pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
|
||||
) {
|
||||
return Err(anyhow::anyhow!("HELPER_REPLY_OPERATION")).context(Stage::ClientReplyBinding);
|
||||
}
|
||||
// Only a complete, authenticated, bound and operation-checked reply gets
|
||||
// this receipt. Hash the received bytes, never a JSON re-serialization.
|
||||
let mut receipt = drain_receipt(call.challenge, &reply_bytes);
|
||||
transfer(pipe.as_raw_handle(), &mut receipt, true, deadline)
|
||||
.context(Stage::ClientDrainReceipt)?;
|
||||
Ok(reply)
|
||||
}
|
||||
|
||||
@@ -1388,12 +1452,21 @@ mod tests {
|
||||
#[test]
|
||||
fn untrusted_lengths_are_rejected_before_body_allocation() {
|
||||
for n in [0, (FRAME_LIMIT + 1) as u32, u32::MAX] {
|
||||
assert!(frame_length(n.to_be_bytes()).is_err());
|
||||
let mut header = [0; FRAME_HEADER_LEN];
|
||||
header[..8].copy_from_slice(&FRAME_TAG);
|
||||
header[8..].copy_from_slice(&n.to_be_bytes());
|
||||
assert!(frame_length(header).is_err());
|
||||
assert!(frame_header(n as usize).is_err());
|
||||
}
|
||||
assert_eq!(
|
||||
frame_length((FRAME_LIMIT as u32).to_be_bytes()).unwrap(),
|
||||
FRAME_LIMIT
|
||||
);
|
||||
let header = frame_header(FRAME_LIMIT).unwrap();
|
||||
assert_eq!(frame_length(header).unwrap(), FRAME_LIMIT);
|
||||
// Neither a v1 length prefix nor another framing version is accepted.
|
||||
let mut old = [0; FRAME_HEADER_LEN];
|
||||
old[..4].copy_from_slice(&1u32.to_be_bytes());
|
||||
assert!(frame_length(old).is_err());
|
||||
let mut foreign = header;
|
||||
foreign[7] = b'1';
|
||||
assert!(frame_length(foreign).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn protocol_does_not_accept_a_shell_operation() {
|
||||
@@ -1417,6 +1490,22 @@ mod tests {
|
||||
assert_eq!(diagnostic(&caller).code, "UNCLASSIFIED_IO_OR_CODEC");
|
||||
let remote = remote_denial(Stage::ClientReplyBinding, "caller-payload-private-marker");
|
||||
assert_eq!(diagnostic(&remote).code, "UNCLASSIFIED_REMOTE_DENIAL");
|
||||
let challenge = Uuid::from_u128(1);
|
||||
let raw = br#"{"a":1,"b":2}"#;
|
||||
let receipt = drain_receipt(challenge, raw);
|
||||
assert!(verify_drain_receipt(&receipt, challenge, raw).is_ok());
|
||||
// Same JSON meaning, different exact bytes must not drain this reply.
|
||||
assert!(verify_drain_receipt(&receipt, challenge, br#"{"b":2,"a":1}"#).is_err());
|
||||
assert!(verify_drain_receipt(&receipt, Uuid::from_u128(2), raw).is_err());
|
||||
for offset in [0, 7, 8, 23, 24, DRAIN_RECEIPT_LEN - 1] {
|
||||
let mut changed = receipt;
|
||||
changed[offset] ^= 1;
|
||||
let error = verify_drain_receipt(&changed, challenge, raw)
|
||||
.unwrap_err()
|
||||
.context(Stage::ServerDrainReceipt);
|
||||
assert_eq!(diagnostic(&error).code, "HELPER_DRAIN_RECEIPT");
|
||||
assert_eq!(diagnostic(&error).stage, "server_drain_receipt");
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn reconfigured_service_cannot_adopt_an_old_running_identity() {
|
||||
|
||||
@@ -470,6 +470,13 @@ fn verified_mirror_row(
|
||||
Ok(outcome)
|
||||
}
|
||||
fn system_shape(job: &JobPayload) -> bool {
|
||||
if job.action.windows_msi().is_some() {
|
||||
return job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes);
|
||||
}
|
||||
job.execution_identity == "system"
|
||||
&& (1..=120).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
@@ -487,7 +494,7 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
|
||||
matches!(
|
||||
outcome.state.as_str(),
|
||||
"succeeded" | "failed" | "cancelled" | "expired" | "unknown"
|
||||
) && !outcome.reboot_required
|
||||
) && (job.action.windows_msi().is_some() || !outcome.reboot_required)
|
||||
&& outcome
|
||||
.stdout
|
||||
.len()
|
||||
@@ -496,6 +503,47 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
|
||||
"SYSTEM_EXECUTE_OUTCOME_SCOPE"
|
||||
);
|
||||
if outcome.state == "succeeded" {
|
||||
if let Some(m) = job.action.windows_msi() {
|
||||
let e = &outcome.evidence;
|
||||
let after: crate::package::Snapshot = serde_json::from_value(e["after"].clone())?;
|
||||
let noop = e["already_desired"] == true;
|
||||
ensure!(
|
||||
job.action.validate()
|
||||
&& e["provider"] == "windows.msi.fixture/1"
|
||||
&& e["recipe_sha256"] == m.recipe_sha256
|
||||
&& e["artifact_sha256"] == m.recipe.artifact.sha256
|
||||
&& e["postconditions_passed"] == true
|
||||
&& e["state"] == "succeeded"
|
||||
&& e["exit_code"] == serde_json::to_value(outcome.exit_code)?
|
||||
&& e["already_desired"].is_boolean()
|
||||
&& !outcome.output_truncated
|
||||
&& e["reboot_initiated"] == false
|
||||
&& e["automatic_retry"] == false
|
||||
&& after.desired(m),
|
||||
"SYSTEM_MSI_POSTCONDITION_BINDING"
|
||||
);
|
||||
if noop {
|
||||
let before: crate::package::Snapshot = serde_json::from_value(e["before"].clone())?;
|
||||
ensure!(
|
||||
outcome.exit_code.is_none()
|
||||
&& !outcome.reboot_required
|
||||
&& e["installer_process_started"] == false
|
||||
&& e["transaction_started"] == false
|
||||
&& e["installer_reboot_required"].is_null()
|
||||
&& before.desired(m),
|
||||
"SYSTEM_MSI_NOOP_BINDING"
|
||||
);
|
||||
} else {
|
||||
ensure!(
|
||||
matches!(outcome.exit_code, Some(0 | 3010))
|
||||
&& e["installer_process_started"] == true
|
||||
&& outcome.reboot_required == (outcome.exit_code == Some(3010))
|
||||
&& e["installer_reboot_required"] == outcome.reboot_required,
|
||||
"SYSTEM_MSI_EXIT_BINDING"
|
||||
);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let Action::SetServiceState { unit, state } = &job.action else {
|
||||
anyhow::bail!("SYSTEM_TYPED_SERVICE_REQUIRED");
|
||||
};
|
||||
@@ -537,6 +585,43 @@ pub fn map_snapshot(s: &Snapshot) -> HelperSnapshot {
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn msi_test_job() -> JobPayload {
|
||||
use rmm_domain::windows_execution::*;
|
||||
let recipe:WindowsMsiRecipe=serde_json::from_value(json!({"schema_version":1,"recipe_id":MSI_RECIPE_ID,"recipe_version":"1","platform":"windows","upgrade_code":MSI_UPGRADE_CODE,"architecture":"x64","context":"machine","command_profile":"fixture_quiet_no_reboot_v1","artifact":{"artifact_id":uuid::Uuid::from_u128(10),"sha256":"ab".repeat(32),"bytes":32768},"postcondition":{"product_code":MSI_PRODUCT_CODE,"product_version":MSI_VERSION,"payload_path":MSI_PAYLOAD,"payload_sha256":MSI_PAYLOAD_10_SHA256,"payload_bytes":33},"no_reboot":true})).unwrap();
|
||||
let manifest = ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
};
|
||||
let now = chrono::Utc::now();
|
||||
let id = uuid::Uuid::from_u128(1);
|
||||
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: Action::EnsurePackage {
|
||||
provider: "msi".into(),
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: MSI_VERSION.into(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: "1".into(),
|
||||
installation_context: "machine".into(),
|
||||
recipe_id: Some(MSI_RECIPE_ID.into()),
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: Some(Box::new(manifest)),
|
||||
},
|
||||
execution_identity: "system".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::minutes(2),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
}
|
||||
}
|
||||
fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
|
||||
native::private_path(state, true)?;
|
||||
let path = state.join(PROBE_FILE);
|
||||
@@ -574,6 +659,50 @@ fn write_current_probe(state: &Path, value: &serde_json::Value) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit() {
|
||||
let job = msi_test_job();
|
||||
assert!(system_shape(&job));
|
||||
let m = job.action.windows_msi().unwrap();
|
||||
let p = &m.recipe.postcondition;
|
||||
let snapshot = crate::package::Snapshot {
|
||||
product_code: p.product_code.clone(),
|
||||
related_products: vec![p.product_code.clone()],
|
||||
product_state: Some("5".into()),
|
||||
product_version: Some(p.product_version.clone()),
|
||||
payload_sha256: Some(p.payload_sha256.clone()),
|
||||
payload_bytes: Some(p.payload_bytes),
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = Outcome {
|
||||
state: "succeeded".into(),
|
||||
exit_code: Some(3010),
|
||||
reboot_required: true,
|
||||
evidence: json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":true,"reboot_initiated":false,"automatic_retry":false,"already_desired":false,"state":"succeeded","exit_code":3010,"installer_process_started":true,"installer_reboot_required":true,"after":snapshot,"before":snapshot}),
|
||||
..Outcome::unknown("")
|
||||
};
|
||||
assert!(checked_outcome(&job, &out).is_ok());
|
||||
out.reboot_required = false;
|
||||
assert!(checked_outcome(&job, &out).is_err());
|
||||
out.reboot_required = true;
|
||||
out.evidence["after"]["payload_sha256"] = "cd".repeat(32).into();
|
||||
assert!(checked_outcome(&job, &out).is_err());
|
||||
out.evidence["after"] = serde_json::to_value(&snapshot).unwrap();
|
||||
out.evidence["already_desired"] = true.into();
|
||||
out.evidence["exit_code"] = serde_json::Value::Null;
|
||||
out.exit_code = None;
|
||||
out.reboot_required = false;
|
||||
out.evidence["installer_reboot_required"] = serde_json::Value::Null;
|
||||
out.evidence["installer_process_started"] = false.into();
|
||||
out.evidence["transaction_started"] = false.into();
|
||||
assert!(checked_outcome(&job, &out).is_ok());
|
||||
out.exit_code = Some(0);
|
||||
assert!(checked_outcome(&job, &out).is_err());
|
||||
out.state = "unknown".into();
|
||||
out.reboot_required = true;
|
||||
out.exit_code = Some(1641);
|
||||
assert!(checked_outcome(&job, &out).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn system_route_binds_original_request_shape_budget_and_reply_scope() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
|
||||
@@ -69,11 +69,49 @@ pub struct Settings {
|
||||
pub max_runtime_seconds: u32,
|
||||
pub enable_effects: bool,
|
||||
pub allow_reboot: bool,
|
||||
#[serde(
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none",
|
||||
deserialize_with = "strict_recipe_hashes"
|
||||
)]
|
||||
pub allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
}
|
||||
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
|
||||
d: D,
|
||||
) -> std::result::Result<Option<Vec<String>>, D::Error> {
|
||||
Vec::<String>::deserialize(d).map(Some)
|
||||
}
|
||||
impl Settings {
|
||||
fn permits_msi(&self, job: &JobPayload) -> bool {
|
||||
self.schema_version == 2
|
||||
&& job.execution_identity == "system"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& job.max_runtime_seconds <= self.max_runtime_seconds
|
||||
&& job.action.windows_msi().is_some_and(|m| {
|
||||
self.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|h| h.contains(&m.recipe_sha256))
|
||||
})
|
||||
}
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
ensure!(
|
||||
self.schema_version == 1
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2 || self.allowed_msi_recipe_sha256.is_none())
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_none_or(|hashes| {
|
||||
hashes.len() <= 2
|
||||
&& hashes.iter().all(|h| ipc::digest(h))
|
||||
&& hashes
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& !self.allow_reboot
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
&& self.allowed_services.len() <= 16,
|
||||
@@ -763,6 +801,11 @@ fn verified_window(
|
||||
Ok((job, permit, now))
|
||||
}
|
||||
|
||||
struct UnsettledMsi {
|
||||
grant: Uuid,
|
||||
request_sha256: String,
|
||||
installer: Box<crate::package::Installer>,
|
||||
}
|
||||
pub struct SystemHelper {
|
||||
settings: Settings,
|
||||
pin: Pin,
|
||||
@@ -773,6 +816,7 @@ pub struct SystemHelper {
|
||||
boot: WindowsBoot,
|
||||
sync: Option<HelperSync<DalekVerifier>>,
|
||||
last_diagnostic: Option<Instant>,
|
||||
unsettled_msi: Option<UnsettledMsi>,
|
||||
}
|
||||
impl SystemHelper {
|
||||
pub fn open() -> Result<Self> {
|
||||
@@ -796,6 +840,7 @@ impl SystemHelper {
|
||||
boot,
|
||||
sync,
|
||||
last_diagnostic: None,
|
||||
unsettled_msi: None,
|
||||
})
|
||||
}
|
||||
pub fn pin(&self) -> &Pin {
|
||||
@@ -972,7 +1017,8 @@ impl SystemHelper {
|
||||
ensure!(
|
||||
job.execution_identity == "system"
|
||||
&& job.max_runtime_seconds <= self.settings.max_runtime_seconds
|
||||
&& matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit)),
|
||||
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|
||||
|| self.settings.permits_msi(&job)),
|
||||
"SYSTEM_ABANDON_POLICY_DENIED"
|
||||
);
|
||||
self.sync()?;
|
||||
@@ -1063,6 +1109,9 @@ impl SystemHelper {
|
||||
),
|
||||
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
||||
);
|
||||
if job.action.windows_msi().is_some() {
|
||||
return self.execute_msi(generation, request, &job, &permit, peer);
|
||||
}
|
||||
let mut provider = PreparedService::prepare(&self.settings, &job)?;
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
@@ -1101,6 +1150,211 @@ impl SystemHelper {
|
||||
ledger::finish(&self.db, &permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn execute_msi(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
request: &Request,
|
||||
job: &JobPayload,
|
||||
permit: &ExecutionPermitPayload,
|
||||
peer: &mut ipc::PeerProof,
|
||||
) -> Result<Outcome> {
|
||||
use crate::package::{Prepared, Run};
|
||||
self.observe_unsettled_msi()?;
|
||||
ensure!(
|
||||
self.unsettled_msi.is_none(),
|
||||
"SYSTEM_MSI_PREVIOUS_PROCESS_UNSETTLED"
|
||||
);
|
||||
let began = Instant::now();
|
||||
let original_request_sha256 = hash(&serde_json::to_vec(request)?);
|
||||
let timeout = Duration::from_secs(job.max_runtime_seconds.into());
|
||||
let m = job
|
||||
.action
|
||||
.windows_msi()
|
||||
.context("SYSTEM_MSI_MANIFEST_REQUIRED")?;
|
||||
ensure!(
|
||||
self.settings.permits_msi(job),
|
||||
"SYSTEM_MSI_RECIPE_NOT_ALLOWED"
|
||||
);
|
||||
// No implicit bootstrap: reject absent/unprotected cache before consume.
|
||||
let _cache = PinnedFile::open(Path::new(crate::msi_cache::CACHE), true, &[], &[], false)
|
||||
.context("MSI_CACHE_NOT_CONFIGURED")?;
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
ensure!(
|
||||
self.sync.as_ref().unwrap().can_start(
|
||||
&self.db,
|
||||
&self.guard,
|
||||
generation,
|
||||
&self.clock,
|
||||
&self.boot
|
||||
),
|
||||
"SYSTEM_SIGNED_SYNC_REQUIRED"
|
||||
);
|
||||
let (_, fresh, recorded_at) =
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
ensure!(
|
||||
&fresh == permit && !STOP.load(Ordering::SeqCst),
|
||||
"SYSTEM_MSI_START_FENCED"
|
||||
);
|
||||
ledger::begin_execution(
|
||||
&mut self.db,
|
||||
permit,
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
recorded_at,
|
||||
)?;
|
||||
self.sync.as_mut().unwrap().close();
|
||||
let result = (|| -> Result<Outcome> {
|
||||
ensure!(
|
||||
began.elapsed() < timeout,
|
||||
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
||||
);
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
let _copied_archive = crate::msi_cache::import(m, permit.grant_id)?;
|
||||
ensure!(
|
||||
began.elapsed() < timeout,
|
||||
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
||||
);
|
||||
let provider = Prepared::prepare(m, &m.recipe_sha256, began, timeout)?;
|
||||
let run = provider.start(began, timeout, &STOP, || {
|
||||
self.recheck()?;
|
||||
peer.check()?;
|
||||
ensure!(
|
||||
!STOP.load(Ordering::SeqCst),
|
||||
"SYSTEM_MSI_CANCELLED_BEFORE_START"
|
||||
);
|
||||
verified_window(&self.settings.binding, request, &self.clock)?;
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
self.boot.current_boot()?,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)?;
|
||||
Ok(())
|
||||
})?;
|
||||
let observation = match run {
|
||||
Run::Noop(value) => *value, // Noop variant can itself be Unknown.
|
||||
Run::Installer(mut child) => loop {
|
||||
// Continue observing this original transaction after start.
|
||||
// A lost clock/peer/agent-denial observation cannot free the
|
||||
// lane or retroactively produce success; never kill/retry.
|
||||
let fenced = STOP.load(Ordering::SeqCst)
|
||||
|| self.clock.now().is_err()
|
||||
|| peer.check().is_err()
|
||||
|| self
|
||||
.boot
|
||||
.current_boot()
|
||||
.and_then(|boot| {
|
||||
crate::helper_runtime::intent::Store::require_not_denied(
|
||||
request,
|
||||
boot,
|
||||
generation,
|
||||
&self.pin.policy_sha256,
|
||||
&self.pin.helper.binary_sha256,
|
||||
)
|
||||
})
|
||||
.is_err();
|
||||
let cancelled = AtomicBool::new(fenced);
|
||||
match child.poll(&cancelled) {
|
||||
Ok(Some(mut value)) => {
|
||||
if fenced {
|
||||
value.state = "unknown";
|
||||
value.code = "MSI_RUNNING_OBSERVATION_FENCED";
|
||||
value.postconditions_passed = false;
|
||||
}
|
||||
if value.state == "unknown" {
|
||||
self.unsettled_msi = Some(UnsettledMsi {
|
||||
grant: permit.grant_id,
|
||||
request_sha256: original_request_sha256.clone(),
|
||||
installer: child,
|
||||
});
|
||||
}
|
||||
break value;
|
||||
}
|
||||
Ok(None) => std::thread::sleep(Duration::from_millis(50)),
|
||||
Err(error) => {
|
||||
let outcome = Outcome {
|
||||
evidence: serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":true,"process_id":child.process_id(),"automatic_retry":false,"observer_error":safe_error(&error)}),
|
||||
..Outcome::unknown("MSI_OBSERVER_FAILED_EFFECT_UNRESOLVED")
|
||||
};
|
||||
self.unsettled_msi = Some(UnsettledMsi {
|
||||
grant: permit.grant_id,
|
||||
request_sha256: original_request_sha256.clone(),
|
||||
installer: child,
|
||||
});
|
||||
return Ok(outcome);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
let mut evidence = serde_json::to_value(&observation)?;
|
||||
evidence["provider"] = "windows.msi.fixture/1".into();
|
||||
let mut outcome = Outcome {
|
||||
state: observation.state.into(),
|
||||
stdout: vec![],
|
||||
stderr: vec![],
|
||||
exit_code: observation.exit_code.map(|v| v as i32),
|
||||
output_truncated: false,
|
||||
reboot_required: observation.installer_reboot_required.unwrap_or(false),
|
||||
error_code: if observation.state == "succeeded" {
|
||||
String::new()
|
||||
} else {
|
||||
observation.code.into()
|
||||
},
|
||||
evidence,
|
||||
};
|
||||
if outcome.state == "succeeded" {
|
||||
let fresh = self.clock.now().is_ok() && peer.check().is_ok();
|
||||
if !fresh || began.elapsed() >= timeout {
|
||||
outcome.state = "unknown".into();
|
||||
outcome.error_code = "MSI_FINAL_OBSERVATION_FENCED".into();
|
||||
outcome.evidence["postconditions_passed"] = false.into();
|
||||
}
|
||||
}
|
||||
Ok(outcome)
|
||||
})();
|
||||
let outcome = result.unwrap_or_else(|error| {
|
||||
let code = safe_error(&error);
|
||||
Outcome {state:if began.elapsed() >= timeout {"unknown"} else {"failed"}.into(),
|
||||
evidence:serde_json::json!({"provider":"windows.msi.fixture/1","recipe_sha256":m.recipe_sha256,"artifact_sha256":m.recipe.artifact.sha256,"postconditions_passed":false,"installer_process_started":false,"transaction_started":false,"automatic_retry":false}), ..Outcome::unknown(&code)}
|
||||
});
|
||||
ledger::persist_outcome(&self.db, permit, &outcome)?;
|
||||
self.guard.check(&self.db)?;
|
||||
ledger::finish(&self.db, permit, &outcome)?;
|
||||
Ok(outcome)
|
||||
}
|
||||
fn observe_unsettled_msi(&mut self) -> Result<()> {
|
||||
let Some(slot) = self.unsettled_msi.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
self.guard.check(&self.db)?;
|
||||
let (start, outcome): (Vec<u8>, Vec<u8>) = self.db.query_row(
|
||||
"SELECT start,outcome FROM execution_evidence WHERE grant_id=?1",
|
||||
[slot.grant.to_string()],
|
||||
|r| Ok((r.get(0)?, r.get(1)?)),
|
||||
)?;
|
||||
let start: serde_json::Value = serde_json::from_slice(&start)?;
|
||||
let original: Request = serde_json::from_value(start["request"].clone())?;
|
||||
let saved: Outcome = serde_json::from_slice(&outcome)?;
|
||||
ensure!(
|
||||
hash(&serde_json::to_vec(&original)?) == slot.request_sha256
|
||||
&& saved.state == "unknown",
|
||||
"SYSTEM_MSI_UNSETTLED_ORIGINAL_BINDING"
|
||||
);
|
||||
if slot.installer.process_exited()? {
|
||||
self.unsettled_msi = None;
|
||||
}
|
||||
// No ledger/outcome update here. An observed late exit never revises
|
||||
// the original deadline outcome or grants permission for another job.
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub fn safe_error(error: &anyhow::Error) -> String {
|
||||
if error.chain().any(|cause| {
|
||||
@@ -1176,10 +1430,16 @@ unsafe extern "system" fn service_main(_: u32, _: *mut *mut u16) {
|
||||
let server = ipc::Server::bind(helper.pin().clone())?;
|
||||
scm_status(SERVICE_RUNNING, 0);
|
||||
while !STOP.load(Ordering::SeqCst) {
|
||||
// A failed observation keeps the owned slot and its handles locked.
|
||||
if helper.observe_unsettled_msi().is_err()
|
||||
&& let Some(sync) = &mut helper.sync
|
||||
{
|
||||
sync.close();
|
||||
}
|
||||
match server.receive() {
|
||||
Ok(Some(mut incoming)) => {
|
||||
let reply = helper.handle(&incoming.call, &mut incoming.peer);
|
||||
if let Err(error) = server.reply(&reply) {
|
||||
if let Err(error) = server.reply(&reply, &mut incoming.peer) {
|
||||
if let Some(sync) = &mut helper.sync {
|
||||
sync.close();
|
||||
}
|
||||
@@ -1230,6 +1490,56 @@ pub fn dispatch() -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi() {
|
||||
let job = crate::helper_runtime::msi_test_job();
|
||||
let m = job.action.windows_msi().unwrap();
|
||||
let peer = PeerPin {
|
||||
service_name: "synthetic".into(),
|
||||
service_sid: "synthetic".into(),
|
||||
user_sid: "synthetic".into(),
|
||||
binary: PathBuf::from("synthetic"),
|
||||
binary_sha256: "ab".repeat(32),
|
||||
};
|
||||
let mut settings = Settings {
|
||||
schema_version: 1,
|
||||
binding: Binding {
|
||||
tenant_id: job.tenant_id,
|
||||
asset_id: job.asset_id,
|
||||
agent_id: job.agent_id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
public_key_hex: "ab".repeat(32),
|
||||
},
|
||||
agent: peer.clone(),
|
||||
helper: peer,
|
||||
allowed_services: vec![],
|
||||
max_runtime_seconds: 30,
|
||||
enable_effects: false,
|
||||
allow_reboot: false,
|
||||
allowed_msi_recipe_sha256: None,
|
||||
};
|
||||
let legacy = serde_json::to_value(&settings).unwrap();
|
||||
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
|
||||
let mut null = legacy.clone();
|
||||
null["allowed_msi_recipe_sha256"] = serde_json::Value::Null;
|
||||
assert!(serde_json::from_value::<Settings>(null).is_err());
|
||||
assert!(!settings.permits_msi(&job));
|
||||
settings.allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
|
||||
assert!(!settings.permits_msi(&job));
|
||||
assert_eq!(
|
||||
settings.validate().unwrap_err().to_string(),
|
||||
"SYSTEM_POLICY_PROFILE"
|
||||
);
|
||||
settings.schema_version = 2;
|
||||
assert!(settings.permits_msi(&job));
|
||||
assert!(!settings.enable_effects);
|
||||
settings.max_runtime_seconds = 29;
|
||||
assert!(!settings.permits_msi(&job));
|
||||
settings.max_runtime_seconds = 30;
|
||||
settings.allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
||||
assert!(!settings.permits_msi(&job));
|
||||
}
|
||||
#[test]
|
||||
fn service_adapter_exposes_only_implemented_states() {
|
||||
assert_eq!(desired_state("running").unwrap(), SERVICE_RUNNING);
|
||||
assert_eq!(desired_state("stopped").unwrap(), SERVICE_STOPPED);
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Shared protected public signing binding; never learns trust from a worker ticket.
|
||||
use crate::native;
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_agent_core::auth::Binding;
|
||||
use std::path::Path;
|
||||
fn read_private(path: &Path, limit: u64) -> Result<Vec<u8>> {
|
||||
use std::{fs::OpenOptions, io::Read, os::windows::fs::OpenOptionsExt};
|
||||
use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_READ};
|
||||
native::private_path(path, false)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
ensure!(file.metadata()?.len() <= limit, "BINDING_SIZE");
|
||||
let mut bytes = Vec::new();
|
||||
(&mut file).take(limit + 1).read_to_end(&mut bytes)?;
|
||||
ensure!(bytes.len() as u64 <= limit, "BINDING_SIZE");
|
||||
Ok(bytes)
|
||||
}
|
||||
pub fn check_admin_readonly(path: &Path) -> Result<()> {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
self, ACCESS_ALLOWED_ACE, ACL,
|
||||
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
},
|
||||
};
|
||||
unsafe fn sid(sid: Security::PSID) -> Result<String> {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
|
||||
"BINDING_SID"
|
||||
);
|
||||
let mut len = 0;
|
||||
while unsafe { *raw.add(len) } != 0 {
|
||||
len += 1;
|
||||
ensure!(len < 256, "BINDING_SID_LIMIT");
|
||||
}
|
||||
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
|
||||
unsafe {
|
||||
LocalFree(raw.cast());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
|
||||
// The immediate configuration directory must also deny agent replacement.
|
||||
for (item, directory) in [
|
||||
(path, false),
|
||||
(path.parent().context("BINDING_PARENT")?, true),
|
||||
] {
|
||||
native::private_path(item, directory)?;
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut dacl: *mut ACL = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
native::wide(item).as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&mut owner,
|
||||
ptr::null_mut(),
|
||||
&mut dacl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "BINDING_SECURITY");
|
||||
let check = (|| -> Result<()> {
|
||||
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
|
||||
ensure!(
|
||||
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
|
||||
"BINDING_ADMIN_OWNER_REQUIRED"
|
||||
);
|
||||
for index in 0..unsafe { (*dacl).AceCount } {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
|
||||
"BINDING_ACE"
|
||||
);
|
||||
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
|
||||
ensure!(
|
||||
ace.Header.AceType == 0
|
||||
&& usize::from(ace.Header.AceSize)
|
||||
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||
"BINDING_ACE_TYPE"
|
||||
);
|
||||
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
|
||||
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
|
||||
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
|
||||
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
check?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn readonly_binding(path: &Path) -> Result<Binding> {
|
||||
check_admin_readonly(path)?;
|
||||
let binding: Binding = serde_json::from_slice(&read_private(path, 8192)?)?;
|
||||
ensure!(
|
||||
!binding.tenant_id.is_nil()
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.enrollment_generation > 0
|
||||
&& binding.assignment_version > 0
|
||||
&& binding.public_key_hex.len() == 64
|
||||
&& binding
|
||||
.public_key_hex
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit()),
|
||||
"JOB_BINDING_PROFILE"
|
||||
);
|
||||
Ok(binding)
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
pub mod actions;
|
||||
#[cfg(windows)]
|
||||
pub mod clock;
|
||||
pub mod event_log;
|
||||
#[cfg(windows)]
|
||||
pub mod event_log_job;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub mod helper_ipc;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
@@ -12,7 +15,12 @@ pub mod helper_runtime;
|
||||
pub mod helper_system;
|
||||
#[cfg(windows)]
|
||||
pub mod inventory;
|
||||
#[cfg(windows)]
|
||||
pub mod job_binding;
|
||||
pub mod journal;
|
||||
pub mod package;
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub mod msi_cache;
|
||||
#[cfg(windows)]
|
||||
pub mod native;
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Fixed public-byte staging and independent SYSTEM cache import. No IPC path,
|
||||
//! URL or byte-array authority. Directories must be provisioned separately;
|
||||
//! this module never installs/repairs an ACL, directory, policy or service.
|
||||
use crate::helper_ipc::{self as ipc, PinnedFile};
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use rmm_domain::windows_execution::ResolvedWindowsMsi;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
mem::zeroed,
|
||||
os::windows::{
|
||||
fs::OpenOptionsExt,
|
||||
io::{AsRawHandle, FromRawHandle},
|
||||
},
|
||||
path::{Path, PathBuf},
|
||||
ptr,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
use windows_sys::Win32::{Foundation::*, Storage::FileSystem::*};
|
||||
|
||||
pub const AGENT_STATE: &str = r"C:\ProgramData\RustDiscovery\state";
|
||||
pub const STAGE: &str = r"C:\ProgramData\RustDiscovery\state\msi-stage";
|
||||
pub const CACHE: &str = r"C:\ProgramData\RustDiscoverySystem\cache";
|
||||
fn name(m: &ResolvedWindowsMsi) -> Result<String> {
|
||||
ensure!(m.validate(), "MSI_CACHE_MANIFEST");
|
||||
Ok(format!("{}.msi", m.recipe.artifact.sha256))
|
||||
}
|
||||
fn regular(file: &File, directory: bool) -> Result<()> {
|
||||
let mut i: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
|
||||
ensure!(
|
||||
unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut i) } != 0
|
||||
&& i.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT == 0
|
||||
&& (i.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY != 0) == directory
|
||||
&& (directory || i.nNumberOfLinks == 1),
|
||||
"MSI_CACHE_NONREGULAR"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
/// Keep every actual parent open without DELETE sharing throughout the copy.
|
||||
/// Source data/ACL is untrusted; only the original signed digest authorizes bytes.
|
||||
fn parents(path: &Path) -> Result<Vec<File>> {
|
||||
let mut held = Vec::new();
|
||||
for p in path.ancestors().skip(1) {
|
||||
let raw = unsafe {
|
||||
CreateFileW(
|
||||
ipc::wide(p).as_ptr(),
|
||||
FILE_READ_ATTRIBUTES,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
|
||||
ptr::null_mut(),
|
||||
)
|
||||
};
|
||||
ensure!(
|
||||
raw != INVALID_HANDLE_VALUE,
|
||||
"MSI_CACHE_PARENT_NOT_CONFIGURED"
|
||||
);
|
||||
let file = unsafe { File::from_raw_handle(raw) };
|
||||
regular(&file, true)?;
|
||||
held.push(file);
|
||||
}
|
||||
Ok(held)
|
||||
}
|
||||
fn checked_bytes(path: &Path, m: &ResolvedWindowsMsi) -> Result<Vec<u8>> {
|
||||
let _parents = parents(path)?;
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)
|
||||
.context("MSI_STAGE_NOT_CONFIGURED")?;
|
||||
regular(&file, false)?;
|
||||
let id = ipc::file_identity(&file)?;
|
||||
ensure!(
|
||||
file.metadata()?.len() == m.recipe.artifact.bytes && m.recipe.artifact.bytes <= 262144,
|
||||
"MSI_CACHE_LENGTH"
|
||||
);
|
||||
let mut bytes = Vec::new();
|
||||
(&mut file).take(262145).read_to_end(&mut bytes)?;
|
||||
ensure!(
|
||||
bytes.len() as u64 == m.recipe.artifact.bytes
|
||||
&& format!("{:x}", Sha256::digest(&bytes)) == m.recipe.artifact.sha256,
|
||||
"MSI_CACHE_DIGEST"
|
||||
);
|
||||
let again = OpenOptions::new()
|
||||
.read(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(path)?;
|
||||
regular(&again, false)?;
|
||||
ensure!(ipc::file_identity(&again)? == id, "MSI_CACHE_FILE_REPLACED");
|
||||
Ok(bytes)
|
||||
}
|
||||
pub fn stage_configured() -> bool {
|
||||
crate::native::private_path(Path::new(STAGE), true).is_ok()
|
||||
}
|
||||
/// Called by LocalService only for the already approved original job/attempt.
|
||||
pub fn stage(m: &ResolvedWindowsMsi, bytes: &[u8]) -> Result<()> {
|
||||
crate::native::require_local_service()?;
|
||||
let path = Path::new(STAGE).join(name(m)?);
|
||||
let _parents = parents(&path)?;
|
||||
crate::native::private_path(Path::new(STAGE), true)?;
|
||||
ensure!(
|
||||
bytes.len() as u64 == m.recipe.artifact.bytes
|
||||
&& format!("{:x}", Sha256::digest(bytes)) == m.recipe.artifact.sha256,
|
||||
"MSI_DOWNLOAD_DIGEST"
|
||||
);
|
||||
if path.try_exists()? {
|
||||
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
|
||||
return Ok(());
|
||||
}
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(&path)?;
|
||||
regular(&file, false)?;
|
||||
let id = ipc::file_identity(&file)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
ensure!(ipc::file_identity(&file)? == id, "MSI_STAGE_FILE_CHANGED");
|
||||
drop(file);
|
||||
crate::native::private_path(&path, false)?;
|
||||
ensure!(checked_bytes(&path, m)? == bytes, "MSI_STAGE_CONFLICT");
|
||||
Ok(())
|
||||
}
|
||||
/// Called ONLY after full independent helper authorization and durable consume.
|
||||
/// Publish to the fixed SYS/Admin cache without replacing any existing entry.
|
||||
/// Returned guards pin the copied archive until the provider holds its own.
|
||||
pub fn import(m: &ResolvedWindowsMsi, grant: Uuid) -> Result<Vec<PinnedFile>> {
|
||||
let file_name = name(m)?;
|
||||
ensure!(!grant.is_nil(), "MSI_CACHE_GRANT");
|
||||
let destination = Path::new(CACHE).join(file_name);
|
||||
let _parents = parents(&destination)?;
|
||||
let root = PinnedFile::open(Path::new(CACHE), true, &[], &[], false)
|
||||
.context("MSI_CACHE_NOT_CONFIGURED")?;
|
||||
if destination.try_exists()? {
|
||||
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
|
||||
checked_bytes(&destination, m)?;
|
||||
return Ok(vec![root, archive]);
|
||||
}
|
||||
let source: PathBuf = Path::new(STAGE).join(name(m)?);
|
||||
let bytes = checked_bytes(&source, m)?; // Never trust actor ownership/data.
|
||||
let pending = Path::new(CACHE).join(format!("{}.{}.pending", m.recipe.artifact.sha256, grant));
|
||||
let mut file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.share_mode(FILE_SHARE_READ)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
|
||||
.open(&pending)?;
|
||||
regular(&file, false)?;
|
||||
file.write_all(&bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
// Cache directory was already independently validated SYS/Admin-only. New
|
||||
// SYSTEM-created files inherit that boundary; no ACL repair is performed.
|
||||
let copied = PinnedFile::open(&pending, false, &[], &[], false)?;
|
||||
checked_bytes(&pending, m)?;
|
||||
drop(copied);
|
||||
ensure!(
|
||||
unsafe {
|
||||
MoveFileExW(
|
||||
ipc::wide(&pending).as_ptr(),
|
||||
ipc::wide(&destination).as_ptr(),
|
||||
0,
|
||||
)
|
||||
} != 0,
|
||||
"MSI_CACHE_CREATE_ONLY_PUBLICATION"
|
||||
);
|
||||
let archive = PinnedFile::open(&destination, false, &[], &[], false)?;
|
||||
checked_bytes(&destination, m)?;
|
||||
Ok(vec![root, archive])
|
||||
}
|
||||
@@ -4,8 +4,8 @@
|
||||
//! attempt before start(). Cache population is a separate verified RMM artifact
|
||||
//! operation: this module has no network, URL, UNC, transform or free arguments.
|
||||
//!
|
||||
//! Only first install/exact noop of v1.0.0 is implemented. Upgrade and EXE are
|
||||
//! separate deliveries, not guessed modes of this MSI executor.
|
||||
//! Only fixed1.0 first install/noop and fixed1.0→1.1 major-upgrade/noop.
|
||||
//! No fresh1.1, downgrade, repair, arbitrary predecessor, or EXE mode.
|
||||
//! MSI metadata APIs are synchronous. The caller owns the outer observation
|
||||
//! deadline; a poll timeout is not a promise that Windows Installer stopped.
|
||||
//! Do not put this controller in a kill-on-close process-tree executor.
|
||||
@@ -15,33 +15,81 @@
|
||||
//! https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
|
||||
#[cfg(windows)]
|
||||
use anyhow::{Result, ensure};
|
||||
#[cfg(windows)]
|
||||
use rmm_domain::windows_execution::ResolvedWindowsMsi;
|
||||
use serde::Serialize;
|
||||
#[cfg(any(windows, test))]
|
||||
use rmm_domain::windows_execution::{ResolvedWindowsMsi, valid_package_code};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Snapshot {
|
||||
pub product_code: String,
|
||||
pub package_code: Option<String>,
|
||||
pub related_products: Vec<String>,
|
||||
pub predecessor_state: Option<String>,
|
||||
pub predecessor_version: Option<String>,
|
||||
pub predecessor_package_code: Option<String>,
|
||||
pub product_state: Option<String>,
|
||||
pub product_version: Option<String>,
|
||||
pub payload_sha256: Option<String>,
|
||||
pub payload_bytes: Option<u64>,
|
||||
}
|
||||
impl Snapshot {
|
||||
#[cfg(windows)]
|
||||
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
#[cfg(any(windows, test))]
|
||||
pub(crate) fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
let p = &r.recipe.postcondition;
|
||||
self.product_state.as_deref() == Some("5")
|
||||
self.product_code == p.product_code
|
||||
&& self.related_products == [p.product_code.clone()]
|
||||
&& self.predecessor_state.is_none()
|
||||
&& self.predecessor_version.is_none()
|
||||
&& self.predecessor_package_code.is_none()
|
||||
&& r.recipe
|
||||
.package_code
|
||||
.as_ref()
|
||||
.is_none_or(|code| self.package_code.as_ref() == Some(code))
|
||||
&& self.product_state.as_deref() == Some("5")
|
||||
&& self.product_version.as_deref() == Some(&p.product_version)
|
||||
&& self.payload_sha256.as_deref() == Some(&p.payload_sha256)
|
||||
&& self.payload_bytes == Some(p.payload_bytes)
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn absent(&self) -> bool {
|
||||
self.product_state.is_none()
|
||||
self.related_products.is_empty()
|
||||
&& self.package_code.is_none()
|
||||
&& self.predecessor_state.is_none()
|
||||
&& self.predecessor_version.is_none()
|
||||
&& self.predecessor_package_code.is_none()
|
||||
&& self.product_state.is_none()
|
||||
&& self.product_version.is_none()
|
||||
&& self.payload_sha256.is_none()
|
||||
&& self.payload_bytes.is_none()
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn predecessor(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
let Some(old) = &r.recipe.predecessor else {
|
||||
return false;
|
||||
};
|
||||
self.product_code == r.recipe.postcondition.product_code
|
||||
&& self.related_products == [old.product_code.clone()]
|
||||
&& self.product_state.is_none()
|
||||
&& self.product_version.is_none()
|
||||
&& self.package_code.is_none()
|
||||
&& self.predecessor_state.as_deref() == Some("5")
|
||||
&& self.predecessor_version.as_ref() == Some(&old.product_version)
|
||||
&& self.predecessor_package_code.as_ref().is_some_and(|code| {
|
||||
valid_package_code(code) && Some(code) != r.recipe.package_code.as_ref()
|
||||
})
|
||||
&& self.payload_sha256.as_ref() == Some(&old.payload_sha256)
|
||||
&& self.payload_bytes == Some(old.payload_bytes)
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn baseline_allowed(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
self.desired(r)
|
||||
|| if r.recipe.predecessor.is_some() {
|
||||
self.predecessor(r)
|
||||
} else {
|
||||
self.absent()
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct Observation {
|
||||
@@ -93,6 +141,94 @@ fn classification(
|
||||
_ => ("unknown", "MSI_FAILURE_EFFECT_UNRESOLVED", None, false),
|
||||
}
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn within_budget(began: std::time::Instant, timeout: std::time::Duration) -> bool {
|
||||
began.elapsed() < timeout
|
||||
}
|
||||
/// Classify only evidence actually observed inside the original budget. An
|
||||
/// installer may already have changed the machine when a late poll sees exit0;
|
||||
/// late evidence cannot retroactively turn that timed-out attempt into success.
|
||||
#[cfg(any(windows, test))]
|
||||
fn observed_classification(
|
||||
exit: u32,
|
||||
postconditions: bool,
|
||||
within_deadline: bool,
|
||||
) -> (&'static str, &'static str, Option<bool>, bool) {
|
||||
let result = classification(exit, postconditions);
|
||||
if within_deadline {
|
||||
result
|
||||
} else {
|
||||
(
|
||||
"unknown",
|
||||
"MSI_TIMEOUT_EFFECT_UNRESOLVED",
|
||||
result.2,
|
||||
result.3,
|
||||
)
|
||||
}
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn expected_upgrade_rows() -> Vec<Vec<Option<String>>> {
|
||||
use rmm_domain::windows_execution::*;
|
||||
let row = |min: &str, max: Option<&str>, attributes: &str, property: &str| {
|
||||
vec![
|
||||
Some(MSI_UPGRADE_CODE.into()),
|
||||
Some(min.into()),
|
||||
max.map(str::to_owned),
|
||||
None,
|
||||
Some(attributes.into()),
|
||||
Some("ALL".into()),
|
||||
Some(property.into()),
|
||||
]
|
||||
};
|
||||
// Both lists must contain exactly the one approved ProductCode in the
|
||||
// LaunchCondition. OnlyDetect never removes an unexpected family member.
|
||||
vec![
|
||||
row("0.0.0", None, "258", MSI_ALL_PRODUCTS),
|
||||
row(MSI_VERSION, Some(MSI_VERSION), "768", MSI_OLD_PRODUCTS),
|
||||
]
|
||||
}
|
||||
#[cfg(any(windows, test))]
|
||||
fn expected_sequence_rows(upgrade: bool) -> Vec<Vec<Option<String>>> {
|
||||
let mut rows = vec![
|
||||
("LaunchConditions", 100),
|
||||
("CostInitialize", 800),
|
||||
("FileCost", 900),
|
||||
("CostFinalize", 1000),
|
||||
("InstallValidate", 1400),
|
||||
("InstallInitialize", 1500),
|
||||
("ProcessComponents", 1600),
|
||||
("UnpublishFeatures", 1800),
|
||||
("RemoveFiles", 3500),
|
||||
("RemoveFolders", 3600),
|
||||
("CreateFolders", 3700),
|
||||
("InstallFiles", 4000),
|
||||
("RegisterUser", 6000),
|
||||
("RegisterProduct", 6100),
|
||||
("PublishFeatures", 6300),
|
||||
("PublishProduct", 6400),
|
||||
("InstallFinalize", 6600),
|
||||
];
|
||||
if upgrade {
|
||||
rows.extend([
|
||||
("FindRelatedProducts", 25),
|
||||
("RemoveExistingProducts", 1550),
|
||||
]);
|
||||
}
|
||||
rows.sort_by_key(|r| r.1);
|
||||
rows.into_iter()
|
||||
.map(|(action, seq)| {
|
||||
vec![
|
||||
Some(action.into()),
|
||||
if action == "RemoveExistingProducts" {
|
||||
Some("NOT Installed".into())
|
||||
} else {
|
||||
None
|
||||
},
|
||||
Some(seq.to_string()),
|
||||
]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// Contract and locally protected policy must agree, independently of the job.
|
||||
/// The policy hash must come from the helper's protected settings, never a field
|
||||
/// copied back out of the job being checked.
|
||||
@@ -108,7 +244,7 @@ fn validate(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use rmm_domain::windows_execution::{MSI_PAYLOAD, MSI_PRODUCT_CODE};
|
||||
use rmm_domain::windows_execution::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
@@ -352,6 +488,106 @@ mod windows {
|
||||
ensure!(code == ERROR_NO_MORE_ITEMS, "MSI_DATABASE_NOT_UNIQUE");
|
||||
Ok(String::from_utf16(&text[..len as usize])?)
|
||||
}
|
||||
fn msi_rows(db: u32, query: &str, fields: u32) -> Result<Vec<Vec<Option<String>>>> {
|
||||
let mut view = 0;
|
||||
ensure!(
|
||||
unsafe { MsiDatabaseOpenViewW(db, wide(query).as_ptr(), &mut view) } == 0,
|
||||
"MSI_ROWS_VIEW"
|
||||
);
|
||||
let view = Msi(view);
|
||||
ensure!(
|
||||
unsafe { MsiViewExecute(view.0, 0) } == 0,
|
||||
"MSI_ROWS_EXECUTE"
|
||||
);
|
||||
let mut rows = Vec::new();
|
||||
loop {
|
||||
let mut record = 0;
|
||||
let code = unsafe { MsiViewFetch(view.0, &mut record) };
|
||||
let record = Msi(record);
|
||||
if code == ERROR_NO_MORE_ITEMS {
|
||||
return Ok(rows);
|
||||
}
|
||||
ensure!(
|
||||
code == 0
|
||||
&& rows.len() < 64
|
||||
&& unsafe { MsiRecordGetFieldCount(record.0) } == fields,
|
||||
"MSI_ROWS_BOUND"
|
||||
);
|
||||
let mut row = Vec::new();
|
||||
for field in 1..=fields {
|
||||
if unsafe { MsiRecordIsNull(record.0, field) } != 0 {
|
||||
row.push(None);
|
||||
continue;
|
||||
}
|
||||
let mut text = [0u16; 256];
|
||||
let mut count = 255;
|
||||
ensure!(
|
||||
unsafe { MsiRecordGetStringW(record.0, field, text.as_mut_ptr(), &mut count) }
|
||||
== 0
|
||||
&& count < 256,
|
||||
"MSI_ROW_STRING"
|
||||
);
|
||||
row.push(Some(String::from_utf16(&text[..count as usize])?));
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
fn inspect_upgrade(db: u32, r: &ResolvedWindowsMsi) -> Result<()> {
|
||||
let upgrade = r.recipe.predecessor.is_some();
|
||||
let tables = msi_rows(db, "SELECT `Name` FROM `_Tables` WHERE `Name`='Upgrade'", 1)?;
|
||||
if upgrade {
|
||||
ensure!(
|
||||
tables == vec![vec![Some("Upgrade".into())]],
|
||||
"MSI_UPGRADE_TABLE_REQUIRED"
|
||||
);
|
||||
ensure!(
|
||||
msi_rows(
|
||||
db,
|
||||
"SELECT `UpgradeCode`,`VersionMin`,`VersionMax`,`Language`,`Attributes`,`Remove`,`ActionProperty` FROM `Upgrade` ORDER BY `ActionProperty`",
|
||||
7
|
||||
)? == expected_upgrade_rows(),
|
||||
"MSI_EXACT_UPGRADE_TABLE_REQUIRED"
|
||||
);
|
||||
ensure!(
|
||||
msi_text(
|
||||
db,
|
||||
"SELECT `Value` FROM `Property` WHERE `Property`='SecureCustomProperties'"
|
||||
)? == format!("{MSI_ALL_PRODUCTS};{MSI_OLD_PRODUCTS}"),
|
||||
"MSI_SECURE_UPGRADE_PROPERTIES"
|
||||
);
|
||||
ensure!(
|
||||
msi_rows(
|
||||
db,
|
||||
"SELECT `Condition`,`Description` FROM `LaunchCondition` ORDER BY `Condition`",
|
||||
2
|
||||
)? == vec![
|
||||
vec![
|
||||
Some(MSI_UPGRADE_CONDITION.into()),
|
||||
Some(
|
||||
"Only the exact approved fixture1.0 predecessor may be upgraded."
|
||||
.into()
|
||||
)
|
||||
],
|
||||
vec![
|
||||
Some("VersionNT64".into()),
|
||||
Some("This fixture requires 64-bit Windows.".into())
|
||||
]
|
||||
],
|
||||
"MSI_EXACT_UPGRADE_LAUNCH_CONDITIONS"
|
||||
);
|
||||
} else {
|
||||
ensure!(tables.is_empty(), "MSI_UNEXPECTED_UPGRADE_TABLE");
|
||||
}
|
||||
ensure!(
|
||||
msi_rows(
|
||||
db,
|
||||
"SELECT `Action`,`Condition`,`Sequence` FROM `InstallExecuteSequence` ORDER BY `Sequence`",
|
||||
3
|
||||
)? == expected_sequence_rows(upgrade),
|
||||
"MSI_EXACT_EXECUTE_SEQUENCE_REQUIRED"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
fn no_custom_actions(db: u32) -> Result<()> {
|
||||
let mut view = 0;
|
||||
ensure!(
|
||||
@@ -409,6 +645,7 @@ mod windows {
|
||||
);
|
||||
let db = Msi(db);
|
||||
no_custom_actions(db.0)?;
|
||||
inspect_upgrade(db.0, r)?;
|
||||
let cabinet = msi_text(db.0, "SELECT `Cabinet` FROM `Media`")?;
|
||||
ensure!(
|
||||
cabinet.starts_with('#')
|
||||
@@ -420,7 +657,7 @@ mod windows {
|
||||
"MSI_EMBEDDED_CABINET_REQUIRED"
|
||||
);
|
||||
for (field, value) in [
|
||||
("ProductCode", MSI_PRODUCT_CODE),
|
||||
("ProductCode", r.recipe.postcondition.product_code.as_str()),
|
||||
(
|
||||
"ProductVersion",
|
||||
r.recipe.postcondition.product_version.as_str(),
|
||||
@@ -467,15 +704,41 @@ mod windows {
|
||||
String::from_utf16(&text[..len as usize])?.starts_with("x64;"),
|
||||
"MSI_NOT_X64"
|
||||
);
|
||||
let mut len = 255;
|
||||
ensure!(
|
||||
unsafe {
|
||||
MsiSummaryInfoGetPropertyW(
|
||||
summary.0,
|
||||
9,
|
||||
&mut kind,
|
||||
&mut value,
|
||||
&mut time,
|
||||
text.as_mut_ptr(),
|
||||
&mut len,
|
||||
)
|
||||
} == 0
|
||||
&& kind == 30
|
||||
&& len < 256,
|
||||
"MSI_PACKAGE_SUMMARY"
|
||||
);
|
||||
let package_code = String::from_utf16(&text[..len as usize])?;
|
||||
ensure!(
|
||||
valid_package_code(&package_code)
|
||||
&& r.recipe
|
||||
.package_code
|
||||
.as_ref()
|
||||
.is_none_or(|code| code == &package_code),
|
||||
"MSI_PACKAGE_CODE_BINDING"
|
||||
);
|
||||
file.check()?;
|
||||
Ok(())
|
||||
}
|
||||
fn property(name: &str) -> Result<Option<String>> {
|
||||
fn property(product: &str, name: &str) -> Result<Option<String>> {
|
||||
let mut value = [0u16; 256];
|
||||
let mut len = 255;
|
||||
let code = unsafe {
|
||||
MsiGetProductInfoExW(
|
||||
wide(MSI_PRODUCT_CODE).as_ptr(),
|
||||
wide(product).as_ptr(),
|
||||
ptr::null(),
|
||||
MSIINSTALLCONTEXT_MACHINE,
|
||||
wide(name).as_ptr(),
|
||||
@@ -489,13 +752,58 @@ mod windows {
|
||||
ensure!(code == 0 && len < 256, "MSI_MACHINE_PRODUCT_QUERY");
|
||||
Ok(Some(String::from_utf16(&value[..len as usize])?))
|
||||
}
|
||||
pub fn snapshot() -> Result<Snapshot> {
|
||||
let product_state = property("State")?;
|
||||
fn snapshot_product(product: &str, predecessor: Option<&str>) -> Result<Snapshot> {
|
||||
let product_state = property(product, "State")?;
|
||||
let product_version = if product_state.as_deref() == Some("5") {
|
||||
property("VersionString")?
|
||||
property(product, "VersionString")?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let package_code = if product_state.as_deref() == Some("5") {
|
||||
property(product, "PackageCode")?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let predecessor_state = predecessor
|
||||
.map(|p| property(p, "State"))
|
||||
.transpose()?
|
||||
.flatten();
|
||||
let predecessor_version = if predecessor_state.as_deref() == Some("5") {
|
||||
property(predecessor.unwrap(), "VersionString")?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let predecessor_package_code = if predecessor_state.as_deref() == Some("5") {
|
||||
property(predecessor.unwrap(), "PackageCode")?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut related_products = Vec::new();
|
||||
for index in 0..=16 {
|
||||
let mut code = [0u16; 39];
|
||||
let status = unsafe {
|
||||
MsiEnumRelatedProductsW(
|
||||
wide(MSI_UPGRADE_CODE).as_ptr(),
|
||||
0,
|
||||
index,
|
||||
code.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
if status == ERROR_NO_MORE_ITEMS {
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
status == ERROR_SUCCESS && index < 16 && code[38] == 0,
|
||||
"MSI_RELATED_PRODUCT_QUERY"
|
||||
);
|
||||
let code = String::from_utf16(&code[..38])?;
|
||||
ensure!(
|
||||
!related_products.contains(&code),
|
||||
"MSI_DUPLICATE_RELATED_PRODUCT"
|
||||
);
|
||||
related_products.push(code);
|
||||
}
|
||||
related_products.sort();
|
||||
let (payload_sha256, payload_bytes) = match std::fs::symlink_metadata(MSI_PAYLOAD) {
|
||||
Ok(_) => {
|
||||
let mut file = Held::open(Path::new(MSI_PAYLOAD), false)?;
|
||||
@@ -506,12 +814,32 @@ mod windows {
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
Ok(Snapshot {
|
||||
product_code: product.into(),
|
||||
package_code,
|
||||
related_products,
|
||||
predecessor_state,
|
||||
predecessor_version,
|
||||
predecessor_package_code,
|
||||
product_state,
|
||||
product_version,
|
||||
payload_sha256,
|
||||
payload_bytes,
|
||||
})
|
||||
}
|
||||
/// Retained1.0 read-only witness. No implicit choice of upgrade recipe.
|
||||
pub fn snapshot() -> Result<Snapshot> {
|
||||
snapshot_product(MSI_PRODUCT_CODE, None)
|
||||
}
|
||||
pub fn snapshot_for(r: &ResolvedWindowsMsi) -> Result<Snapshot> {
|
||||
ensure!(r.validate(), "MSI_RECIPE_INVALID");
|
||||
snapshot_product(
|
||||
&r.recipe.postcondition.product_code,
|
||||
r.recipe
|
||||
.predecessor
|
||||
.as_ref()
|
||||
.map(|old| old.product_code.as_str()),
|
||||
)
|
||||
}
|
||||
fn system_root() -> Result<PathBuf> {
|
||||
let mut value = [0u16; 32768];
|
||||
let len = unsafe { GetSystemWindowsDirectoryW(value.as_mut_ptr(), value.len() as u32) };
|
||||
@@ -527,8 +855,17 @@ mod windows {
|
||||
system_root: PathBuf,
|
||||
}
|
||||
impl Prepared {
|
||||
pub fn prepare(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<Self> {
|
||||
pub fn prepare(
|
||||
r: &ResolvedWindowsMsi,
|
||||
allowed_recipe_sha256: &str,
|
||||
began: Instant,
|
||||
timeout: Duration,
|
||||
) -> Result<Self> {
|
||||
validate(r, allowed_recipe_sha256)?;
|
||||
ensure!(
|
||||
within_budget(began, timeout),
|
||||
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
||||
);
|
||||
let mut roots = Vec::new();
|
||||
for path in [CACHE, FIXTURES] {
|
||||
let file = OpenOptions::new()
|
||||
@@ -545,11 +882,19 @@ mod windows {
|
||||
false,
|
||||
)?;
|
||||
inspect_archive(&mut archive, r)?;
|
||||
ensure!(
|
||||
within_budget(began, timeout),
|
||||
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
||||
);
|
||||
let system_root = system_root()?;
|
||||
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
|
||||
let before = snapshot()?;
|
||||
let before = snapshot_for(r)?;
|
||||
ensure!(
|
||||
before.absent() || before.desired(r),
|
||||
within_budget(began, timeout),
|
||||
"MSI_PREPARATION_TIMEOUT_NO_INSTALLER_START"
|
||||
);
|
||||
ensure!(
|
||||
before.baseline_allowed(r),
|
||||
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
|
||||
);
|
||||
Ok(Self {
|
||||
@@ -561,10 +906,30 @@ mod windows {
|
||||
system_root,
|
||||
})
|
||||
}
|
||||
fn verification_timeout(&self, after: Option<Snapshot>) -> Run {
|
||||
Run::Noop(Box::new(Observation {
|
||||
recipe_sha256: self.recipe.recipe_sha256.clone(),
|
||||
artifact_sha256: self.recipe.recipe.artifact.sha256.clone(),
|
||||
process_id: None,
|
||||
state: "unknown",
|
||||
code: "MSI_VERIFICATION_TIMEOUT_NO_INSTALLER_START",
|
||||
exit_code: None,
|
||||
postconditions_passed: false,
|
||||
already_desired: false,
|
||||
installer_process_started: false,
|
||||
transaction_started: Some(false),
|
||||
installer_reboot_required: None,
|
||||
reboot_initiated: false,
|
||||
before: self.before.clone(),
|
||||
after,
|
||||
automatic_retry: false,
|
||||
}))
|
||||
}
|
||||
/// Called only after durable original-grant consumption. No change of
|
||||
/// config, privilege, policy, clock, reboot or foreign process occurs.
|
||||
pub fn start(
|
||||
mut self,
|
||||
began: Instant,
|
||||
timeout: Duration,
|
||||
cancelled: &AtomicBool,
|
||||
check_effect_fence: impl FnOnce() -> Result<()>,
|
||||
@@ -575,10 +940,34 @@ mod windows {
|
||||
&& !cancelled.load(Ordering::SeqCst),
|
||||
"MSI_START_LIMIT_OR_CANCELLED"
|
||||
);
|
||||
inspect_archive(&mut self.archive, &self.recipe)?;
|
||||
self.msiexec.check()?;
|
||||
let before = snapshot()?;
|
||||
// One original budget includes all synchronous verification and
|
||||
// the eventual installer. A late Noop is not retroactive success.
|
||||
let archive = inspect_archive(&mut self.archive, &self.recipe);
|
||||
if !within_budget(began, timeout) {
|
||||
return Ok(self.verification_timeout(None));
|
||||
}
|
||||
archive?;
|
||||
let executable = self.msiexec.check();
|
||||
if !within_budget(began, timeout) {
|
||||
return Ok(self.verification_timeout(None));
|
||||
}
|
||||
executable?;
|
||||
let observation = snapshot_for(&self.recipe);
|
||||
if !within_budget(began, timeout) {
|
||||
return Ok(self.verification_timeout(observation.ok()));
|
||||
}
|
||||
let before = observation?;
|
||||
ensure!(before == self.before, "MSI_BASELINE_CHANGED");
|
||||
// Both a Noop and an installer decision require a fresh caller
|
||||
// authorization fence; no bypass for the already-desired branch.
|
||||
check_effect_fence()?;
|
||||
if !within_budget(began, timeout) {
|
||||
return Ok(self.verification_timeout(Some(before)));
|
||||
}
|
||||
ensure!(
|
||||
!cancelled.load(Ordering::SeqCst),
|
||||
"MSI_CANCELLED_BEFORE_START"
|
||||
);
|
||||
if before.desired(&self.recipe) {
|
||||
return Ok(Run::Noop(Box::new(Observation {
|
||||
recipe_sha256: self.recipe.recipe_sha256.clone(),
|
||||
@@ -598,14 +987,11 @@ mod windows {
|
||||
automatic_retry: false,
|
||||
})));
|
||||
}
|
||||
ensure!(before.absent(), "MSI_INSTALL_BASELINE_CONFLICT");
|
||||
use std::os::windows::process::CommandExt;
|
||||
check_effect_fence()?;
|
||||
ensure!(
|
||||
!cancelled.load(Ordering::SeqCst),
|
||||
"MSI_CANCELLED_BEFORE_START"
|
||||
before.baseline_allowed(&self.recipe),
|
||||
"MSI_INSTALL_BASELINE_CONFLICT"
|
||||
);
|
||||
let began = Instant::now();
|
||||
use std::os::windows::process::CommandExt;
|
||||
let child = Command::new(&self.msiexec.path)
|
||||
.args([
|
||||
std::ffi::OsStr::new("/i"),
|
||||
@@ -642,6 +1028,11 @@ mod windows {
|
||||
timeout: Duration,
|
||||
}
|
||||
impl Installer {
|
||||
/// Observe only this retained process handle. Never adopt a PID, kill,
|
||||
/// restart, or revise an already persisted timeout outcome.
|
||||
pub fn process_exited(&mut self) -> Result<bool> {
|
||||
Ok(self.child.try_wait()?.is_some())
|
||||
}
|
||||
pub fn process_id(&self) -> u32 {
|
||||
self.child.id()
|
||||
}
|
||||
@@ -657,14 +1048,21 @@ mod windows {
|
||||
};
|
||||
if exit.is_none()
|
||||
&& !cancelled.load(Ordering::SeqCst)
|
||||
&& self.began.elapsed() < self.timeout
|
||||
&& within_budget(self.began, self.timeout)
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut after = None;
|
||||
let (state, error, reboot, initiated) = if let Some(code) = code {
|
||||
after = snapshot().ok();
|
||||
if after.is_none() && matches!(code, 0 | 3010) {
|
||||
// No extra synchronous MSI query once the original budget has
|
||||
// expired. try_wait and snapshot can themselves return late.
|
||||
if within_budget(self.began, self.timeout) {
|
||||
after = snapshot_for(&self.prepared.recipe).ok();
|
||||
}
|
||||
let within_deadline = within_budget(self.began, self.timeout);
|
||||
if !within_deadline {
|
||||
observed_classification(code, false, false)
|
||||
} else if after.is_none() && matches!(code, 0 | 3010) {
|
||||
(
|
||||
"unknown",
|
||||
"MSI_POSTCONDITION_QUERY_FAILED",
|
||||
@@ -672,11 +1070,12 @@ mod windows {
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
classification(
|
||||
observed_classification(
|
||||
code,
|
||||
after
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.desired(&self.prepared.recipe)),
|
||||
within_deadline,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
@@ -716,11 +1115,124 @@ mod windows {
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub use windows::{Installer, Prepared, Run, snapshot};
|
||||
pub use windows::{Installer, Prepared, Run, snapshot, snapshot_for};
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn upgrade_and_noop_need_independent_exact_products_family_and_payload() {
|
||||
use rmm_domain::windows_execution::*;
|
||||
let recipe = WindowsMsiRecipe {
|
||||
schema_version: 1,
|
||||
recipe_id: MSI_UPGRADE_RECIPE_ID.into(),
|
||||
recipe_version: "1".into(),
|
||||
platform: "windows".into(),
|
||||
upgrade_code: MSI_UPGRADE_CODE.into(),
|
||||
architecture: Architecture::X64,
|
||||
context: InstallContext::Machine,
|
||||
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
|
||||
artifact: MsiArtifact {
|
||||
artifact_id: uuid::Uuid::new_v4(),
|
||||
sha256: "ab".repeat(32),
|
||||
bytes: 20480,
|
||||
},
|
||||
postcondition: MsiPostcondition {
|
||||
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
|
||||
product_version: MSI_UPGRADE_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_11_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: Some("{8475C4D1-6EE2-4C3A-B41D-D834A20F4135}".into()),
|
||||
predecessor: Some(MsiPostcondition {
|
||||
product_code: MSI_PRODUCT_CODE.into(),
|
||||
product_version: MSI_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
}),
|
||||
};
|
||||
let r = ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
};
|
||||
assert!(r.validate());
|
||||
let mut before = Snapshot {
|
||||
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
|
||||
related_products: vec![MSI_PRODUCT_CODE.into()],
|
||||
predecessor_state: Some("5".into()),
|
||||
predecessor_version: Some(MSI_VERSION.into()),
|
||||
predecessor_package_code: Some("{D1C4ECE2-7025-4E16-A842-A20F320CE783}".into()),
|
||||
payload_sha256: Some(MSI_PAYLOAD_10_SHA256.into()),
|
||||
payload_bytes: Some(MSI_PAYLOAD_BYTES),
|
||||
..Snapshot::default()
|
||||
};
|
||||
assert!(before.predecessor(&r));
|
||||
assert!(before.baseline_allowed(&r));
|
||||
assert!(!before.desired(&r));
|
||||
assert!(!Snapshot::default().baseline_allowed(&r)); // no fresh1.1 fallback
|
||||
before
|
||||
.related_products
|
||||
.push("{11111111-1111-4111-8111-111111111111}".into());
|
||||
assert!(!before.baseline_allowed(&r));
|
||||
let mut after = Snapshot {
|
||||
product_code: MSI_UPGRADE_PRODUCT_CODE.into(),
|
||||
package_code: r.recipe.package_code.clone(),
|
||||
related_products: vec![MSI_UPGRADE_PRODUCT_CODE.into()],
|
||||
product_state: Some("5".into()),
|
||||
product_version: Some(MSI_UPGRADE_VERSION.into()),
|
||||
payload_sha256: Some(MSI_PAYLOAD_11_SHA256.into()),
|
||||
payload_bytes: Some(MSI_PAYLOAD_BYTES),
|
||||
..Snapshot::default()
|
||||
};
|
||||
assert!(after.desired(&r));
|
||||
after.predecessor_state = Some("5".into());
|
||||
assert!(!after.desired(&r));
|
||||
after.predecessor_state = None;
|
||||
after.payload_sha256 = Some(MSI_PAYLOAD_10_SHA256.into());
|
||||
assert!(!after.desired(&r));
|
||||
let table = expected_upgrade_rows();
|
||||
assert_eq!(table.len(), 2);
|
||||
assert_eq!(table[0][4].as_deref(), Some("258"));
|
||||
assert_eq!(table[1][4].as_deref(), Some("768"));
|
||||
let sequence = expected_sequence_rows(true);
|
||||
let position = |name: &str| {
|
||||
sequence
|
||||
.iter()
|
||||
.position(|r| r[0].as_deref() == Some(name))
|
||||
.unwrap()
|
||||
};
|
||||
assert!(position("FindRelatedProducts") < position("LaunchConditions"));
|
||||
assert!(position("InstallInitialize") < position("RemoveExistingProducts"));
|
||||
assert!(position("RemoveExistingProducts") < position("ProcessComponents"));
|
||||
}
|
||||
#[test]
|
||||
fn late_exit_or_postcondition_cannot_retroactively_succeed_or_retry() {
|
||||
use std::time::{Duration, Instant};
|
||||
let original = Instant::now().checked_sub(Duration::from_secs(2)).unwrap();
|
||||
let timely = within_budget(Instant::now(), Duration::from_secs(60));
|
||||
let late = within_budget(original, Duration::from_secs(1));
|
||||
assert!(timely);
|
||||
assert!(!late);
|
||||
// This same budget gates the Noop decision and the installer poll;
|
||||
// metadata returning late does not receive a fresh timer.
|
||||
assert_eq!(observed_classification(0, true, late).0, "unknown");
|
||||
for exit in [0, 3010, 1618, 1603, 1641] {
|
||||
let late = observed_classification(exit, true, false);
|
||||
assert_eq!(
|
||||
(late.0, late.1),
|
||||
("unknown", "MSI_TIMEOUT_EFFECT_UNRESOLVED")
|
||||
);
|
||||
assert_eq!(
|
||||
(late.2, late.3),
|
||||
(classification(exit, true).2, classification(exit, true).3)
|
||||
);
|
||||
}
|
||||
assert_eq!(observed_classification(0, true, true).0, "succeeded");
|
||||
assert_eq!(observed_classification(0, false, true).0, "failed");
|
||||
}
|
||||
#[test]
|
||||
fn exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority() {
|
||||
assert_eq!(
|
||||
classification(0, true),
|
||||
@@ -752,6 +1264,7 @@ mod tests {
|
||||
product_version: None,
|
||||
payload_sha256: None,
|
||||
payload_bytes: None,
|
||||
..Snapshot::default()
|
||||
};
|
||||
assert!(!advertised.absent());
|
||||
}
|
||||
|
||||
+111
-116
@@ -7,7 +7,7 @@ use rmm_agent_core::{
|
||||
jobs, ledger,
|
||||
reconcile::{self, SyncClock},
|
||||
};
|
||||
use rmm_agent_windows::{CAPABILITIES, journal::Journal, native};
|
||||
use rmm_agent_windows::{CAPABILITIES, job_binding::readonly_binding, journal::Journal, native};
|
||||
use rmm_domain::jobs::{Action, ExecutionPermitPayload};
|
||||
use rmm_protocol::*;
|
||||
use rusqlite::{Connection, OptionalExtension};
|
||||
@@ -216,104 +216,6 @@ fn verified_window(
|
||||
binding.verify(request, now + chrono::Duration::seconds(2))?;
|
||||
Ok(result)
|
||||
}
|
||||
fn readonly_binding(path: &Path) -> Result<Binding> {
|
||||
use std::ptr;
|
||||
use windows_sys::Win32::{
|
||||
Foundation::LocalFree,
|
||||
Security::{
|
||||
self, ACCESS_ALLOWED_ACE, ACL,
|
||||
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
|
||||
DACL_SECURITY_INFORMATION, OWNER_SECURITY_INFORMATION,
|
||||
},
|
||||
};
|
||||
unsafe fn sid(sid: Security::PSID) -> Result<String> {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { ConvertSidToStringSidW(sid, &mut raw) } != 0,
|
||||
"BINDING_SID"
|
||||
);
|
||||
let mut len = 0;
|
||||
while unsafe { *raw.add(len) } != 0 {
|
||||
len += 1;
|
||||
ensure!(len < 256, "BINDING_SID_LIMIT");
|
||||
}
|
||||
let value = String::from_utf16(unsafe { std::slice::from_raw_parts(raw, len) })?;
|
||||
unsafe {
|
||||
LocalFree(raw.cast());
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_JOB_BINDING_REQUIRED");
|
||||
// The immediate configuration directory must also deny agent replacement.
|
||||
for (item, directory) in [
|
||||
(path, false),
|
||||
(path.parent().context("BINDING_PARENT")?, true),
|
||||
] {
|
||||
native::private_path(item, directory)?;
|
||||
let mut owner = ptr::null_mut();
|
||||
let mut dacl: *mut ACL = ptr::null_mut();
|
||||
let mut descriptor = ptr::null_mut();
|
||||
let status = unsafe {
|
||||
GetNamedSecurityInfoW(
|
||||
native::wide(item).as_ptr(),
|
||||
SE_FILE_OBJECT,
|
||||
OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION,
|
||||
&mut owner,
|
||||
ptr::null_mut(),
|
||||
&mut dacl,
|
||||
ptr::null_mut(),
|
||||
&mut descriptor,
|
||||
)
|
||||
};
|
||||
ensure!(status == 0, "BINDING_SECURITY");
|
||||
let check = (|| -> Result<()> {
|
||||
ensure!(!owner.is_null() && !dacl.is_null(), "BINDING_NULL_SECURITY");
|
||||
ensure!(
|
||||
matches!(unsafe { sid(owner) }?.as_str(), "S-1-5-18" | "S-1-5-32-544"),
|
||||
"BINDING_ADMIN_OWNER_REQUIRED"
|
||||
);
|
||||
for index in 0..unsafe { (*dacl).AceCount } {
|
||||
let mut raw = ptr::null_mut();
|
||||
ensure!(
|
||||
unsafe { Security::GetAce(dacl, u32::from(index), &mut raw) } != 0,
|
||||
"BINDING_ACE"
|
||||
);
|
||||
let ace = unsafe { &*raw.cast::<ACCESS_ALLOWED_ACE>() };
|
||||
ensure!(
|
||||
ace.Header.AceType == 0
|
||||
&& usize::from(ace.Header.AceSize)
|
||||
>= std::mem::size_of::<ACCESS_ALLOWED_ACE>(),
|
||||
"BINDING_ACE_TYPE"
|
||||
);
|
||||
let who = unsafe { sid(ptr::addr_of!(ace.SidStart).cast_mut().cast()) }?;
|
||||
if !matches!(who.as_str(), "S-1-5-18" | "S-1-5-32-544") {
|
||||
// Generic write/all, owner/DACL/delete and all file/directory mutation bits.
|
||||
ensure!(ace.Mask & 0x500d_0156 == 0, "BINDING_AGENT_WRITE_FORBIDDEN");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
unsafe {
|
||||
LocalFree(descriptor.cast());
|
||||
}
|
||||
check?;
|
||||
}
|
||||
let binding: Binding = serde_json::from_slice(&protected_read(path, 8192)?)?;
|
||||
ensure!(
|
||||
!binding.tenant_id.is_nil()
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.enrollment_generation > 0
|
||||
&& binding.assignment_version > 0
|
||||
&& binding.public_key_hex.len() == 64
|
||||
&& binding
|
||||
.public_key_hex
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_hexdigit()),
|
||||
"JOB_BINDING_PROFILE"
|
||||
);
|
||||
Ok(binding)
|
||||
}
|
||||
fn import_legacy_inventory(journal: &mut Journal) -> Result<()> {
|
||||
let original = {
|
||||
let mut q = journal
|
||||
@@ -465,6 +367,25 @@ struct Agent {
|
||||
impl Agent {
|
||||
fn close_gate(&mut self) {
|
||||
self.fence.close();
|
||||
#[cfg(feature = "system-helper")]
|
||||
if let Some(running) = &self.running
|
||||
&& running.grant.execution_identity == "system"
|
||||
{
|
||||
running.cancel.store(true, Ordering::SeqCst);
|
||||
let denied = (|| -> Result<()> {
|
||||
let mut store = rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
|
||||
let intent = store.by_grant(running.grant.grant_id)?;
|
||||
ensure!(
|
||||
intent.permit()? == running.grant,
|
||||
"SYSTEM_CANCEL_GRANT_BINDING"
|
||||
);
|
||||
store.deny(&intent.request, Uuid::parse_str(&self.boot)?)
|
||||
})();
|
||||
if denied.is_err() {
|
||||
self.helper_refused = true;
|
||||
eprintln!("SYSTEM_CANCEL_PERSISTENCE_FAILED");
|
||||
}
|
||||
}
|
||||
if let Some(sync) = &mut self.sync {
|
||||
sync.close();
|
||||
}
|
||||
@@ -664,7 +585,11 @@ impl Agent {
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
{
|
||||
Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
|
||||
(job.action.windows_msi().is_none()
|
||||
|| (self.config.state_directory
|
||||
== Path::new(rmm_agent_windows::msi_cache::AGENT_STATE)
|
||||
&& rmm_agent_windows::msi_cache::stage_configured()))
|
||||
&& Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file()
|
||||
&& self
|
||||
.helper
|
||||
.as_ref()
|
||||
@@ -684,6 +609,8 @@ impl Agent {
|
||||
{
|
||||
caps.extend(["rmm.sync.v1", "refresh_inventory"].map(str::to_string));
|
||||
if rmm_agent_windows::actions::powershell().is_ok() {
|
||||
// The process_remote_signed profile is implemented but remains
|
||||
// unpublished until its separate native qualification passes.
|
||||
caps.extend(["run_script", "script.powershell/1"].map(str::to_string));
|
||||
}
|
||||
}
|
||||
@@ -1079,9 +1006,69 @@ impl Agent {
|
||||
let completed = self.completed_tx.clone();
|
||||
let work_offer = offer.clone();
|
||||
let work_grant = grant.clone();
|
||||
let msi = job.action.windows_msi().cloned();
|
||||
let address = self.config.connect_address;
|
||||
let ca = self.ca.clone();
|
||||
let state = self.config.state_directory.clone();
|
||||
let request_for_stage = request.clone();
|
||||
let binding_for_stage = binding.clone();
|
||||
let worker = tokio::spawn(async move {
|
||||
let staged = if let Some(m) = msi {
|
||||
let result = async {
|
||||
ensure!(
|
||||
!worker_cancel.load(Ordering::SeqCst)
|
||||
&& fence.allows_identity(generation, true, &clock),
|
||||
"MSI_DOWNLOAD_FENCED"
|
||||
);
|
||||
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
|
||||
let cert = protected_read(&state.join("device.pem"), 32768)?;
|
||||
let key = protected_read(&state.join("device.key"), 16384)?;
|
||||
let tls = crate::https_channel::mtls_client(address, &ca, &cert, &key)?;
|
||||
let response = tls
|
||||
.get(format!(
|
||||
"https://{}:{}/agent/v1/artifacts/{}?job_id={}&attempt_id={}",
|
||||
crate::https_channel::server_name()?,
|
||||
address.port(),
|
||||
m.recipe.artifact.artifact_id,
|
||||
work_grant.job_id,
|
||||
work_grant.attempt_id
|
||||
))
|
||||
.send()
|
||||
.await?;
|
||||
ensure!(
|
||||
response
|
||||
.headers()
|
||||
.get("x-artifact-sha256")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
== Some(m.recipe.artifact.sha256.as_str()),
|
||||
"MSI_DOWNLOAD_METADATA"
|
||||
);
|
||||
let bytes = crate::https_channel::bounded_body(
|
||||
response,
|
||||
m.recipe.artifact.bytes as usize,
|
||||
"application/octet-stream",
|
||||
)
|
||||
.await?;
|
||||
ensure!(
|
||||
!worker_cancel.load(Ordering::SeqCst)
|
||||
&& fence.allows_identity(generation, true, &clock),
|
||||
"MSI_DOWNLOAD_FENCED"
|
||||
);
|
||||
verified_window(&binding_for_stage, &request_for_stage, &clock)?;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
rmm_agent_windows::msi_cache::stage(&m, &bytes)
|
||||
})
|
||||
.await??;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
result.is_ok()
|
||||
} else {
|
||||
true
|
||||
};
|
||||
let _result = helper
|
||||
.delegate(intent, move || {
|
||||
ensure!(staged, "MSI_DOWNLOAD_NOT_READY");
|
||||
ensure!(
|
||||
!worker_cancel.load(Ordering::SeqCst),
|
||||
"CANCELLED_BEFORE_DISPATCH"
|
||||
@@ -1162,6 +1149,7 @@ impl Agent {
|
||||
let directory = self.config.state_directory.join("jobs");
|
||||
let work_offer = offer.clone();
|
||||
let work_grant = grant.clone();
|
||||
let original_boot = Uuid::parse_str(&self.boot)?;
|
||||
let worker = tokio::task::spawn_blocking(move || {
|
||||
let outcome = (|| -> Result<Outcome> {
|
||||
if !fence.allows(generation, &clock)
|
||||
@@ -1172,17 +1160,24 @@ impl Agent {
|
||||
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||
));
|
||||
}
|
||||
let script = if matches!(job.action, Action::RunScript { .. }) {
|
||||
match rmm_agent_windows::actions::Script::prepare(
|
||||
&job,
|
||||
&directory,
|
||||
work_grant.grant_id,
|
||||
) {
|
||||
Ok(script) => Some(script),
|
||||
Err(_) => return Ok(jobs::no_start("failed", "SCRIPT_PREPARATION_FAILED")),
|
||||
let prepared = match rmm_agent_windows::actions::PreparedAction::prepare(
|
||||
&job,
|
||||
&directory,
|
||||
work_grant.grant_id,
|
||||
&request,
|
||||
original_boot,
|
||||
) {
|
||||
Ok(prepared) => prepared,
|
||||
Err(_) => {
|
||||
return Ok(jobs::no_start(
|
||||
"failed",
|
||||
if matches!(job.action, Action::RunScript { .. }) {
|
||||
"SCRIPT_PREPARATION_FAILED"
|
||||
} else {
|
||||
"ACTION_PREPARATION_FAILED"
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// File creation, pool scheduling and fsync never extend a start window.
|
||||
if worker_cancel.load(Ordering::SeqCst) {
|
||||
@@ -1196,11 +1191,7 @@ impl Agent {
|
||||
"START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT",
|
||||
));
|
||||
}
|
||||
if let Some(script) = script {
|
||||
script.run(&job, &worker_cancel)
|
||||
} else {
|
||||
rmm_agent_windows::actions::inventory(&job)
|
||||
}
|
||||
prepared.run(&job, &worker_cancel)
|
||||
})()
|
||||
.unwrap_or_else(|_| Outcome::unknown("WINDOWS_EXECUTOR_EFFECT_UNKNOWN"));
|
||||
let _ = completed.blocking_send((work_offer, work_grant, outcome));
|
||||
@@ -1390,7 +1381,7 @@ impl Agent {
|
||||
#[cfg(feature="system-helper")]
|
||||
if Path::new(rmm_agent_windows::helper_runtime::intent::DB).is_file() {
|
||||
let mut store=rmm_agent_windows::helper_runtime::intent::Store::open(true)?;
|
||||
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.cancel_before_dispatch(intent.id)?;}
|
||||
if let Some(intent)=store.pending()?.first() && intent.permit()?.job_id.to_string()==cancel.job_id && intent.permit()?.attempt_id.to_string()==cancel.attempt_id {store.deny(&intent.request,Uuid::parse_str(&self.boot)?)?;store.cancel_before_dispatch(intent.id)?;}
|
||||
}
|
||||
if state=="accepted" {self.record(generation,&JobOffer::decode(bytes.as_slice())?,&grant,jobs::no_start("cancelled","CANCELLED_BEFORE_START"))?;needs_sync=true;}
|
||||
}
|
||||
@@ -1547,6 +1538,10 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.first().map(String::as_str) == Some(rmm_agent_windows::event_log_job::MODE) {
|
||||
ensure!(args.len() == 2, "EVENT_LOG_WORKER_ARGUMENTS");
|
||||
return rmm_agent_windows::event_log_job::worker(Path::new(&args[1]));
|
||||
}
|
||||
if args == ["--help"] {
|
||||
println!(
|
||||
"Development Windows service. --service --config ABSOLUTE_PATH. Jobs disabled by default; require qualified clock, provisioned signing binding, signed Sync and WebUI-authorized grant. No approval bypass."
|
||||
|
||||
@@ -353,6 +353,7 @@ mod tests {
|
||||
script_utf8: "true".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -50,6 +50,7 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
script_utf8: "printf 'fixture only; never executed\\n'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("fixture only; never executed\n".into()),
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -594,6 +594,7 @@ fn script() -> Action {
|
||||
script_utf8: "printf hello".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
+336
-6
@@ -1,5 +1,6 @@
|
||||
//! Version 1 codec: UTF-8 compact serde JSON of these structs, declaration field
|
||||
//! order, explicit null options, ordered vectors, UTC RFC3339 timestamps. Hash the
|
||||
//! order, explicit null legacy options (new opt-in fields omit None), ordered vectors,
|
||||
//! UTC RFC3339 timestamps. Hash the
|
||||
//! stored bytes, never a reconstructed API view. No floating point/map payloads.
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -13,6 +14,51 @@ pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
|
||||
serde_json::to_vec(value)
|
||||
}
|
||||
|
||||
/// One explicitly qualified Event Log source, not an arbitrary channel/XPath.
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_SOURCE: &str =
|
||||
"windows.eventlog.application.rustdiscovery-mvp-test";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY: &str = "logs.windows.eventlog.fixture/1";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_CHANNEL: &str = "Application";
|
||||
pub const WINDOWS_EVENT_LOG_FIXTURE_PROVIDER: &str = "RustDiscovery-MVP-Test";
|
||||
|
||||
/// Fixed per-job Windows PowerShell 5.1 option, never a machine/GPO policy.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
pub enum WindowsExecutionProfile {
|
||||
#[serde(rename = "powershell_51_remote_signed")]
|
||||
PowerShell51RemoteSigned,
|
||||
}
|
||||
|
||||
/// A missing field uses serde's default None. A present field must be the exact
|
||||
/// string: null and serde's externally-tagged enum object form are not profiles.
|
||||
pub fn deserialize_windows_execution_profile<'de, D>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<WindowsExecutionProfile>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = String::deserialize(deserializer)?;
|
||||
match value.as_str() {
|
||||
"powershell_51_remote_signed" => {
|
||||
Ok(Some(WindowsExecutionProfile::PowerShell51RemoteSigned))
|
||||
}
|
||||
_ => Err(serde::de::Error::unknown_variant(
|
||||
&value,
|
||||
&["powershell_51_remote_signed"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing preserves Linux codecs; explicit null/nonobject is never a manifest.
|
||||
pub fn deserialize_windows_msi_manifest<'de, D>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<Box<crate::windows_execution::ResolvedWindowsMsi>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
crate::windows_execution::ResolvedWindowsMsi::deserialize(deserializer)
|
||||
.map(|m| Some(Box::new(m)))
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Action {
|
||||
@@ -21,6 +67,13 @@ pub enum Action {
|
||||
script_utf8: String,
|
||||
arguments: Vec<String>,
|
||||
expected_stdout: Option<String>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_windows_execution_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
},
|
||||
RefreshInventory {
|
||||
scope: String,
|
||||
@@ -46,6 +99,13 @@ pub enum Action {
|
||||
recipe_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
apt_manifest: Option<crate::apt_transaction::AptExecutionManifest>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "deserialize_windows_msi_manifest",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "crate::windows_execution::ResolvedWindowsMsi")]
|
||||
windows_msi_manifest: Option<Box<crate::windows_execution::ResolvedWindowsMsi>>,
|
||||
},
|
||||
ApplyUpdates {
|
||||
provider: String,
|
||||
@@ -99,8 +159,10 @@ impl Action {
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
} => {
|
||||
matches!(interpreter.as_str(), "posix_sh" | "bash" | "powershell")
|
||||
&& (windows_execution_profile.is_none() || interpreter == "powershell")
|
||||
&& (interpreter != "powershell"
|
||||
|| script_utf8.is_ascii()
|
||||
|| script_utf8.starts_with('\u{feff}'))
|
||||
@@ -124,7 +186,8 @@ impl Action {
|
||||
} => {
|
||||
unit(u)
|
||||
&& since < until
|
||||
&& (*until - *since).num_hours() <= 24
|
||||
&& *until - *since <= chrono::Duration::hours(24)
|
||||
&& (u != WINDOWS_EVENT_LOG_FIXTURE_SOURCE || since.timestamp() >= 0)
|
||||
&& *max_lines > 0
|
||||
&& *max_lines <= 1000
|
||||
}
|
||||
@@ -140,6 +203,28 @@ impl Action {
|
||||
installation_context,
|
||||
recipe_id,
|
||||
apt_manifest,
|
||||
windows_msi_manifest: Some(m),
|
||||
} => {
|
||||
m.validate()
|
||||
&& provider == "msi"
|
||||
&& package == crate::windows_execution::MSI_PACKAGE_ID
|
||||
&& version == &m.recipe.postcondition.product_version
|
||||
&& architecture == "x64"
|
||||
&& installation_context == "machine"
|
||||
&& recipe_version == &m.recipe.recipe_version
|
||||
&& recipe_id.as_ref() == Some(&m.recipe.recipe_id)
|
||||
&& apt_manifest.is_none()
|
||||
}
|
||||
Self::EnsurePackage {
|
||||
provider,
|
||||
package,
|
||||
version,
|
||||
architecture,
|
||||
recipe_version,
|
||||
installation_context,
|
||||
recipe_id,
|
||||
apt_manifest,
|
||||
windows_msi_manifest: None,
|
||||
} => {
|
||||
provider == "apt"
|
||||
&& unit(package)
|
||||
@@ -198,6 +283,35 @@ impl Action {
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn windows_msi(&self) -> Option<&crate::windows_execution::ResolvedWindowsMsi> {
|
||||
match self {
|
||||
Self::EnsurePackage {
|
||||
windows_msi_manifest: Some(m),
|
||||
..
|
||||
} => Some(m.as_ref()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn valid_helper_denial_shape(&self, identity: &str) -> bool {
|
||||
(matches!(self,Self::SetServiceState{state,..} if matches!(state.as_str(),"running"|"stopped"))
|
||||
&& self.validate())
|
||||
|| (identity == "system" && self.windows_msi().is_some() && self.validate())
|
||||
}
|
||||
pub fn is_windows_event_log_fixture(&self) -> bool {
|
||||
matches!(self, Self::QueryLogs { unit, .. } if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE)
|
||||
}
|
||||
/// The outer process budget includes authenticated worker startup/cleanup;
|
||||
/// its inner Event Log calls retain their own cooperative <=5s deadline.
|
||||
pub fn valid_job_limits(&self, runtime_seconds: u32, output_bytes: u32) -> bool {
|
||||
(1..=3600).contains(&runtime_seconds)
|
||||
&& (self.windows_msi().is_none()
|
||||
|| ((10..=120).contains(&runtime_seconds)
|
||||
&& (1024..=65536).contains(&output_bytes)))
|
||||
&& (1..=262144).contains(&output_bytes)
|
||||
&& (!self.is_windows_event_log_fixture()
|
||||
|| ((10..=120).contains(&runtime_seconds)
|
||||
&& (1024..=65536).contains(&output_bytes)))
|
||||
}
|
||||
/// Interpreter identity is part of the immutable action, never inferred at execution.
|
||||
pub fn script_platform(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
@@ -211,7 +325,7 @@ impl Action {
|
||||
}
|
||||
/// Shared plan/revalidation/start gate. Passive Windows never implies job support.
|
||||
pub fn available_for(&self, identity: &str, capabilities: &[String]) -> bool {
|
||||
if identity == "system" && !matches!(self, Self::SetServiceState { .. }) {
|
||||
if identity == "system" && !self.valid_helper_denial_shape(identity) {
|
||||
return false;
|
||||
}
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
@@ -219,15 +333,25 @@ impl Action {
|
||||
return false;
|
||||
}
|
||||
match self {
|
||||
Self::RunScript { interpreter, .. } if interpreter == "powershell" => {
|
||||
Self::RunScript {
|
||||
interpreter,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} if interpreter == "powershell" => {
|
||||
identity == "agent_service"
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has("script.powershell/1")
|
||||
&& (windows_execution_profile.is_none()
|
||||
|| has("script.powershell.process_remote_signed/1"))
|
||||
}
|
||||
Self::RunScript { .. } => {
|
||||
self.script_platform() == Some("linux")
|
||||
Self::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} => {
|
||||
windows_execution_profile.is_none()
|
||||
&& self.script_platform() == Some("linux")
|
||||
&& has("linux.base/1")
|
||||
&& !has("windows.base/1")
|
||||
}
|
||||
@@ -237,6 +361,27 @@ impl Action {
|
||||
&& !(has("linux.base/1") && has("windows.base/1"))
|
||||
&& (scope != "windows.base" || has("rmm.sync.v1"))
|
||||
}
|
||||
Self::EnsurePackage { .. } if self.windows_msi().is_some() || has("windows.base/1") => {
|
||||
self.windows_msi().is_some()
|
||||
&& self.validate()
|
||||
&& identity == "system"
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has("helper.system.v1")
|
||||
&& has("system:ensure_package")
|
||||
&& has(crate::windows_execution::MSI_CAPABILITY)
|
||||
}
|
||||
Self::QueryLogs { unit, .. }
|
||||
if unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE || has("windows.base/1") =>
|
||||
{
|
||||
identity == "agent_service"
|
||||
&& unit == WINDOWS_EVENT_LOG_FIXTURE_SOURCE
|
||||
&& has("windows.base/1")
|
||||
&& !has("linux.base/1")
|
||||
&& has("rmm.sync.v1")
|
||||
&& has(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY)
|
||||
}
|
||||
Self::SetServiceState { state, .. }
|
||||
if identity == "system" || has("windows.base/1") =>
|
||||
{
|
||||
@@ -272,6 +417,7 @@ impl Action {
|
||||
installation_context,
|
||||
recipe_id: None,
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: None,
|
||||
} => {
|
||||
provider == "apt"
|
||||
&& !package.is_empty()
|
||||
@@ -496,6 +642,7 @@ mod tests {
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
let mut all = caps;
|
||||
all.extend(["run_script".into(), "script.powershell/1".into()]);
|
||||
@@ -505,6 +652,7 @@ mod tests {
|
||||
script_utf8: "printf hi\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
let reboot = Action::Reboot {
|
||||
reason: "fixed test".into(),
|
||||
@@ -526,6 +674,7 @@ mod tests {
|
||||
script_utf8: "Write-Output 'Hello'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello\r\n".into()),
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
@@ -601,6 +750,7 @@ mod tests {
|
||||
script_utf8: "echo hi\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
assert_eq!(
|
||||
String::from_utf8(encode(&a).unwrap()).unwrap(),
|
||||
@@ -613,6 +763,186 @@ mod tests {
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn windows_remote_signed_profile_is_optional_exact_and_capability_bound() {
|
||||
let schema = schemars::schema_for!(Action).to_value();
|
||||
let script_schema = schema["oneOf"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|variant| {
|
||||
variant["properties"]
|
||||
.get("windows_execution_profile")
|
||||
.is_some()
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
script_schema["properties"]["windows_execution_profile"],
|
||||
serde_json::json!({"$ref":"#/$defs/WindowsExecutionProfile"})
|
||||
);
|
||||
assert!(
|
||||
!script_schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&serde_json::json!("windows_execution_profile"))
|
||||
);
|
||||
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
|
||||
let legacy = br#"{"action":"run_script","interpreter":"powershell","script_utf8":"Write-Output 'hi'\r\n","arguments":[],"expected_stdout":null}"#;
|
||||
let mut action: Action = serde_json::from_slice(legacy).unwrap();
|
||||
assert_eq!(encode(&action).unwrap(), legacy);
|
||||
let inherited_hash = hash(legacy);
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*windows_execution_profile = Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
}
|
||||
let encoded = encode(&action).unwrap();
|
||||
assert_eq!(
|
||||
String::from_utf8(encoded.clone()).unwrap(),
|
||||
String::from_utf8(legacy[..legacy.len() - 1].to_vec()).unwrap()
|
||||
+ r#","windows_execution_profile":"powershell_51_remote_signed"}"#
|
||||
);
|
||||
assert_ne!(hash(&encoded), inherited_hash);
|
||||
assert_eq!(serde_json::from_slice::<Action>(&encoded).unwrap(), action);
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"run_script",
|
||||
"script.powershell/1",
|
||||
"script.powershell.process_remote_signed/1",
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
assert!(action.validate());
|
||||
assert!(action.available_for("agent_service", &caps));
|
||||
for missing in 0..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(missing);
|
||||
assert!(!action.available_for("agent_service", &short));
|
||||
}
|
||||
for identity in ["root", "system", "SYSTEM"] {
|
||||
assert!(!action.available_for(identity, &caps));
|
||||
}
|
||||
let mut mixed = caps.clone();
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!action.available_for("agent_service", &mixed));
|
||||
for interpreter in ["posix_sh", "bash", "pwsh"] {
|
||||
let mut invalid = action.clone();
|
||||
if let Action::RunScript { interpreter: i, .. } = &mut invalid {
|
||||
*i = interpreter.into();
|
||||
}
|
||||
assert!(!invalid.validate());
|
||||
assert!(!invalid.available_for("agent_service", &caps));
|
||||
assert!(!invalid.available_for("root", &["linux.base/1".into(), "run_script".into()]));
|
||||
}
|
||||
for profile in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!(false),
|
||||
serde_json::json!(1),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!({}),
|
||||
serde_json::json!({"powershell_51_remote_signed": null}),
|
||||
serde_json::json!("bypass"),
|
||||
serde_json::json!("RemoteSigned"),
|
||||
serde_json::json!("powershell_7_remote_signed"),
|
||||
] {
|
||||
let mut bad = serde_json::to_value(&action).unwrap();
|
||||
bad["windows_execution_profile"] = profile.clone();
|
||||
assert!(serde_json::from_value::<Action>(bad).is_err(), "{profile}");
|
||||
// An opt-in profile is also never metadata on another action.
|
||||
assert!(
|
||||
serde_json::from_value::<Action>(serde_json::json!({
|
||||
"action":"refresh_inventory", "scope":"windows.base",
|
||||
"windows_execution_profile":profile
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes() {
|
||||
let since = DateTime::parse_from_rfc3339("2026-11-14T00:00:00Z")
|
||||
.unwrap()
|
||||
.with_timezone(&Utc);
|
||||
let mut action = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since,
|
||||
until: since + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
};
|
||||
let caps: Vec<String> = [
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"query_logs",
|
||||
WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
assert!(action.validate());
|
||||
assert!(action.available_for("agent_service", &caps));
|
||||
assert!(action.valid_job_limits(10, 1024));
|
||||
assert!(action.valid_job_limits(120, 65536));
|
||||
for (runtime, bytes) in [(9, 1024), (121, 1024), (10, 1023), (10, 65537)] {
|
||||
assert!(!action.valid_job_limits(runtime, bytes));
|
||||
}
|
||||
for i in 0..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(i);
|
||||
assert!(!action.available_for("agent_service", &short));
|
||||
}
|
||||
for identity in ["root", "system", "SYSTEM"] {
|
||||
assert!(!action.available_for(identity, &caps));
|
||||
}
|
||||
let mut mixed = caps.clone();
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!action.available_for("agent_service", &mixed));
|
||||
assert!(!action.available_for("root", &["linux.base/1".into(), "query_logs".into()]));
|
||||
for unit in [
|
||||
"Application",
|
||||
"Security",
|
||||
"windows.eventlog.application.other",
|
||||
] {
|
||||
let mut wrong = action.clone();
|
||||
if let Action::QueryLogs { unit: u, .. } = &mut wrong {
|
||||
*u = unit.into();
|
||||
}
|
||||
assert!(!wrong.available_for("agent_service", &caps));
|
||||
}
|
||||
if let Action::QueryLogs { until, .. } = &mut action {
|
||||
*until += chrono::Duration::nanoseconds(1);
|
||||
}
|
||||
assert!(!action.validate());
|
||||
let linux = Action::QueryLogs {
|
||||
unit: "rmm-test.service".into(),
|
||||
since,
|
||||
until: since + chrono::Duration::hours(24),
|
||||
max_lines: 1000,
|
||||
};
|
||||
assert_eq!(
|
||||
String::from_utf8(encode(&linux).unwrap()).unwrap(),
|
||||
r#"{"action":"query_logs","unit":"rmm-test.service","since":"2026-11-14T00:00:00Z","until":"2026-11-15T00:00:00Z","max_lines":1000}"#
|
||||
);
|
||||
assert!(linux.validate());
|
||||
for identity in ["root", "agent_service"] {
|
||||
assert!(linux.available_for(identity, &["linux.base/1".into(), "query_logs".into()]));
|
||||
}
|
||||
let mut too_long = linux;
|
||||
if let Action::QueryLogs { until, .. } = &mut too_long {
|
||||
*until += chrono::Duration::minutes(59);
|
||||
}
|
||||
assert!(!too_long.validate());
|
||||
let pre_epoch = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: DateTime::from_timestamp(-1, 0).unwrap(),
|
||||
until: DateTime::from_timestamp(0, 0).unwrap(),
|
||||
max_lines: 1,
|
||||
};
|
||||
assert!(!pre_epoch.validate());
|
||||
}
|
||||
#[test]
|
||||
fn no_terminal_replay_or_unknown_restart() {
|
||||
assert!(!JobState::Succeeded.allows(JobState::Running));
|
||||
assert!(!JobState::Unknown.allows(JobState::Running));
|
||||
|
||||
@@ -4,6 +4,7 @@ pub mod checkpoint_repair;
|
||||
pub mod inventory_document;
|
||||
pub mod jobs;
|
||||
pub mod reconciliation;
|
||||
pub mod windows_execution;
|
||||
|
||||
pub const TENANT_A: &str = "11111111-1111-4111-8111-111111111111";
|
||||
pub const TENANT_B: &str = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
@@ -1,39 +1,84 @@
|
||||
//! Unexported Windows MSI fixture contract. No legacy Linux codec is changed.
|
||||
//! This version supports first installation or independently proven exact noop;
|
||||
//! an upgrade requires a separate reviewed recipe with explicit predecessor
|
||||
//! products/UpgradeCode semantics. No implicit REINSTALL flags are inferred.
|
||||
//! Windows MSI fixture contract. No legacy Linux codec is changed.
|
||||
//! Fixed1.0 first installation/noop and separate1.0→1.1 major-upgrade/noop
|
||||
//! recipes only. No implicit REINSTALL, repair, downgrade or fresh1.1 mode.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const MSI_PACKAGE_ID: &str = "rmm-windows-msi-fixture";
|
||||
pub const MSI_CAPABILITY: &str = "package.msi.fixture/1";
|
||||
pub const MSI_RECIPE_ID: &str = "rmm-windows-msi-fixture-install-1.0";
|
||||
pub const MSI_PRODUCT_CODE: &str = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}";
|
||||
pub const MSI_UPGRADE_CODE: &str = "{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}";
|
||||
pub const MSI_VERSION: &str = "1.0.0";
|
||||
pub const MSI_PAYLOAD: &str = r"C:\Program Files\RustDiscoveryFixtures\msi-payload.txt";
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub const MSI_UPGRADE_RECIPE_ID: &str = "rmm-windows-msi-fixture-upgrade-1.1";
|
||||
pub const MSI_UPGRADE_PRODUCT_CODE: &str = "{D42BD387-079B-4BBF-A134-0DA7B7A97011}";
|
||||
pub const MSI_UPGRADE_VERSION: &str = "1.1.0";
|
||||
pub const MSI_PAYLOAD_BYTES: u64 = 33;
|
||||
pub const MSI_PAYLOAD_10_SHA256: &str =
|
||||
"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0";
|
||||
pub const MSI_PAYLOAD_11_SHA256: &str =
|
||||
"ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49";
|
||||
pub const MSI_OLD_PRODUCTS: &str = "RMM_OLD_PRODUCTS";
|
||||
pub const MSI_ALL_PRODUCTS: &str = "RMM_ALL_PRODUCTS";
|
||||
pub const MSI_UPGRADE_CONDITION: &str = "Installed OR (RMM_OLD_PRODUCTS = \"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\" AND RMM_ALL_PRODUCTS = \"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\")";
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Architecture {
|
||||
X64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum InstallContext {
|
||||
Machine,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, schemars::JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MsiCommandProfile {
|
||||
FixtureQuietNoRebootV1,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
impl<'de> Deserialize<'de> for Architecture {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = String::deserialize(deserializer)?;
|
||||
if value == "x64" {
|
||||
Ok(Self::X64)
|
||||
} else {
|
||||
Err(serde::de::Error::unknown_variant(&value, &["x64"]))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for InstallContext {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = String::deserialize(deserializer)?;
|
||||
if value == "machine" {
|
||||
Ok(Self::Machine)
|
||||
} else {
|
||||
Err(serde::de::Error::unknown_variant(&value, &["machine"]))
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<'de> Deserialize<'de> for MsiCommandProfile {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let value = String::deserialize(deserializer)?;
|
||||
if value == "fixture_quiet_no_reboot_v1" {
|
||||
Ok(Self::FixtureQuietNoRebootV1)
|
||||
} else {
|
||||
Err(serde::de::Error::unknown_variant(
|
||||
&value,
|
||||
&["fixture_quiet_no_reboot_v1"],
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MsiArtifact {
|
||||
pub artifact_id: Uuid,
|
||||
pub sha256: String,
|
||||
pub bytes: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MsiPostcondition {
|
||||
pub product_code: String,
|
||||
@@ -42,7 +87,7 @@ pub struct MsiPostcondition {
|
||||
pub payload_sha256: String,
|
||||
pub payload_bytes: u64,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WindowsMsiRecipe {
|
||||
pub schema_version: u32,
|
||||
@@ -56,8 +101,13 @@ pub struct WindowsMsiRecipe {
|
||||
pub artifact: MsiArtifact,
|
||||
pub postcondition: MsiPostcondition,
|
||||
pub no_reboot: bool,
|
||||
// Appended opt-in metadata: old1.0 recipes retain exactly their old bytes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub package_code: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub predecessor: Option<MsiPostcondition>,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ResolvedWindowsMsi {
|
||||
pub recipe: WindowsMsiRecipe,
|
||||
@@ -70,10 +120,16 @@ pub fn digest(value: &str) -> bool {
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
|
||||
}
|
||||
pub fn valid_package_code(value: &str) -> bool {
|
||||
Uuid::parse_str(value).is_ok_and(|id| {
|
||||
!id.is_nil()
|
||||
&& value == format!("{{{}}}", id.to_string().to_uppercase())
|
||||
&& ![MSI_PRODUCT_CODE, MSI_UPGRADE_PRODUCT_CODE, MSI_UPGRADE_CODE].contains(&value)
|
||||
})
|
||||
}
|
||||
impl WindowsMsiRecipe {
|
||||
pub fn validate(&self) -> bool {
|
||||
self.schema_version == 1
|
||||
&& self.recipe_id == MSI_RECIPE_ID
|
||||
&& self.recipe_version == "1"
|
||||
&& self.platform == "windows"
|
||||
&& self.upgrade_code == MSI_UPGRADE_CODE
|
||||
@@ -81,11 +137,32 @@ impl WindowsMsiRecipe {
|
||||
&& !self.artifact.artifact_id.is_nil()
|
||||
&& digest(&self.artifact.sha256)
|
||||
&& (1..=262144).contains(&self.artifact.bytes)
|
||||
&& self.postcondition.product_code == MSI_PRODUCT_CODE
|
||||
&& self.postcondition.product_version == MSI_VERSION
|
||||
&& self.postcondition.payload_path == MSI_PAYLOAD
|
||||
&& digest(&self.postcondition.payload_sha256)
|
||||
&& (1..=65536).contains(&self.postcondition.payload_bytes)
|
||||
&& match self.recipe_id.as_str() {
|
||||
MSI_RECIPE_ID => {
|
||||
self.postcondition.product_code == MSI_PRODUCT_CODE
|
||||
&& self.postcondition.product_version == MSI_VERSION
|
||||
&& self.package_code.is_none()
|
||||
&& self.predecessor.is_none()
|
||||
}
|
||||
MSI_UPGRADE_RECIPE_ID => {
|
||||
self.postcondition.product_code == MSI_UPGRADE_PRODUCT_CODE
|
||||
&& self.postcondition.product_version == MSI_UPGRADE_VERSION
|
||||
&& self.postcondition.payload_sha256 == MSI_PAYLOAD_11_SHA256
|
||||
&& self.postcondition.payload_bytes == MSI_PAYLOAD_BYTES
|
||||
&& self.package_code.as_deref().is_some_and(valid_package_code)
|
||||
&& self.predecessor.as_ref().is_some_and(|old| {
|
||||
old.product_code == MSI_PRODUCT_CODE
|
||||
&& old.product_version == MSI_VERSION
|
||||
&& old.payload_path == MSI_PAYLOAD
|
||||
&& old.payload_sha256 == MSI_PAYLOAD_10_SHA256
|
||||
&& old.payload_bytes == MSI_PAYLOAD_BYTES
|
||||
})
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
pub fn sha256(&self) -> Result<String, serde_json::Error> {
|
||||
Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(self)?)))
|
||||
@@ -127,6 +204,156 @@ mod tests {
|
||||
payload_bytes: 20,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: None,
|
||||
predecessor: None,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn ensure_msi_action_is_strict_opt_in_and_system_windows_only_without_linux_byte_changes() {
|
||||
use crate::jobs::{Action, encode};
|
||||
let old=br#"{"action":"ensure_package","provider":"apt","package":"rmm-test","version":"1.0","architecture":"amd64","recipe_version":"1","installation_context":"system"}"#;
|
||||
let legacy: Action = serde_json::from_slice(old).unwrap();
|
||||
assert!(legacy.validate_plan_shape());
|
||||
assert!(legacy.windows_msi().is_none());
|
||||
assert_eq!(encode(&legacy).unwrap(), old);
|
||||
let recipe = recipe();
|
||||
let m = ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
};
|
||||
let action = Action::EnsurePackage {
|
||||
provider: "msi".into(),
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: MSI_VERSION.into(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: "1".into(),
|
||||
installation_context: "machine".into(),
|
||||
recipe_id: Some(MSI_RECIPE_ID.into()),
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: Some(Box::new(m)),
|
||||
};
|
||||
assert!(action.validate());
|
||||
assert!(action.valid_helper_denial_shape("system"));
|
||||
assert!(!action.valid_helper_denial_shape("root"));
|
||||
let caps: Vec<String> = [
|
||||
"ensure_package",
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.system.v1",
|
||||
"system:ensure_package",
|
||||
MSI_CAPABILITY,
|
||||
]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
assert!(action.available_for("system", &caps));
|
||||
for identity in ["root", "agent_service"] {
|
||||
assert!(!action.available_for(identity, &caps));
|
||||
}
|
||||
for i in 0..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(i);
|
||||
assert!(!action.available_for("system", &short));
|
||||
}
|
||||
let mut mixed = caps;
|
||||
mixed.push("linux.base/1".into());
|
||||
assert!(!action.available_for("system", &mixed));
|
||||
for (key, value) in [
|
||||
("provider", serde_json::json!("apt")),
|
||||
("architecture", serde_json::json!("amd64")),
|
||||
("installation_context", serde_json::json!("system")),
|
||||
("version", serde_json::json!("1.1.0")),
|
||||
] {
|
||||
let mut bad = serde_json::to_value(&action).unwrap();
|
||||
bad[key] = value;
|
||||
assert!(!serde_json::from_value::<Action>(bad).unwrap().validate());
|
||||
}
|
||||
for value in [
|
||||
serde_json::Value::Null,
|
||||
serde_json::json!(false),
|
||||
serde_json::json!(1),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!({}),
|
||||
] {
|
||||
let mut bad = serde_json::to_value(&action).unwrap();
|
||||
bad["windows_msi_manifest"] = value;
|
||||
assert!(serde_json::from_value::<Action>(bad).is_err());
|
||||
}
|
||||
for (key, value) in [
|
||||
("architecture", "x64"),
|
||||
("context", "machine"),
|
||||
("command_profile", "fixture_quiet_no_reboot_v1"),
|
||||
] {
|
||||
let mut bad = serde_json::to_value(&action).unwrap();
|
||||
bad["windows_msi_manifest"]["recipe"][key] = serde_json::json!({value:null});
|
||||
assert!(serde_json::from_value::<Action>(bad).is_err());
|
||||
}
|
||||
for (runtime, bytes) in [(9, 4096), (121, 4096), (10, 1023), (10, 65537)] {
|
||||
assert!(!action.valid_job_limits(runtime, bytes));
|
||||
}
|
||||
let schema = schemars::schema_for!(Action).to_value();
|
||||
let pkg = schema["oneOf"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|v| v["properties"].get("windows_msi_manifest").is_some())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
pkg["properties"]["windows_msi_manifest"],
|
||||
serde_json::json!({"$ref":"#/$defs/ResolvedWindowsMsi"})
|
||||
);
|
||||
assert!(
|
||||
!pkg["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&serde_json::json!("windows_msi_manifest"))
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn major_upgrade_requires_explicit_exact_predecessor_new_package_and_same_family() {
|
||||
let old = recipe();
|
||||
let old_bytes = serde_json::to_vec(&old).unwrap();
|
||||
assert!(
|
||||
!String::from_utf8(old_bytes.clone())
|
||||
.unwrap()
|
||||
.contains("predecessor")
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_vec(&serde_json::from_slice::<WindowsMsiRecipe>(&old_bytes).unwrap())
|
||||
.unwrap(),
|
||||
old_bytes
|
||||
);
|
||||
let mut r = old.clone();
|
||||
r.recipe_id = MSI_UPGRADE_RECIPE_ID.into();
|
||||
r.package_code = Some("{8475C4D1-6EE2-4C3A-B41D-D834A20F4135}".into());
|
||||
r.postcondition.product_code = MSI_UPGRADE_PRODUCT_CODE.into();
|
||||
r.postcondition.product_version = MSI_UPGRADE_VERSION.into();
|
||||
r.postcondition.payload_sha256 = MSI_PAYLOAD_11_SHA256.into();
|
||||
r.postcondition.payload_bytes = MSI_PAYLOAD_BYTES;
|
||||
r.predecessor = Some(MsiPostcondition {
|
||||
product_code: MSI_PRODUCT_CODE.into(),
|
||||
product_version: MSI_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
});
|
||||
assert!(r.validate());
|
||||
assert_ne!(r.sha256().unwrap(), old.sha256().unwrap());
|
||||
for case in 0..8 {
|
||||
let mut bad = r.clone();
|
||||
match case {
|
||||
0 => bad.predecessor = None,
|
||||
1 => bad.package_code = None,
|
||||
2 => bad.package_code = Some(MSI_PRODUCT_CODE.into()),
|
||||
3 => bad.upgrade_code = Uuid::new_v4().to_string(),
|
||||
4 => {
|
||||
bad.predecessor.as_mut().unwrap().product_code = MSI_UPGRADE_PRODUCT_CODE.into()
|
||||
}
|
||||
5 => bad.predecessor.as_mut().unwrap().payload_sha256 = "aa".repeat(32),
|
||||
6 => bad.postcondition.product_version = "1.2.0".into(),
|
||||
_ => bad.postcondition.payload_sha256 = MSI_PAYLOAD_10_SHA256.into(),
|
||||
};
|
||||
assert!(!bad.validate());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
|
||||
@@ -481,6 +481,7 @@ fn signed_request() -> (
|
||||
script_utf8: "true".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now - chrono::Duration::seconds(1),
|
||||
|
||||
@@ -130,6 +130,7 @@ pub fn script(job: &JobPayload) -> Result<Outcome> {
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile: None,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("NOT_SCRIPT")
|
||||
|
||||
@@ -750,6 +750,7 @@ mod tests {
|
||||
script_utf8: "true".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -33,6 +33,7 @@ fn fixture() -> (
|
||||
script_utf8: "printf 'Hello World\\n'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("Hello World\n".into()),
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now - chrono::Duration::seconds(60),
|
||||
|
||||
@@ -432,6 +432,7 @@ fn script() -> Action {
|
||||
script_utf8: "printf hello".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: Some("hello".into()),
|
||||
windows_execution_profile: None,
|
||||
}
|
||||
}
|
||||
fn success() -> ReconciledOutcome {
|
||||
|
||||
@@ -36,13 +36,20 @@ 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,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,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") {
|
||||
return Err(Error(StatusCode::CONFLICT, "PLAN_HASH_MISMATCH"));
|
||||
}
|
||||
let plan: PlanPayload = serde_json::from_slice(&plan_bytes)?;
|
||||
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?;
|
||||
}
|
||||
|
||||
if job.asset_id != row.get::<Uuid, _>("asset_id")
|
||||
|| job.enrollment_generation != row.get::<i64, _>("enrollment_generation") as u64
|
||||
|| job.assignment_version != row.get::<i64, _>("assignment_version") as u64
|
||||
|
||||
@@ -24,6 +24,10 @@ pub struct AptRecipe {
|
||||
}
|
||||
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
|
||||
r.route(
|
||||
"/api/v1/tenants/{tenant}/windows-msi-recipes",
|
||||
get(crate::windows_msi_catalog::list).post(crate::windows_msi_catalog::import),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/package-recipes",
|
||||
get(list).post(import),
|
||||
)
|
||||
@@ -43,6 +47,15 @@ pub async fn references(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
action: &rmm_domain::jobs::Action,
|
||||
) -> Result<Vec<rmm_domain::jobs::RecipeReference>, Error> {
|
||||
if let Some(manifest) = action.windows_msi() {
|
||||
if !action.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
return crate::windows_msi_catalog::references(tx, manifest).await;
|
||||
}
|
||||
let manifest = match action {
|
||||
rmm_domain::jobs::Action::EnsurePackage {
|
||||
apt_manifest: Some(m),
|
||||
@@ -138,7 +151,7 @@ pub async fn references(
|
||||
references.dedup();
|
||||
Ok(references)
|
||||
}
|
||||
async fn context<'a>(
|
||||
pub(crate) async fn context<'a>(
|
||||
s: &'a crate::State,
|
||||
h: &HeaderMap,
|
||||
t: Uuid,
|
||||
@@ -182,6 +195,7 @@ pub async fn import(
|
||||
installation_context: recipe.installation_context.clone(),
|
||||
recipe_id: None,
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: None,
|
||||
};
|
||||
if recipe.schema_version != 1
|
||||
|| recipe.reboot_policy != "never"
|
||||
|
||||
@@ -518,6 +518,7 @@ mod tests {
|
||||
script_utf8: "printf hello\\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: c.issued_at,
|
||||
|
||||
@@ -191,6 +191,8 @@ pub async fn event(
|
||||
ensure!(r.stdout == expected.as_bytes(), "expected output mismatch");
|
||||
}
|
||||
}
|
||||
script_profile_evidence(&payload.action, &evidence)?;
|
||||
windows_event_log_success_evidence(&payload, r, &evidence)?;
|
||||
if matches!(payload.action, Action::Reboot { .. }) {
|
||||
crate::synchronization::verify_reboot_success(
|
||||
tx, tenant, agent, e, &payload, r, &evidence,
|
||||
@@ -224,6 +226,226 @@ pub async fn event(
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
fn windows_event_log_success_evidence(
|
||||
job: &JobPayload,
|
||||
result: &JobResult,
|
||||
evidence: &Value,
|
||||
) -> Result<()> {
|
||||
if !job.action.is_windows_event_log_fixture() {
|
||||
return Ok(());
|
||||
}
|
||||
let Action::QueryLogs {
|
||||
unit,
|
||||
since,
|
||||
until,
|
||||
max_lines,
|
||||
} = &job.action
|
||||
else {
|
||||
anyhow::bail!("fixed event log action required")
|
||||
};
|
||||
let observed_since: chrono::DateTime<Utc> = serde_json::from_value(
|
||||
evidence
|
||||
.get("start_utc")
|
||||
.cloned()
|
||||
.context("event log start missing")?,
|
||||
)?;
|
||||
let observed_until: chrono::DateTime<Utc> = serde_json::from_value(
|
||||
evidence
|
||||
.get("end_utc")
|
||||
.cloned()
|
||||
.context("event log end missing")?,
|
||||
)?;
|
||||
let complete = evidence.get("completeness") == Some(&json!("complete"))
|
||||
&& evidence.get("truncated") == Some(&json!(false))
|
||||
&& evidence.get("error_code") == Some(&Value::Null);
|
||||
let partial = evidence.get("completeness") == Some(&json!("partial"))
|
||||
&& evidence.get("truncated") == Some(&json!(true))
|
||||
&& matches!(
|
||||
evidence.get("error_code").and_then(Value::as_str),
|
||||
Some("EVENT_LOG_EVENT_LIMIT" | "EVENT_LOG_BYTE_LIMIT" | "EVENT_LOG_EVENT_SIZE_LIMIT")
|
||||
);
|
||||
ensure!(
|
||||
!result.reboot_required
|
||||
&& evidence.get("truncated") == Some(&json!(result.output_truncated))
|
||||
&& job.execution_identity == "agent_service"
|
||||
&& job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& evidence.get("source_id") == Some(&json!(unit))
|
||||
&& evidence.get("channel") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_CHANNEL))
|
||||
&& evidence.get("provider") == Some(&json!(WINDOWS_EVENT_LOG_FIXTURE_PROVIDER))
|
||||
&& observed_since == *since
|
||||
&& observed_until == *until
|
||||
&& evidence.get("max_events") == Some(&json!(max_lines))
|
||||
&& evidence.get("max_output_bytes") == Some(&json!(job.max_output_bytes))
|
||||
&& evidence.get("quality") == Some(&json!("valid"))
|
||||
&& evidence.get("win32_error") == Some(&Value::Null)
|
||||
&& evidence.get("bookmark_updated") == Some(&json!(false))
|
||||
&& evidence.get("process_tree_bounded") == Some(&json!(true))
|
||||
&& evidence.get("execution_sid") == Some(&json!("S-1-5-19"))
|
||||
&& (complete || partial),
|
||||
"fixed Windows Event Log evidence mismatch"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The profile records the requested process option, never an effective GPO policy.
|
||||
fn script_profile_evidence(action: &Action, evidence: &Value) -> Result<()> {
|
||||
if let Action::RunScript {
|
||||
script_utf8,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
..
|
||||
} = action
|
||||
{
|
||||
ensure!(
|
||||
evidence.get("windows_execution_profile")
|
||||
== Some(&json!("powershell_51_remote_signed"))
|
||||
&& evidence.get("execution_policy")
|
||||
== Some(&json!("process_remote_signed_requested"))
|
||||
&& evidence.get("execution_policy_requested") == Some(&json!("RemoteSigned"))
|
||||
&& evidence.get("execution_policy_scope") == Some(&json!("process"))
|
||||
&& evidence.get("script_sha256") == Some(&json!(hash(script_utf8.as_bytes()))),
|
||||
"requested Windows process profile evidence mismatch"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod script_profile_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn windows_event_log_success_binds_request_and_keeps_limit_partial_honest() {
|
||||
let id = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
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: Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
},
|
||||
execution_identity: "agent_service".into(),
|
||||
not_before: now,
|
||||
start_before: now + Duration::minutes(1),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let evidence = json!({"source_id":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"channel":"Application","provider":"RustDiscovery-MVP-Test","start_utc":now-Duration::hours(1),"end_utc":now,"max_events":1000,"max_output_bytes":4096,"quality":"valid","completeness":"complete","truncated":false,"error_code":null,"win32_error":null,"bookmark_updated":false,"process_tree_bounded":true,"execution_sid":"S-1-5-19"});
|
||||
let result = JobResult::default();
|
||||
windows_event_log_success_evidence(&job, &result, &evidence).unwrap();
|
||||
for conflicting in [
|
||||
JobResult {
|
||||
reboot_required: true,
|
||||
..Default::default()
|
||||
},
|
||||
JobResult {
|
||||
output_truncated: true,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
assert!(windows_event_log_success_evidence(&job, &conflicting, &evidence).is_err());
|
||||
}
|
||||
for field in [
|
||||
"source_id",
|
||||
"channel",
|
||||
"provider",
|
||||
"start_utc",
|
||||
"end_utc",
|
||||
"max_events",
|
||||
"max_output_bytes",
|
||||
"quality",
|
||||
"win32_error",
|
||||
"bookmark_updated",
|
||||
"process_tree_bounded",
|
||||
"execution_sid",
|
||||
] {
|
||||
let mut bad = evidence.clone();
|
||||
bad[field] = json!("different");
|
||||
assert!(
|
||||
windows_event_log_success_evidence(&job, &result, &bad).is_err(),
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
for code in [
|
||||
"EVENT_LOG_EVENT_LIMIT",
|
||||
"EVENT_LOG_BYTE_LIMIT",
|
||||
"EVENT_LOG_EVENT_SIZE_LIMIT",
|
||||
] {
|
||||
let mut partial = evidence.clone();
|
||||
partial["completeness"] = json!("partial");
|
||||
partial["truncated"] = json!(true);
|
||||
partial["error_code"] = json!(code);
|
||||
let partial_result = JobResult {
|
||||
output_truncated: true,
|
||||
..Default::default()
|
||||
};
|
||||
windows_event_log_success_evidence(&job, &partial_result, &partial).unwrap();
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &partial).is_err());
|
||||
partial["error_code"] = json!("EVENT_LOG_TIMEOUT");
|
||||
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
|
||||
partial["quality"] = json!("permission_denied");
|
||||
assert!(windows_event_log_success_evidence(&job, &partial_result, &partial).is_err());
|
||||
}
|
||||
let mut permission_denied = evidence.clone();
|
||||
permission_denied["win32_error"] = json!(5);
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &permission_denied).is_err());
|
||||
let mut false_complete = evidence.clone();
|
||||
false_complete["truncated"] = json!(true);
|
||||
assert!(windows_event_log_success_evidence(&job, &result, &false_complete).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn requested_profile_success_evidence_is_exact_without_effective_policy_claim() {
|
||||
let mut action = Action::RunScript {
|
||||
interpreter: "powershell".into(),
|
||||
script_utf8: "Write-Output 'hi'\r\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
};
|
||||
let evidence = json!({"windows_execution_profile":"powershell_51_remote_signed",
|
||||
"execution_policy":"process_remote_signed_requested", "execution_policy_requested":"RemoteSigned",
|
||||
"execution_policy_scope":"process", "script_sha256":hash(b"Write-Output 'hi'\r\n")});
|
||||
script_profile_evidence(&action, &evidence).unwrap();
|
||||
for field in [
|
||||
"windows_execution_profile",
|
||||
"execution_policy",
|
||||
"execution_policy_requested",
|
||||
"execution_policy_scope",
|
||||
"script_sha256",
|
||||
] {
|
||||
let mut changed = evidence.clone();
|
||||
changed.as_object_mut().unwrap().remove(field);
|
||||
assert!(
|
||||
script_profile_evidence(&action, &changed).is_err(),
|
||||
"{field}"
|
||||
);
|
||||
changed[field] = json!("different");
|
||||
assert!(
|
||||
script_profile_evidence(&action, &changed).is_err(),
|
||||
"{field}"
|
||||
);
|
||||
}
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut action
|
||||
{
|
||||
*windows_execution_profile = None;
|
||||
}
|
||||
script_profile_evidence(&action, &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn locked_job(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
agent: Uuid,
|
||||
@@ -269,6 +491,9 @@ pub async fn permit(
|
||||
let payload: JobPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("payload"))?;
|
||||
let plan: PlanPayload = serde_json::from_slice(&row.get::<Vec<u8>, _>("plan_payload"))?;
|
||||
let capabilities: Vec<String> = serde_json::from_value(row.get("capabilities"))?;
|
||||
if crate::windows_msi_catalog::validate_job_binding(&plan, &payload).is_err() {
|
||||
return Ok(denied("WINDOWS_MSI_BINDING_MISMATCH"));
|
||||
}
|
||||
if row.get::<Uuid, _>("bound_asset") != payload.asset_id
|
||||
|| !payload
|
||||
.action
|
||||
@@ -314,6 +539,12 @@ pub async fn permit(
|
||||
return Ok(denied("BINDING_MISMATCH"));
|
||||
}
|
||||
let now = Utc::now();
|
||||
if !payload
|
||||
.action
|
||||
.valid_job_limits(payload.max_runtime_seconds, payload.max_output_bytes)
|
||||
{
|
||||
return Ok(denied("INVALID_JOB_LIMITS"));
|
||||
}
|
||||
if !payload.action.validate() {
|
||||
return Ok(denied("APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
@@ -508,9 +739,26 @@ pub async fn next(
|
||||
};
|
||||
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() {
|
||||
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()
|
||||
|| crate::catalog::check(&mut tx, &payload.action)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tx.commit().await?;
|
||||
return Ok(None);
|
||||
}
|
||||
}
|
||||
|
||||
if !payload
|
||||
.action
|
||||
.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);
|
||||
|
||||
+521
-2
@@ -151,6 +151,13 @@ pub struct Variant {
|
||||
interpreter: String,
|
||||
encoding: String,
|
||||
script_utf8: String,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_execution_profile",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
#[schemars(with = "WindowsExecutionProfile")]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -174,6 +181,12 @@ struct WebParameters {
|
||||
recipe_version: Option<String>,
|
||||
recipe_id: Option<String>,
|
||||
apt_manifest: Option<rmm_domain::apt_transaction::AptExecutionManifest>,
|
||||
#[serde(
|
||||
default,
|
||||
deserialize_with = "rmm_domain::jobs::deserialize_windows_msi_manifest"
|
||||
)]
|
||||
#[schemars(with = "rmm_domain::windows_execution::ResolvedWindowsMsi")]
|
||||
windows_msi_manifest: Option<Box<rmm_domain::windows_execution::ResolvedWindowsMsi>>,
|
||||
installation_context: Option<String>,
|
||||
packages: Option<Vec<String>>,
|
||||
reboot_policy: Option<String>,
|
||||
@@ -198,6 +211,9 @@ impl PlanRequest {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let p = w.parameters;
|
||||
if p.windows_msi_manifest.is_some() && w.action != "ensure_package" {
|
||||
return Err(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
}
|
||||
let required =
|
||||
|value: Option<String>| value.ok_or(Error(StatusCode::BAD_REQUEST, "VALIDATION_ERROR"));
|
||||
let action = match w.action.as_str() {
|
||||
@@ -213,6 +229,7 @@ impl PlanRequest {
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: p.arguments.clone().unwrap_or_default(),
|
||||
expected_stdout: p.expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
}
|
||||
}
|
||||
"refresh_inventory" => Action::RefreshInventory {
|
||||
@@ -243,6 +260,7 @@ impl PlanRequest {
|
||||
installation_context: required(p.installation_context)?,
|
||||
recipe_id: p.recipe_id,
|
||||
apt_manifest: p.apt_manifest,
|
||||
windows_msi_manifest: p.windows_msi_manifest,
|
||||
},
|
||||
"apply_updates" => Action::ApplyUpdates {
|
||||
provider: required(p.provider)?,
|
||||
@@ -310,6 +328,7 @@ fn validate_variants(variants: &[Variant]) -> Result<()> {
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
};
|
||||
if v.encoding != "utf-8"
|
||||
|| action.script_platform() != Some(v.os_family.as_str())
|
||||
@@ -336,12 +355,21 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
script_utf8,
|
||||
arguments,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
} = &input.action
|
||||
else {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
};
|
||||
let first = &input.script_variants[0];
|
||||
if interpreter != &first.interpreter || script_utf8 != &first.script_utf8 {
|
||||
if interpreter != &first.interpreter
|
||||
|| script_utf8 != &first.script_utf8
|
||||
|| windows_execution_profile != &first.windows_execution_profile
|
||||
|| (input.execution_identity != "agent_service"
|
||||
&& input
|
||||
.script_variants
|
||||
.iter()
|
||||
.any(|v| v.windows_execution_profile.is_some()))
|
||||
{
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
let platform = match (
|
||||
@@ -362,6 +390,7 @@ fn target_action(input: &PlanInput, caps: &[String]) -> Result<Action> {
|
||||
script_utf8: v.script_utf8.clone(),
|
||||
arguments: arguments.clone(),
|
||||
expected_stdout: expected_stdout.clone(),
|
||||
windows_execution_profile: v.windows_execution_profile,
|
||||
})
|
||||
}
|
||||
async fn policy(tx: &mut Transaction<'_, Postgres>) -> Result<()> {
|
||||
@@ -416,6 +445,14 @@ pub async fn plan(
|
||||
{
|
||||
return Err(Error(StatusCode::FORBIDDEN, "ROOT_IDENTITY_REQUIRED"));
|
||||
}
|
||||
if input.action.windows_msi().is_some()
|
||||
&& (input.execution_identity != "system" || !input.artifact_ids.is_empty())
|
||||
{
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED",
|
||||
));
|
||||
}
|
||||
// Conservative policy: reboot is always serial, no provider-triggered reboot.
|
||||
if matches!(input.action, Action::Reboot { .. }) && input.rollout.max_parallel != 1 {
|
||||
return Err(fail("POLICY_DENIED"));
|
||||
@@ -439,7 +476,11 @@ pub async fn plan(
|
||||
crate::permissions::require_principal(&mut tx, p, "logs:read").await?;
|
||||
}
|
||||
let recipe_references = crate::catalog::references(&mut tx, &input.action).await?;
|
||||
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
||||
let artifacts = if input.action.windows_msi().is_some() {
|
||||
crate::windows_msi_catalog::automatic_artifacts(&mut tx, tenant, &input.action).await?
|
||||
} else {
|
||||
crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?
|
||||
};
|
||||
let mut jobs = Vec::new();
|
||||
for asset in ids {
|
||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||
@@ -453,6 +494,9 @@ pub async fn plan(
|
||||
let row = &rows[0];
|
||||
let caps = capabilities(row.get("capabilities"))?;
|
||||
let action = target_action(&input, &caps)?;
|
||||
if !action.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes) {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if !action.available_for(&input.execution_identity, &caps) {
|
||||
return Err(fail("UNSUPPORTED_CAPABILITY"));
|
||||
}
|
||||
@@ -509,6 +553,7 @@ pub async fn plan(
|
||||
recipe_references,
|
||||
artifact_references,
|
||||
};
|
||||
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
|
||||
let bytes = encode(&payload)?;
|
||||
let plan_hash = hash(&bytes);
|
||||
sqlx::query("INSERT INTO operation_plans(tenant_id,plan_id,principal,payload,plan_hash,expires_at) VALUES($1,$2,$3,$4,$5,$6)").bind(tenant).bind(payload.plan_id).bind(&p.name).bind(&bytes).bind(&plan_hash).bind(input.schedule.start_before).execute(&mut *tx).await?;
|
||||
@@ -543,6 +588,7 @@ async fn load_plan(
|
||||
Ok((serde_json::from_slice(&bytes)?, h, bytes))
|
||||
}
|
||||
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
|
||||
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
|
||||
policy(tx).await?;
|
||||
let current_artifacts = crate::catalog::resolve_artifacts(
|
||||
tx,
|
||||
@@ -580,6 +626,12 @@ async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Resu
|
||||
}
|
||||
let mut references = Vec::new();
|
||||
for job in &plan.jobs {
|
||||
if !job.payload.action.valid_job_limits(
|
||||
job.payload.max_runtime_seconds,
|
||||
job.payload.max_output_bytes,
|
||||
) {
|
||||
return Err(fail("VALIDATION_ERROR"));
|
||||
}
|
||||
if !job.payload.action.validate() {
|
||||
return Err(Error(StatusCode::CONFLICT, "APT_MANIFEST_REQUIRED"));
|
||||
}
|
||||
@@ -1004,6 +1056,7 @@ async fn operations_http(
|
||||
#[cfg(test)]
|
||||
mod windows_contract_tests {
|
||||
use super::*;
|
||||
use chrono::Duration;
|
||||
fn input() -> PlanInput {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
@@ -1035,6 +1088,111 @@ mod windows_contract_tests {
|
||||
i.script_variants.remove(1);
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn fixed_windows_log_web_contract_denies_extra_source_parameters() {
|
||||
let tenant = Uuid::new_v4();
|
||||
let now = Utc::now();
|
||||
let value = json!({"tenant_id":tenant,"action":"query_logs","targets":{"asset_ids":[Uuid::new_v4()]},"parameters":{"execution_identity":"agent_service","timeout_seconds":30,"max_output_bytes":4096,"unit":WINDOWS_EVENT_LOG_FIXTURE_SOURCE,"since":now-Duration::hours(1),"until":now,"max_lines":1000},"schedule":{"not_before":now,"start_before":now+Duration::minutes(10),"offline_policy":"wait_until_deadline"},"rollout":{"max_parallel":1,"halt_after_failures":1},"reason":"fixed source"});
|
||||
let input = serde_json::from_value::<PlanRequest>(value.clone())
|
||||
.unwrap()
|
||||
.resolve(tenant)
|
||||
.unwrap();
|
||||
assert!(input.action.is_windows_event_log_fixture());
|
||||
assert!(input.action.validate());
|
||||
assert!(
|
||||
input
|
||||
.action
|
||||
.valid_job_limits(input.max_runtime_seconds, input.max_output_bytes)
|
||||
);
|
||||
assert!(input.script_variants.is_empty());
|
||||
for field in ["channel", "provider", "xpath", "bookmark"] {
|
||||
let mut bad = value.clone();
|
||||
bad["parameters"][field] = json!("arbitrary");
|
||||
assert!(
|
||||
serde_json::from_value::<PlanRequest>(bad)
|
||||
.map(|request| request.resolve(tenant).is_err())
|
||||
.unwrap_or(true)
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn remote_signed_fixed_variants_bind_profile_without_linux_inheritance() {
|
||||
let mut i = input();
|
||||
let legacy_linux = encode(&i.action).unwrap();
|
||||
i.script_variants[1].windows_execution_profile =
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
assert_eq!(
|
||||
encode(&target_action(&i, &["linux.base/1".into()]).unwrap()).unwrap(),
|
||||
legacy_linux
|
||||
);
|
||||
let windows = target_action(&i, &["windows.base/1".into()]).unwrap();
|
||||
assert!(matches!(
|
||||
windows,
|
||||
Action::RunScript {
|
||||
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
|
||||
..
|
||||
}
|
||||
));
|
||||
assert!(!windows.available_for(
|
||||
"agent_service",
|
||||
&[
|
||||
"windows.base/1".into(),
|
||||
"rmm.sync.v1".into(),
|
||||
"run_script".into(),
|
||||
"script.powershell/1".into()
|
||||
]
|
||||
));
|
||||
for identity in ["root", "system"] {
|
||||
i.execution_identity = identity.into();
|
||||
assert!(target_action(&i, &["linux.base/1".into()]).is_err());
|
||||
}
|
||||
i.execution_identity = "agent_service".into();
|
||||
// Even the first Action must match the optional profile byte-for-byte.
|
||||
i.script_variants.reverse();
|
||||
i.action = windows;
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_ok());
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut i.action
|
||||
{
|
||||
*windows_execution_profile = None;
|
||||
}
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
i.script_variants[1].windows_execution_profile =
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
assert!(validate_variants(&i.script_variants).is_err());
|
||||
let schema = schemars::schema_for!(Variant).to_value();
|
||||
assert_eq!(
|
||||
schema["properties"]["windows_execution_profile"],
|
||||
json!({"$ref":"#/$defs/WindowsExecutionProfile"})
|
||||
);
|
||||
assert!(
|
||||
!schema["required"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("windows_execution_profile"))
|
||||
);
|
||||
assert_eq!(schema["$defs"]["WindowsExecutionProfile"]["type"], "string");
|
||||
let legacy = json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi"});
|
||||
let inherited: Variant = serde_json::from_value(legacy.clone()).unwrap();
|
||||
assert!(inherited.windows_execution_profile.is_none());
|
||||
assert_eq!(serde_json::to_value(inherited).unwrap(), legacy);
|
||||
for profile in [
|
||||
Value::Null,
|
||||
json!(false),
|
||||
json!(1),
|
||||
json!([]),
|
||||
json!({}),
|
||||
json!({"powershell_51_remote_signed":null}),
|
||||
json!("bypass"),
|
||||
json!("powershell_7_remote_signed"),
|
||||
] {
|
||||
assert!(serde_json::from_value::<Variant>(json!({"os_family":"windows", "interpreter":"powershell", "encoding":"utf-8", "script_utf8":"hi", "windows_execution_profile":profile})).is_err());
|
||||
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":profile})).is_err());
|
||||
}
|
||||
assert!(serde_json::from_value::<WebParameters>(json!({"execution_identity":"agent_service", "timeout_seconds":60, "max_output_bytes":4096, "windows_execution_profile":"powershell_51_remote_signed"})).is_err());
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "requires dedicated isolated PostgreSQL; tests/windows_plan_database.py"]
|
||||
async fn windows_plan_caps_persisted_database() {
|
||||
@@ -1175,6 +1333,75 @@ mod windows_contract_tests {
|
||||
"PLAN_HASH_MISMATCH"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
// A process-profile plan needs the additional current capability. Its
|
||||
// presence is rechecked at submit/approval just like interpreter support.
|
||||
let mut profiled = request.clone();
|
||||
profiled.script_variants[1].windows_execution_profile =
|
||||
Some(WindowsExecutionProfile::PowerShell51RemoteSigned);
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, profiled.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
let mut profile_caps = windows_caps.as_array().unwrap().clone();
|
||||
profile_caps.push(json!("script.powershell.process_remote_signed/1"));
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(profile_caps))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let view = plan(&state, &principal, tenant, profiled).await.unwrap();
|
||||
let profile_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let bytes: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(profile_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &profile_bound).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
let mut changed = profile_bound.clone();
|
||||
let windows_job = changed
|
||||
.jobs
|
||||
.iter_mut()
|
||||
.find(|j| j.payload.asset_id == assets[1])
|
||||
.unwrap();
|
||||
if let Action::RunScript {
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &mut windows_job.payload.action
|
||||
{
|
||||
*windows_execution_profile = None;
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &changed).await.unwrap_err().1,
|
||||
"PLAN_HASH_MISMATCH"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(&windows_caps)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &profile_bound).await.unwrap_err().1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
request.script_variants.clear();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, request.clone())
|
||||
@@ -1198,6 +1425,298 @@ mod windows_contract_tests {
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let now = Utc::now();
|
||||
let mut logs = input();
|
||||
logs.targets.asset_ids = vec![assets[1]];
|
||||
logs.script_variants.clear();
|
||||
logs.max_runtime_seconds = 30;
|
||||
logs.action = Action::QueryLogs {
|
||||
unit: WINDOWS_EVENT_LOG_FIXTURE_SOURCE.into(),
|
||||
since: now - Duration::hours(1),
|
||||
until: now,
|
||||
max_lines: 1000,
|
||||
};
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, logs.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"FORBIDDEN"
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, logs.clone())
|
||||
.await
|
||||
.unwrap_err()
|
||||
.1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
let mut log_caps = windows_caps.as_array().unwrap().clone();
|
||||
log_caps.extend([
|
||||
json!("query_logs"),
|
||||
json!(WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY),
|
||||
]);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(log_caps))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let view = plan(&state, &principal, tenant, logs).await.unwrap();
|
||||
let log_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let bytes: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(log_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let log_bound: PlanPayload = serde_json::from_slice(&bytes).unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &log_bound).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
let pending = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
log_id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-event-log".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
let mut changed = log_bound.clone();
|
||||
if let Action::QueryLogs { max_lines, .. } = &mut changed.jobs[0].payload.action {
|
||||
*max_lines = 999;
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &changed).await.unwrap_err().1,
|
||||
"PLAN_HASH_MISMATCH"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
let mut changed = log_bound.clone();
|
||||
changed.jobs[0].payload.max_output_bytes = 65537;
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &changed).await.unwrap_err().1,
|
||||
"VALIDATION_ERROR"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
log_caps.retain(|cap| cap != WINDOWS_EVENT_LOG_FIXTURE_CAPABILITY);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(json!(log_caps))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
||||
"UNSUPPORTED_CAPABILITY"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'logs:read') WHERE principal=$1").bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
recheck(&mut tx, &log_bound).await.unwrap_err().1,
|
||||
"FORBIDDEN"
|
||||
);
|
||||
tx.rollback().await.unwrap();
|
||||
// MSI metadata only: real migration/RLS/FKs and pending-only planning.
|
||||
// This ignored test runs alone in the dedicated isolated PostgreSQL process.
|
||||
// Opaque bytes deliberately are NOT an authored/installed MSI fixture.
|
||||
use crate::artifact_store::ArtifactStore;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let key_path = temp.join("key.pem");
|
||||
let policy_path = temp.join("system-msi.json");
|
||||
let settings = [
|
||||
("RMM_PROFILE", "development".to_string()),
|
||||
("RMM_JOB_KEY_FILE", key_path.display().to_string()),
|
||||
("RMM_DEV_SYSTEM_ENABLED", "true".to_string()),
|
||||
(
|
||||
"RMM_DEV_SYSTEM_POLICY_FILE",
|
||||
policy_path.display().to_string(),
|
||||
),
|
||||
];
|
||||
let previous = settings
|
||||
.iter()
|
||||
.map(|(key, _)| (*key, std::env::var_os(key)))
|
||||
.collect::<Vec<_>>();
|
||||
for (key, value) in &settings {
|
||||
unsafe {
|
||||
std::env::set_var(key, value);
|
||||
}
|
||||
}
|
||||
let artifact_id = Uuid::new_v4();
|
||||
let opaque = b"metadata-contract-not-an-executable-msi";
|
||||
let artifact_sha = crate::catalog::store()
|
||||
.unwrap()
|
||||
.put(tenant, opaque)
|
||||
.unwrap();
|
||||
let manifest = crate::windows_msi_catalog::test_manifest(
|
||||
artifact_id,
|
||||
&artifact_sha,
|
||||
opaque.len() as u64,
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("INSERT INTO artifacts(tenant_id,artifact_id,sha256,size_bytes,media_type) VALUES($1,$2,$3,$4,'application/octet-stream')")
|
||||
.bind(tenant).bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).execute(&mut *tx).await.unwrap();
|
||||
let catalog_id = crate::windows_msi_catalog::store_recipe(&mut tx, tenant, &manifest)
|
||||
.await
|
||||
.unwrap();
|
||||
tx.commit().await.unwrap();
|
||||
let other = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO tenants(tenant_id,name) VALUES($1,'other MSI tenant')")
|
||||
.bind(other)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut foreign = rmm_persistence::tenant_tx(&state.pool, other)
|
||||
.await
|
||||
.unwrap();
|
||||
let count: i64 = sqlx::query_scalar("SELECT count(*) FROM windows_msi_recipes")
|
||||
.fetch_one(&mut *foreign)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
assert!(
|
||||
crate::windows_msi_catalog::references(&mut foreign, &manifest)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
foreign.rollback().await.unwrap();
|
||||
let row=sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,'1',$4,$5,$6,$7,$8)")
|
||||
.bind(other).bind(Uuid::new_v4()).bind(&manifest.recipe.recipe_id).bind(&manifest.recipe_sha256)
|
||||
.bind(artifact_id).bind(&artifact_sha).bind(opaque.len() as i64).bind(encode(&manifest.recipe).unwrap()).execute(&admin).await;
|
||||
assert!(row.is_err()); // database-level composite tenant/artifact FK
|
||||
assert!(
|
||||
sqlx::query("UPDATE windows_msi_recipes SET recipe_sha256=$2 WHERE catalog_id=$1")
|
||||
.bind(catalog_id)
|
||||
.bind("cd".repeat(32))
|
||||
.execute(&admin)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
sqlx::query("DELETE FROM windows_msi_recipes WHERE catalog_id=$1")
|
||||
.bind(catalog_id)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_append(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let caps = json!([
|
||||
"windows.base/1",
|
||||
"rmm.sync.v1",
|
||||
"helper.system.v1",
|
||||
"ensure_package",
|
||||
"system:ensure_package",
|
||||
rmm_domain::windows_execution::MSI_CAPABILITY,
|
||||
format!("helper.policy.sha256:{}", "ab".repeat(32)),
|
||||
format!("helper.binary.sha256:{}", "cd".repeat(32))
|
||||
]);
|
||||
sqlx::query("UPDATE agent_installations SET capabilities=$2 WHERE agent_id=$1")
|
||||
.bind(agents[1])
|
||||
.bind(&caps)
|
||||
.execute(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let system = json!({"schema_version":2,"profile":"development","expires_at":Utc::now()+Duration::minutes(10),"scopes":[{
|
||||
"tenant_id":tenant,"asset_id":assets[1],"agent_id":agents[1],"enrollment_generation":1,"assignment_version":1,
|
||||
"principals":[principal.name],"helper_policy_sha256":"ab".repeat(32),"helper_binary_sha256":"cd".repeat(32),
|
||||
"acceptance_evidence_id":Uuid::new_v4(),"allowed_services":[],"max_runtime_seconds":120,"allowed_msi_recipe_sha256":[manifest.recipe_sha256]}]});
|
||||
std::fs::write(&policy_path, encode(&system).unwrap()).unwrap();
|
||||
std::fs::set_permissions(&policy_path, std::fs::Permissions::from_mode(0o600)).unwrap();
|
||||
let mut package = input();
|
||||
package.targets.asset_ids = vec![assets[1]];
|
||||
package.script_variants.clear();
|
||||
package.execution_identity = "system".into();
|
||||
package.action = crate::windows_msi_catalog::test_action(manifest.clone());
|
||||
package.max_runtime_seconds = 30;
|
||||
package.max_output_bytes = 4096;
|
||||
let mut extra = package.clone();
|
||||
extra.artifact_ids = vec![artifact_id];
|
||||
assert_eq!(
|
||||
plan(&state, &principal, tenant, extra).await.unwrap_err().1,
|
||||
"WINDOWS_MSI_EXACT_ARTIFACT_REQUIRED"
|
||||
);
|
||||
let view = plan(&state, &principal, tenant, package).await.unwrap();
|
||||
let package_id = Uuid::parse_str(view["plan_id"].as_str().unwrap()).unwrap();
|
||||
let raw: Vec<u8> =
|
||||
sqlx::query_scalar("SELECT payload FROM operation_plans WHERE plan_id=$1")
|
||||
.bind(package_id)
|
||||
.fetch_one(&admin)
|
||||
.await
|
||||
.unwrap();
|
||||
let fixed: PlanPayload = serde_json::from_slice(&raw).unwrap();
|
||||
assert_eq!(fixed.artifact_references.len(), 1);
|
||||
assert_eq!(
|
||||
fixed.artifact_references[0].artifact.artifact_id,
|
||||
artifact_id
|
||||
);
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
recheck(&mut tx, &fixed).await.unwrap();
|
||||
tx.rollback().await.unwrap();
|
||||
for case in 0..4 {
|
||||
let mut bad = fixed.clone();
|
||||
match case {
|
||||
0 => bad.artifact_references.clear(),
|
||||
1 => bad
|
||||
.artifact_references
|
||||
.push(bad.artifact_references[0].clone()),
|
||||
2 => bad.artifact_references[0].artifact.size_bytes += 1,
|
||||
_ => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(),
|
||||
};
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(recheck(&mut tx, &bad).await.is_err());
|
||||
tx.rollback().await.unwrap();
|
||||
}
|
||||
let pending = submit(
|
||||
&state,
|
||||
&principal,
|
||||
tenant,
|
||||
package_id,
|
||||
Submit {
|
||||
idempotency_key: "fixed-msi-metadata".into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(pending["approval_state"], "pending_approval");
|
||||
assert_eq!(pending["job_count"], 0);
|
||||
sqlx::query("UPDATE memberships SET permissions=array_remove(permissions,'system:execute') WHERE tenant_id=$1 AND principal=$2").bind(tenant).bind(&principal.name).execute(&admin).await.unwrap();
|
||||
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(recheck(&mut tx, &fixed).await.unwrap_err().1, "FORBIDDEN");
|
||||
tx.rollback().await.unwrap();
|
||||
for (key, value) in previous {
|
||||
unsafe {
|
||||
match value {
|
||||
Some(value) => std::env::set_var(key, value),
|
||||
None => std::env::remove_var(key),
|
||||
}
|
||||
}
|
||||
}
|
||||
let counts:(i64,i64,i64)=sqlx::query_as("SELECT (SELECT count(*) FROM jobs WHERE tenant_id=$1),(SELECT count(*) FROM outbox WHERE tenant_id=$1),(SELECT count(*) FROM execution_permits WHERE tenant_id=$1)").bind(tenant).fetch_one(&admin).await.unwrap();
|
||||
assert_eq!(counts, (0, 0, 0));
|
||||
let after: Vec<u8> =
|
||||
|
||||
@@ -21,6 +21,7 @@ mod root_policy;
|
||||
mod scheduler;
|
||||
mod synchronization;
|
||||
mod tls;
|
||||
mod windows_msi_catalog;
|
||||
mod windows_policy;
|
||||
|
||||
use anyhow::{Context, Result, ensure};
|
||||
|
||||
@@ -356,6 +356,7 @@ mod tests {
|
||||
script_utf8: "true\n".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
},
|
||||
execution_identity: "root".into(),
|
||||
not_before: now,
|
||||
|
||||
@@ -0,0 +1,380 @@
|
||||
//! Immutable tenant MSI recipe/one-artifact binding. Catalog import is metadata,
|
||||
//! never job approval, helper provisioning, an installer, or a capability grant.
|
||||
use crate::{jobs::Error, pagination};
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
};
|
||||
use rmm_domain::{
|
||||
jobs::{Action, ArtifactReference, JobPayload, PlanPayload, RecipeReference, encode, hash},
|
||||
windows_execution::{MSI_PACKAGE_ID, ResolvedWindowsMsi, WindowsMsiRecipe},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
fn conflict() -> Error {
|
||||
Error(StatusCode::CONFLICT, "WINDOWS_MSI_BINDING_MISMATCH")
|
||||
}
|
||||
fn reference(m: &ResolvedWindowsMsi) -> RecipeReference {
|
||||
RecipeReference {
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: m.recipe.postcondition.product_version.clone(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: m.recipe.recipe_version.clone(),
|
||||
sha256: m.recipe_sha256.clone(),
|
||||
}
|
||||
}
|
||||
fn artifact(m: &ResolvedWindowsMsi) -> ArtifactReference {
|
||||
ArtifactReference {
|
||||
artifact_id: m.recipe.artifact.artifact_id,
|
||||
sha256: m.recipe.artifact.sha256.clone(),
|
||||
size_bytes: m.recipe.artifact.bytes,
|
||||
}
|
||||
}
|
||||
async fn checked(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<(Uuid, ArtifactReference), Error> {
|
||||
if !m.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
// Catalog rows cannot be updated/deleted. Avoid a row lock here: PostgreSQL
|
||||
// requires UPDATE privilege for FOR SHARE, which this immutable reader lacks.
|
||||
let row=sqlx::query("SELECT tenant_id,payload,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes FROM windows_msi_recipes WHERE recipe_id=$1 AND recipe_version=$2")
|
||||
.bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).fetch_optional(&mut **tx).await?
|
||||
.ok_or(Error(StatusCode::CONFLICT,"WINDOWS_MSI_RECIPE_NOT_CONFIGURED"))?;
|
||||
let bytes: Vec<u8> = row.get("payload");
|
||||
let a = artifact(m);
|
||||
if encode(&m.recipe)? != bytes
|
||||
|| hash(&bytes) != m.recipe_sha256
|
||||
|| row.get::<String, _>("recipe_sha256") != m.recipe_sha256
|
||||
|| row.get::<Uuid, _>("artifact_id") != a.artifact_id
|
||||
|| row.get::<String, _>("artifact_sha256") != a.sha256
|
||||
|| row.get::<i64, _>("artifact_bytes") as u64 != a.size_bytes
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
let tenant: Uuid = row.get("tenant_id");
|
||||
let actual = crate::catalog::resolve_artifacts(tx, tenant, &[a.artifact_id]).await?;
|
||||
if actual != [a.clone()] {
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok((tenant, a))
|
||||
}
|
||||
pub async fn references(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<Vec<RecipeReference>, Error> {
|
||||
checked(tx, m).await?;
|
||||
Ok(vec![reference(m)])
|
||||
}
|
||||
pub async fn automatic_artifacts(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
action: &Action,
|
||||
) -> Result<Vec<ArtifactReference>, Error> {
|
||||
let m = action.windows_msi().ok_or_else(conflict)?;
|
||||
if !action.validate() {
|
||||
return Err(conflict());
|
||||
}
|
||||
let (actual, a) = checked(tx, m).await?;
|
||||
if actual != tenant {
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok(vec![a])
|
||||
}
|
||||
/// Set equality/count checks are deliberate. contains()/dedup() would accept
|
||||
/// missing, additional, or duplicate per-attempt Windows artifact authorizations.
|
||||
pub fn validate_plan_bindings(plan: &PlanPayload) -> Result<(), Error> {
|
||||
let mut has_msi = false;
|
||||
let mut recipes = Vec::new();
|
||||
for job in &plan.jobs {
|
||||
let Some(m) = job.payload.action.windows_msi() else {
|
||||
continue;
|
||||
};
|
||||
has_msi = true;
|
||||
recipes.push(reference(m));
|
||||
if !job.payload.action.validate()
|
||||
|| job.payload.execution_identity != "system"
|
||||
|| !job.payload.action.valid_job_limits(
|
||||
job.payload.max_runtime_seconds,
|
||||
job.payload.max_output_bytes,
|
||||
)
|
||||
|| plan.tenant_id != job.payload.tenant_id
|
||||
|| plan
|
||||
.jobs
|
||||
.iter()
|
||||
.filter(|other| {
|
||||
other.payload.job_id == job.payload.job_id
|
||||
&& other.payload.attempt_id == job.payload.attempt_id
|
||||
})
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
let refs = plan
|
||||
.artifact_references
|
||||
.iter()
|
||||
.filter(|r| r.job_id == job.payload.job_id && r.attempt_id == job.payload.attempt_id)
|
||||
.collect::<Vec<_>>();
|
||||
if refs.len() != 1
|
||||
|| refs[0].artifact != artifact(m)
|
||||
|| plan
|
||||
.recipe_references
|
||||
.iter()
|
||||
.filter(|r| **r == reference(m))
|
||||
.count()
|
||||
!= 1
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
}
|
||||
if has_msi {
|
||||
recipes.sort();
|
||||
recipes.dedup();
|
||||
// A package plan resolves one common MSI action for all its targets.
|
||||
// Never accept extra recipe authority or a mixed-action plan at a later
|
||||
// delivery/permit/download boundary merely because contains() succeeds.
|
||||
if recipes != plan.recipe_references
|
||||
|| plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| j.payload.action.windows_msi().is_none())
|
||||
|| plan.artifact_references.iter().any(|r| {
|
||||
!plan
|
||||
.jobs
|
||||
.iter()
|
||||
.any(|j| j.payload.job_id == r.job_id && j.payload.attempt_id == r.attempt_id)
|
||||
})
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn validate_job_binding(plan: &PlanPayload, job: &JobPayload) -> Result<(), Error> {
|
||||
if job.action.windows_msi().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
validate_plan_bindings(plan)?;
|
||||
let bytes = encode(job)?;
|
||||
let matches = plan
|
||||
.jobs
|
||||
.iter()
|
||||
.filter(|j| j.payload.job_id == job.job_id && j.payload.attempt_id == job.attempt_id)
|
||||
.collect::<Vec<_>>();
|
||||
if matches.len() != 1
|
||||
|| matches[0].job_payload_hash != hash(&bytes)
|
||||
|| encode(&matches[0].payload)? != bytes
|
||||
{
|
||||
return Err(conflict());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) async fn store_recipe(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
t: Uuid,
|
||||
m: &ResolvedWindowsMsi,
|
||||
) -> Result<Uuid, Error> {
|
||||
if !m.validate() {
|
||||
return Err(Error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"INVALID_WINDOWS_MSI_MANIFEST",
|
||||
));
|
||||
}
|
||||
let actual = crate::catalog::resolve_artifacts(tx, t, &[m.recipe.artifact.artifact_id]).await?;
|
||||
if actual != [artifact(m)] {
|
||||
return Err(conflict());
|
||||
}
|
||||
let bytes = encode(&m.recipe)?;
|
||||
if bytes.len() > 65536 {
|
||||
return Err(Error(StatusCode::PAYLOAD_TOO_LARGE, "QUOTA_EXCEEDED"));
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query("INSERT INTO windows_msi_recipes(tenant_id,catalog_id,recipe_id,recipe_version,recipe_sha256,artifact_id,artifact_sha256,artifact_bytes,payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)")
|
||||
.bind(t).bind(id).bind(&m.recipe.recipe_id).bind(&m.recipe.recipe_version).bind(&m.recipe_sha256)
|
||||
.bind(m.recipe.artifact.artifact_id).bind(&m.recipe.artifact.sha256).bind(m.recipe.artifact.bytes as i64).bind(bytes).execute(&mut **tx).await?;
|
||||
Ok(id)
|
||||
}
|
||||
pub async fn import(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Json(m): Json<ResolvedWindowsMsi>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (p, mut tx) = crate::catalog::context(&s, &h, t, true).await?;
|
||||
let id = store_recipe(&mut tx, t, &m).await?;
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,'windows_msi_recipe_imported',$4,now())")
|
||||
.bind(t)
|
||||
.bind(Uuid::new_v4())
|
||||
.bind(p.name)
|
||||
.bind(
|
||||
json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"recipe_sha256":m.recipe_sha256,
|
||||
"artifact_id":m.recipe.artifact.artifact_id,"testsimulation":p.testsimulation}),
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(
|
||||
json!({"catalog_id":id,"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m}),
|
||||
))
|
||||
}
|
||||
pub async fn list(
|
||||
State(s): State<crate::State>,
|
||||
h: HeaderMap,
|
||||
Path(t): Path<Uuid>,
|
||||
Query(query): Query<pagination::PageQuery>,
|
||||
) -> Result<Json<Value>, Error> {
|
||||
let (p, mut tx) = crate::catalog::context(&s, &h, t, false).await?;
|
||||
let mut page = pagination::Cursor::parse(&s, &p, "catalog:windows-msi:catalog_id:asc", query)
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?;
|
||||
let rows=sqlx::query("SELECT catalog_id,payload,recipe_sha256 FROM windows_msi_recipes WHERE catalog_id>$1 AND created_at<=$2 ORDER BY catalog_id LIMIT $3")
|
||||
.bind(page.last).bind(page.as_of).bind(i64::from(page.limit)+1).fetch_all(&mut *tx).await?;
|
||||
let truncated = rows.len() > usize::from(page.limit);
|
||||
let next = if truncated {
|
||||
Some(
|
||||
page.next(&s, rows[usize::from(page.limit) - 1].get("catalog_id"))
|
||||
.map_err(|status| Error(status, "VALIDATION_ERROR"))?,
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut items = Vec::new();
|
||||
for row in rows.iter().take(usize::from(page.limit)) {
|
||||
let bytes: Vec<u8> = row.get("payload");
|
||||
let m = ResolvedWindowsMsi {
|
||||
recipe: serde_json::from_slice::<WindowsMsiRecipe>(&bytes)?,
|
||||
recipe_sha256: row.get("recipe_sha256"),
|
||||
};
|
||||
if !m.validate() || encode(&m.recipe)? != bytes {
|
||||
return Err(conflict());
|
||||
}
|
||||
items.push(json!({"catalog_id":row.get::<Uuid,_>("catalog_id"),"recipe_id":m.recipe.recipe_id,"sha256":m.recipe_sha256,"manifest":m}));
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(Json(
|
||||
json!({"items":items,"next_cursor":next,"completeness":if truncated{"partial"}else{"complete"},"truncated":truncated,"as_of":page.as_of}),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_manifest(id: Uuid, sha: &str, bytes: u64) -> ResolvedWindowsMsi {
|
||||
use rmm_domain::windows_execution::*;
|
||||
let recipe = WindowsMsiRecipe {
|
||||
schema_version: 1,
|
||||
recipe_id: MSI_RECIPE_ID.into(),
|
||||
recipe_version: "1".into(),
|
||||
platform: "windows".into(),
|
||||
upgrade_code: MSI_UPGRADE_CODE.into(),
|
||||
architecture: Architecture::X64,
|
||||
context: InstallContext::Machine,
|
||||
command_profile: MsiCommandProfile::FixtureQuietNoRebootV1,
|
||||
artifact: MsiArtifact {
|
||||
artifact_id: id,
|
||||
sha256: sha.into(),
|
||||
bytes,
|
||||
},
|
||||
postcondition: MsiPostcondition {
|
||||
product_code: MSI_PRODUCT_CODE.into(),
|
||||
product_version: MSI_VERSION.into(),
|
||||
payload_path: MSI_PAYLOAD.into(),
|
||||
payload_sha256: MSI_PAYLOAD_10_SHA256.into(),
|
||||
payload_bytes: MSI_PAYLOAD_BYTES,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: None,
|
||||
predecessor: None,
|
||||
};
|
||||
ResolvedWindowsMsi {
|
||||
recipe_sha256: recipe.sha256().unwrap(),
|
||||
recipe,
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn test_action(m: ResolvedWindowsMsi) -> Action {
|
||||
Action::EnsurePackage {
|
||||
provider: "msi".into(),
|
||||
package: MSI_PACKAGE_ID.into(),
|
||||
version: m.recipe.postcondition.product_version.clone(),
|
||||
architecture: "x64".into(),
|
||||
recipe_version: m.recipe.recipe_version.clone(),
|
||||
installation_context: "machine".into(),
|
||||
recipe_id: Some(m.recipe.recipe_id.clone()),
|
||||
apt_manifest: None,
|
||||
windows_msi_manifest: Some(Box::new(m)),
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn exact_per_attempt_artifact_set_never_deduplicates_missing_extra_or_foreign_authority() {
|
||||
use rmm_domain::jobs::{JobArtifactReference, PlannedJob};
|
||||
let id = Uuid::new_v4();
|
||||
let now = chrono::Utc::now();
|
||||
let m = test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32);
|
||||
let job = JobPayload {
|
||||
schema_version: 1,
|
||||
tenant_id: id,
|
||||
asset_id: id,
|
||||
agent_id: id,
|
||||
enrollment_generation: 1,
|
||||
assignment_version: 1,
|
||||
job_id: Uuid::new_v4(),
|
||||
attempt_id: Uuid::new_v4(),
|
||||
action: test_action(m.clone()),
|
||||
execution_identity: "system".into(),
|
||||
not_before: now,
|
||||
start_before: now + chrono::Duration::minutes(1),
|
||||
max_runtime_seconds: 30,
|
||||
max_output_bytes: 4096,
|
||||
};
|
||||
let plan = PlanPayload {
|
||||
schema_version: 1,
|
||||
plan_id: Uuid::new_v4(),
|
||||
tenant_id: id,
|
||||
principal: "test".into(),
|
||||
reason: "metadata only".into(),
|
||||
jobs: vec![PlannedJob {
|
||||
job_payload_hash: hash(&encode(&job).unwrap()),
|
||||
payload: job.clone(),
|
||||
script_sha256: None,
|
||||
}],
|
||||
max_parallel: 1,
|
||||
halt_after_failures: 1,
|
||||
recipe_references: vec![reference(&m)],
|
||||
artifact_references: vec![JobArtifactReference {
|
||||
job_id: job.job_id,
|
||||
attempt_id: job.attempt_id,
|
||||
artifact: artifact(&m),
|
||||
}],
|
||||
};
|
||||
validate_job_binding(&plan, &job).unwrap();
|
||||
for case in 0..9 {
|
||||
let mut bad = plan.clone();
|
||||
match case {
|
||||
0 => bad.artifact_references.clear(),
|
||||
1 => bad
|
||||
.artifact_references
|
||||
.push(bad.artifact_references[0].clone()),
|
||||
2 => bad.artifact_references[0].artifact.artifact_id = Uuid::new_v4(),
|
||||
3 => bad.artifact_references[0].artifact.size_bytes += 1,
|
||||
4 => bad.artifact_references[0].attempt_id = Uuid::new_v4(),
|
||||
5 => bad.jobs[0].payload.max_output_bytes += 1,
|
||||
6 => bad.recipe_references.clear(),
|
||||
7 => bad.recipe_references.push(bad.recipe_references[0].clone()),
|
||||
_ => {
|
||||
let mut extra = bad.recipe_references[0].clone();
|
||||
extra.sha256 = "ef".repeat(32);
|
||||
bad.recipe_references.push(extra);
|
||||
}
|
||||
}
|
||||
assert!(validate_job_binding(&bad, &job).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,8 +37,16 @@ struct SystemScope {
|
||||
// Administrative evidence pin, never an approval or authorization ID.
|
||||
acceptance_evidence_id: Uuid,
|
||||
allowed_services: Vec<String>,
|
||||
#[serde(default, deserialize_with = "strict_optional_hashes")]
|
||||
allowed_msi_recipe_sha256: Option<Vec<String>>,
|
||||
max_runtime_seconds: u32,
|
||||
}
|
||||
fn strict_optional_hashes<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
Vec::<String>::deserialize(deserializer).map(Some)
|
||||
}
|
||||
fn digest(value: &str) -> bool {
|
||||
value.len() == 64
|
||||
&& value
|
||||
@@ -86,9 +94,27 @@ impl SystemScope {
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== self.allowed_services.len()
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_none_or(|hashes| {
|
||||
hashes.len() <= 2
|
||||
&& hashes.iter().all(|h| digest(h))
|
||||
&& hashes
|
||||
.iter()
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.len()
|
||||
== hashes.len()
|
||||
})
|
||||
&& (1..=120).contains(&self.max_runtime_seconds)
|
||||
}
|
||||
fn permits(&self, principal: &str, job: &JobPayload, capabilities: &[String]) -> bool {
|
||||
fn permits(
|
||||
&self,
|
||||
principal: &str,
|
||||
job: &JobPayload,
|
||||
capabilities: &[String],
|
||||
allow_msi: bool,
|
||||
) -> bool {
|
||||
let has = |cap: &str| capabilities.iter().any(|c| c == cap);
|
||||
self.valid()
|
||||
&& job.execution_identity == "system"
|
||||
@@ -110,17 +136,40 @@ impl SystemScope {
|
||||
"helper.binary.sha256:{}",
|
||||
self.helper_binary_sha256
|
||||
))
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
|
||||
&& (1..=65536).contains(&job.max_output_bytes)
|
||||
&& matches!(&job.action,Action::SetServiceState{unit,state}
|
||||
if self.allowed_services.contains(unit) && matches!(state.as_str(),"running"|"stopped"))
|
||||
&& match &job.action {
|
||||
Action::SetServiceState { unit, state } => {
|
||||
self.allowed_services.contains(unit)
|
||||
&& matches!(state.as_str(), "running" | "stopped")
|
||||
&& has("system:set_service_state")
|
||||
&& has("set_service_state")
|
||||
}
|
||||
_ if allow_msi => job.action.windows_msi().is_some_and(|m| {
|
||||
job.action.validate()
|
||||
&& job
|
||||
.action
|
||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||
&& self
|
||||
.allowed_msi_recipe_sha256
|
||||
.as_ref()
|
||||
.is_some_and(|hashes| hashes.contains(&m.recipe_sha256))
|
||||
&& has("ensure_package")
|
||||
&& has("system:ensure_package")
|
||||
&& has(rmm_domain::windows_execution::MSI_CAPABILITY)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl SystemPolicy {
|
||||
fn valid(&self, now: DateTime<Utc>) -> bool {
|
||||
self.schema_version == 1
|
||||
matches!(self.schema_version, 1 | 2)
|
||||
&& (self.schema_version == 2
|
||||
|| self
|
||||
.scopes
|
||||
.iter()
|
||||
.all(|scope| scope.allowed_msi_recipe_sha256.is_none()))
|
||||
&& self.profile == "development"
|
||||
&& self.expires_at > now
|
||||
&& !self.scopes.is_empty()
|
||||
@@ -138,7 +187,7 @@ impl SystemPolicy {
|
||||
&& self
|
||||
.scopes
|
||||
.iter()
|
||||
.any(|scope| scope.permits(principal, job, capabilities))
|
||||
.any(|scope| scope.permits(principal, job, capabilities, self.schema_version == 2))
|
||||
}
|
||||
}
|
||||
fn disabled() -> Error {
|
||||
@@ -393,6 +442,7 @@ mod tests {
|
||||
script_utf8: "Write-Output 'hello'".into(),
|
||||
arguments: vec![],
|
||||
expected_stdout: None,
|
||||
windows_execution_profile: None,
|
||||
};
|
||||
assert!(!policy.permits("selected", &job, &caps, now));
|
||||
job.action = Action::SetServiceState {
|
||||
@@ -409,6 +459,29 @@ mod tests {
|
||||
assert!(serde_json::from_value::<SystemPolicy>(invalid).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn only_explicit_v2_hash_scope_and_package_caps_allow_fixed_msi() {
|
||||
let (mut policy, mut job, mut caps) = fixture();
|
||||
let m = crate::windows_msi_catalog::test_manifest(Uuid::new_v4(), &"ab".repeat(32), 32);
|
||||
job.action = crate::windows_msi_catalog::test_action(m.clone());
|
||||
caps.extend([
|
||||
"ensure_package".into(),
|
||||
"system:ensure_package".into(),
|
||||
rmm_domain::windows_execution::MSI_CAPABILITY.into(),
|
||||
]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec![m.recipe_sha256.clone()]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now())); // v1 remains SCM-only
|
||||
policy.schema_version = 2;
|
||||
assert!(policy.permits("selected", &job, &caps, Utc::now()));
|
||||
for index in caps.len() - 3..caps.len() {
|
||||
let mut short = caps.clone();
|
||||
short.remove(index);
|
||||
assert!(!policy.permits("selected", &job, &short, Utc::now()));
|
||||
}
|
||||
policy.scopes[0].allowed_msi_recipe_sha256 = Some(vec!["cd".repeat(32)]);
|
||||
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
|
||||
}
|
||||
#[test]
|
||||
fn policy_file_refuses_symlinks_public_mode_wrong_owner_and_writable_parent() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let directory = std::env::temp_dir().join(format!("rmm-windows-policy-{}", Uuid::new_v4()));
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
Build-only, fixed MSI 1.0.0 fixture. Writes only a NEW private child directory.
|
||||
Build-only, fixed MSI1.0.0 or1.1.0 major-upgrade fixture. Writes only a NEW private child directory.
|
||||
Never calls InstallProduct/OpenPackage/msiexec, modifies installed products,
|
||||
services, execution policy, certificate trust or reboot state. No downloads.
|
||||
No upgrade/EXE package is authored by this version.
|
||||
1.1 removes only the exact known1.0 predecessor; no EXE/repair mode.
|
||||
|
||||
Primary API/format contracts:
|
||||
https://learn.microsoft.com/en-us/windows/win32/msi/installer-opendatabase
|
||||
@@ -17,7 +17,8 @@ https://learn.microsoft.com/en-us/windows/win32/msi/package-codes
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$OutputParent,
|
||||
[Guid]$CaseId=([Guid]::NewGuid())
|
||||
[Guid]$CaseId=([Guid]::NewGuid()),
|
||||
[ValidateSet('1.0.0','1.1.0')][string]$FixtureVersion='1.0.0'
|
||||
)
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference='Stop'
|
||||
@@ -25,14 +26,18 @@ $case=$null;$created=$false;$installer=$null;$database=$null;$summary=$null;$mak
|
||||
$product='{3F070B4B-9C08-4D65-BD41-13D81B884AEC}'
|
||||
$upgrade='{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}'
|
||||
$component='{4D1CA80F-9AF8-4F54-B426-450AFBAFF92E}'
|
||||
$version='1.0.0'
|
||||
$version=$FixtureVersion
|
||||
$isUpgrade=$version -ceq '1.1.0'
|
||||
$oldProduct=$product
|
||||
if($isUpgrade){$product='{D42BD387-079B-4BBF-A134-0DA7B7A97011}'}
|
||||
$upgradeCondition='Installed OR (RMM_OLD_PRODUCTS = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}" AND RMM_ALL_PRODUCTS = "{3F070B4B-9C08-4D65-BD41-13D81B884AEC}")'
|
||||
# Product/family/component identities are fixed. Nonidentical MSI bytes must
|
||||
# have distinct PackageCodes, so each new authoring case gets its own code.
|
||||
$package='{'+([Guid]::NewGuid().ToString().ToUpperInvariant())+'}'
|
||||
$artifact=[Guid]::NewGuid().ToString()
|
||||
$report=[ordered]@{schema_version=1;case_id=$CaseId.ToString();completed=$false;stage='preflight';
|
||||
build_only=$true;native_installation_tested=$false;product_changes=$false;services_changed=$false;
|
||||
reboot_requested=$false;trust_changed=$false;downloads=$false;upgrade_authored=$false;
|
||||
reboot_requested=$false;trust_changed=$false;downloads=$false;upgrade_authored=$isUpgrade;
|
||||
product_code=$product;upgrade_code=$upgrade;component_code=$component;package_code=$package;version=$version}
|
||||
|
||||
function Require([bool]$Value,[string]$Code) {if (!$Value) {throw $Code}}
|
||||
@@ -169,7 +174,7 @@ try {
|
||||
$report.tools=$tools
|
||||
$report.stage='payload_and_cabinet'
|
||||
$payload=Join-Path $case 'msi-payload.txt'
|
||||
$payloadBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture 1.0.0`r`n")
|
||||
$payloadBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture $version`r`n")
|
||||
Write-New $payload $payloadBytes
|
||||
$ddf=Join-Path $case 'fixture.ddf'
|
||||
$ddfText=@"
|
||||
@@ -190,7 +195,7 @@ try {
|
||||
$cab=Join-Path $case 'fixture.cab';No-Reparse $cab
|
||||
Require ((Get-Item -LiteralPath $cab).Length -gt 0 -and (Get-Item -LiteralPath $cab).Length -le 65536) 'MSI_CABINET_LIMIT'
|
||||
$report.stage='database_authoring:com_activation'
|
||||
$msi=Join-Path $case 'RustDiscoveryFixture-1.0.0-x64.msi';Require (!(Test-Path -LiteralPath $msi)) 'MSI_OUTPUT_EXISTS'
|
||||
$msi=Join-Path $case ('RustDiscoveryFixture-'+$version+'-x64.msi');Require (!(Test-Path -LiteralPath $msi)) 'MSI_OUTPUT_EXISTS'
|
||||
$installer=New-Object -ComObject WindowsInstaller.Installer
|
||||
$report.stage='database_authoring:open_create'
|
||||
$database=Com-Method $installer 'OpenDatabase' @($msi,[int]3)
|
||||
@@ -205,9 +210,11 @@ try {
|
||||
InstallExecuteSequence='`Action` CHAR(72) NOT NULL, `Condition` CHAR(255), `Sequence` SHORT PRIMARY KEY `Action`'
|
||||
LaunchCondition='`Condition` CHAR(255) NOT NULL, `Description` CHAR(255) NOT NULL LOCALIZABLE PRIMARY KEY `Condition`'
|
||||
}
|
||||
if($isUpgrade){$tables.Upgrade='`UpgradeCode` CHAR(38) NOT NULL, `VersionMin` CHAR(20), `VersionMax` CHAR(20), `Language` CHAR(255), `Attributes` SHORT NOT NULL, `Remove` CHAR(255), `ActionProperty` CHAR(72) NOT NULL PRIMARY KEY `UpgradeCode`, `VersionMin`, `VersionMax`, `Language`, `Attributes`'}
|
||||
foreach ($table in $tables.Keys) {$report.stage='database_authoring:create_table:'+$table;Sql ('CREATE TABLE `'+$table+'` ('+$tables[$table]+')')}
|
||||
$report.stage='database_authoring:insert_rows'
|
||||
$properties=[ordered]@{ProductCode=$product;UpgradeCode=$upgrade;ProductVersion=$version;ProductLanguage='1033';ProductName='RustDiscovery MSI Fixture';Manufacturer='Ease Technologies';ALLUSERS='1';INSTALLLEVEL='1';REBOOT='ReallySuppress'}
|
||||
if($isUpgrade){$properties.SecureCustomProperties='RMM_ALL_PRODUCTS;RMM_OLD_PRODUCTS'}
|
||||
foreach ($key in $properties.Keys) {Sql ("INSERT INTO ``Property`` (``Property``,``Value``) VALUES ('$key','$($properties[$key])')")}
|
||||
Sql 'INSERT INTO `Directory` (`Directory`,`DefaultDir`) VALUES (''TARGETDIR'',''SourceDir'')'
|
||||
Sql 'INSERT INTO `Directory` (`Directory`,`Directory_Parent`,`DefaultDir`) VALUES (''ProgramFiles64Folder'',''TARGETDIR'',''.'')'
|
||||
@@ -218,8 +225,17 @@ try {
|
||||
Sql ("INSERT INTO ``File`` (``File``,``Component_``,``FileName``,``FileSize``,``Attributes``,``Sequence``) VALUES ('PayloadFile','PayloadComponent','MSIPAY~1.TXT|msi-payload.txt',$($payloadBytes.Length),16896,1)")
|
||||
Sql 'INSERT INTO `Media` (`DiskId`,`LastSequence`,`Cabinet`) VALUES (1,1,''#fixture.cab'')'
|
||||
Sql 'INSERT INTO `LaunchCondition` (`Condition`,`Description`) VALUES (''VersionNT64'',''This fixture requires 64-bit Windows.'')'
|
||||
if($isUpgrade){
|
||||
Sql ("INSERT INTO ``Upgrade`` (``UpgradeCode``,``VersionMin``,``VersionMax``,``Attributes``,``Remove``,``ActionProperty``) VALUES ('$upgrade','1.0.0','1.0.0',768,'ALL','RMM_OLD_PRODUCTS')")
|
||||
Sql ("INSERT INTO ``Upgrade`` (``UpgradeCode``,``VersionMin``,``Attributes``,``Remove``,``ActionProperty``) VALUES ('$upgrade','0.0.0',258,'ALL','RMM_ALL_PRODUCTS')")
|
||||
Sql ("INSERT INTO ``LaunchCondition`` (``Condition``,``Description``) VALUES ('$upgradeCondition','Only the exact approved fixture1.0 predecessor may be upgraded.')")
|
||||
}
|
||||
$sequence=[ordered]@{LaunchConditions=100;CostInitialize=800;FileCost=900;CostFinalize=1000;InstallValidate=1400;InstallInitialize=1500;ProcessComponents=1600;UnpublishFeatures=1800;RemoveFiles=3500;RemoveFolders=3600;CreateFolders=3700;InstallFiles=4000;RegisterUser=6000;RegisterProduct=6100;PublishFeatures=6300;PublishProduct=6400;InstallFinalize=6600}
|
||||
foreach ($action in $sequence.Keys) {Sql ("INSERT INTO ``InstallExecuteSequence`` (``Action``,``Sequence``) VALUES ('$action',$($sequence[$action]))")}
|
||||
if($isUpgrade){$sequence.FindRelatedProducts=25;$sequence.RemoveExistingProducts=1550}
|
||||
foreach ($action in $sequence.Keys) {
|
||||
if($action -ceq 'RemoveExistingProducts'){Sql ("INSERT INTO ``InstallExecuteSequence`` (``Action``,``Condition``,``Sequence``) VALUES ('$action','NOT Installed',$($sequence[$action]))")}
|
||||
else {Sql ("INSERT INTO ``InstallExecuteSequence`` (``Action``,``Sequence``) VALUES ('$action',$($sequence[$action]))")}
|
||||
}
|
||||
$view=Com-Method $database 'OpenView' @('INSERT INTO `_Streams` (`Name`,`Data`) VALUES (?,?)');$record=$null
|
||||
try {$record=Com-Method $installer 'CreateRecord' @([int]2);Com-Set $record 'StringData' @([int]1,'fixture.cab');[void](Com-Method $record 'SetStream' @([int]2,$cab));[void](Com-Method $view 'Execute' @($record));[void](Com-Method $view 'Close')}
|
||||
finally {Release-Com $record;Release-Com $view}
|
||||
@@ -236,7 +252,23 @@ try {
|
||||
foreach ($key in $properties.Keys) {$row=Rows ("SELECT ``Value`` FROM ``Property`` WHERE ``Property``='$key'");Require ($row.Count -eq 1 -and $row[0][0] -ceq $properties[$key]) 'MSI_PROPERTY_READBACK'}
|
||||
$allTables=Rows 'SELECT `Name` FROM `_Tables`';$names=@($allTables|ForEach-Object {$_[0]})
|
||||
Require ($names.Count -eq $tables.Count -and @($names|Where-Object {$_ -notin $tables.Keys}).Count -eq 0) 'MSI_UNEXPECTED_TABLE'
|
||||
Require ('CustomAction' -notin $names -and 'Upgrade' -notin $names -and 'Registry' -notin $names -and 'ServiceInstall' -notin $names) 'MSI_FORBIDDEN_TABLE'
|
||||
Require ('CustomAction' -notin $names -and 'Registry' -notin $names -and 'ServiceInstall' -notin $names -and ($isUpgrade -or 'Upgrade' -notin $names)) 'MSI_FORBIDDEN_TABLE'
|
||||
# Independently read committed upgrade/sequence metadata; no install APIs.
|
||||
foreach($action in $sequence.Keys){
|
||||
$row=Rows ("SELECT ``Condition``,``Sequence`` FROM ``InstallExecuteSequence`` WHERE ``Action``='$action'")
|
||||
$condition=if($action -ceq 'RemoveExistingProducts'){'NOT Installed'}else{''}
|
||||
Require ($row.Count -eq 1 -and $row[0][0] -ceq $condition -and $row[0][1] -ceq [string]$sequence[$action]) 'MSI_SEQUENCE_READBACK'
|
||||
}
|
||||
if($isUpgrade){
|
||||
$rows=Rows 'SELECT `UpgradeCode`,`VersionMin`,`VersionMax`,`Attributes`,`Remove`,`ActionProperty` FROM `Upgrade` WHERE `Language` IS NULL ORDER BY `ActionProperty`'
|
||||
Require ($rows.Count -eq 2) 'MSI_UPGRADE_ROW_COUNT'
|
||||
$expected=@(@($upgrade,'0.0.0','','258','ALL','RMM_ALL_PRODUCTS'),@($upgrade,'1.0.0','1.0.0','768','ALL','RMM_OLD_PRODUCTS'))
|
||||
for($i=0;$i -lt 2;$i++){for($j=0;$j -lt 6;$j++){Require ($rows[$i][$j] -ceq $expected[$i][$j]) 'MSI_UPGRADE_ROW_READBACK'}}
|
||||
$nullMax=Rows 'SELECT `ActionProperty` FROM `Upgrade` WHERE `VersionMax` IS NULL'
|
||||
Require ($nullMax.Count -eq 1 -and $nullMax[0][0] -ceq 'RMM_ALL_PRODUCTS') 'MSI_UPGRADE_NULL_MAX_READBACK'
|
||||
$launch=Rows ("SELECT ``Description`` FROM ``LaunchCondition`` WHERE ``Condition``='$upgradeCondition'")
|
||||
Require ($launch.Count -eq 1 -and $launch[0][0] -ceq 'Only the exact approved fixture1.0 predecessor may be upgraded.' -and $readback.LaunchCondition.Count -eq 2) 'MSI_UPGRADE_LAUNCH_READBACK'
|
||||
}
|
||||
$summary=Com-Get $database 'SummaryInformation' @([int]0)
|
||||
Require ((Com-Get $summary 'Property' @([int]7)) -ceq 'x64;1033' -and (Com-Get $summary 'Property' @([int]9)) -ceq $package -and [int](Com-Get $summary 'Property' @([int]15)) -eq 2) 'MSI_SUMMARY_READBACK'
|
||||
Release-Com $summary;$summary=$null
|
||||
@@ -253,12 +285,17 @@ try {
|
||||
$extra=Com-Method $view 'Fetch';Require ($null -eq $extra) 'MSI_DUPLICATE_CAB_STREAM';[void](Com-Method $view 'Close')
|
||||
} finally {Release-Com $record;Release-Com $view}
|
||||
Release-Com $database;$database=$null
|
||||
$recipe=[ordered]@{schema_version=1;recipe_id='rmm-windows-msi-fixture-install-1.0';recipe_version='1';platform='windows';upgrade_code=$upgrade;architecture='x64';context='machine';command_profile='fixture_quiet_no_reboot_v1';artifact=[ordered]@{artifact_id=$artifact;sha256=(Hash $msi);bytes=$length};postcondition=[ordered]@{product_code=$product;product_version=$version;payload_path='C:\Program Files\RustDiscoveryFixtures\msi-payload.txt';payload_sha256=(Hash $payload);payload_bytes=$payloadBytes.Length};no_reboot=$true}
|
||||
$recipe=[ordered]@{schema_version=1;recipe_id=$(if($isUpgrade){'rmm-windows-msi-fixture-upgrade-1.1'}else{'rmm-windows-msi-fixture-install-1.0'});recipe_version='1';platform='windows';upgrade_code=$upgrade;architecture='x64';context='machine';command_profile='fixture_quiet_no_reboot_v1';artifact=[ordered]@{artifact_id=$artifact;sha256=(Hash $msi);bytes=$length};postcondition=[ordered]@{product_code=$product;product_version=$version;payload_path='C:\Program Files\RustDiscoveryFixtures\msi-payload.txt';payload_sha256=(Hash $payload);payload_bytes=$payloadBytes.Length};no_reboot=$true}
|
||||
if($isUpgrade){
|
||||
$recipe.package_code=$package
|
||||
$oldBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture 1.0.0`r`n")
|
||||
$recipe.predecessor=[ordered]@{product_code=$oldProduct;product_version='1.0.0';payload_path=$recipe.postcondition.payload_path;payload_sha256=(Hash-Bytes $oldBytes);payload_bytes=$oldBytes.Length}
|
||||
}
|
||||
$recipeJson=$recipe|ConvertTo-Json -Depth 12 -Compress
|
||||
Write-New (Join-Path $case 'recipe.json') ([Text.Encoding]::UTF8.GetBytes($recipeJson))
|
||||
Write-Json (Join-Path $case 'tables.json') $readback
|
||||
$report.artifact=[ordered]@{path=$msi;sha256=(Hash $msi);bytes=$length;artifact_id_proposal=$artifact}
|
||||
$report.payload=[ordered]@{sha256=(Hash $payload);bytes=$payloadBytes.Length;content_ascii="RustDiscovery MSI fixture 1.0.0`r`n";installed_path=$recipe.postcondition.payload_path}
|
||||
$report.payload=[ordered]@{sha256=(Hash $payload);bytes=$payloadBytes.Length;content_ascii="RustDiscovery MSI fixture $version`r`n";installed_path=$recipe.postcondition.payload_path}
|
||||
$report.cabinet=[ordered]@{sha256=(Hash $cab);bytes=(Get-Item -LiteralPath $cab).Length;embedded_hash_verified=$true;stream='fixture.cab'}
|
||||
$report.tables_sha256=Hash (Join-Path $case 'tables.json');$report.table_names=$names
|
||||
$report.resolved_recipe=[ordered]@{recipe=$recipe;recipe_sha256=(Hash (Join-Path $case 'recipe.json'))}
|
||||
@@ -267,7 +304,7 @@ try {
|
||||
Require ((Hash $PSCommandPath) -ceq $report.builder_sha256) 'MSI_BUILDER_CHANGED'
|
||||
$report.completed=$true;$report.stage='authored_and_read_back_not_installed'
|
||||
Write-Json (Join-Path $case 'result.json') $report
|
||||
[ordered]@{completed=$true;build_only=$true;report_path=(Join-Path $case 'result.json');artifact=$report.artifact;native_installation_tested=$false;upgrade_authored=$false}|ConvertTo-Json -Depth 5
|
||||
[ordered]@{completed=$true;build_only=$true;report_path=(Join-Path $case 'result.json');artifact=$report.artifact;native_installation_tested=$false;upgrade_authored=$isUpgrade}|ConvertTo-Json -Depth 5
|
||||
} catch {
|
||||
$report.completed=$false;$report.error_type=$_.Exception.GetType().FullName;$report.error_hresult=$_.Exception.HResult
|
||||
$report.error_line=$_.InvocationInfo.ScriptLineNumber
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Source-bound Pipe-v2 pack and create-once native units, never deployment.
|
||||
|
||||
The access root only supplies the existing pinned SSH transport and immutable
|
||||
native Core proofs. No credentials/devstate symlinks, copies, services or jobs.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
CODE = Path(__file__).resolve().parents[2]
|
||||
ACCESS = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||
sys.path.insert(0, str(ACCESS / 'deploy/windows'))
|
||||
sys.path.insert(0, str(ACCESS / 'deploy'))
|
||||
import client_bootstrap as cb
|
||||
import auto_transport_acceptance as auto
|
||||
import runtime_upgrade as previous
|
||||
|
||||
require = cb.contract.require
|
||||
BUILD = CODE / 'devstate/windows-pipe-drain-build'
|
||||
NATIVE = CODE / 'devstate/windows-client/native-pipe-v2'
|
||||
# These imported transports read their original protected access configuration.
|
||||
# Their new local upload/error receipts belong to this isolated checkout.
|
||||
cb.EVIDENCE = CODE / 'devstate/windows-client'
|
||||
CORE = ACCESS / 'devstate/core-no-start/build-de37ee99-11bf-465b-9519-45ad8f6e5b87/manifest.json'
|
||||
CORE_SHA = '1bc082031fcad20d5a519b0004f63d499dbba2ea9ce25d56230d48d2556d474b'
|
||||
LOCAL = CODE / 'devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json'
|
||||
LOCAL_SHA = 'a7e3c604d4ad19feed0323ac23aa7a0290b6fb93bc57649cafbadbe5f293b1d4'
|
||||
TARGET = 'x86_64-pc-windows-gnu'
|
||||
NAMES = {'agent': 'rmm-agent-windows.exe', 'helper': 'rmm-helper-windows.exe',
|
||||
'probe': 'RuntimeStateProbe.exe', 'system_probe': 'SystemStateProbe.exe',
|
||||
'lib': 'windows-tests-lib.exe', 'bin': 'windows-tests-bin.exe'}
|
||||
# Expected V2 native lists: unchanged names, two existing codec cases extended.
|
||||
TESTS = {
|
||||
'lib': sorted([
|
||||
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
|
||||
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
|
||||
'clock::tests::suspend_closes_until_actual_post_resume_sync',
|
||||
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
|
||||
'clock::tests::wall_step_and_overflow_fail_closed',
|
||||
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
|
||||
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
|
||||
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
|
||||
'helper_ipc::tests::serialization_refuses_oversized_frame',
|
||||
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
|
||||
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
|
||||
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
|
||||
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
|
||||
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
|
||||
'helper_system::tests::service_adapter_exposes_only_implemented_states',
|
||||
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
|
||||
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
|
||||
'journal::tests::durable_reopen_ack_identity_and_single_process',
|
||||
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
|
||||
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
|
||||
'native::tests::boot_identity_survives_independent_native_queries',
|
||||
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
|
||||
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted']),
|
||||
'bin': sorted([
|
||||
'https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
|
||||
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
|
||||
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
|
||||
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
|
||||
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
|
||||
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
|
||||
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses'])}
|
||||
COUNTS = {'lib': 23, 'bin': 7}
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def save(path, value):
|
||||
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
cb.contract.write_private(path, value)
|
||||
|
||||
|
||||
def private_file(path):
|
||||
path = Path(path)
|
||||
require(not path.is_symlink() and not path.parent.is_symlink(), 'private regular path')
|
||||
info = path.lstat()
|
||||
require(stat.S_ISREG(info.st_mode) and info.st_uid == os.getuid()
|
||||
and stat.S_IMODE(info.st_mode) == 0o600, 'private regular owner/mode')
|
||||
return path
|
||||
|
||||
|
||||
def sources():
|
||||
require(ACCESS.is_dir() and not ACCESS.is_symlink() and cb.ROOT == ACCESS,
|
||||
'original access checkout only; no copied configuration')
|
||||
names = {'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'proto/agent.proto',
|
||||
'deploy/windows/system_pipe_acceptance.py', 'docs/windows-helper-pipe-drain.md'}
|
||||
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates').glob('*/Cargo.toml'))
|
||||
for crate in ('agent-windows', 'agent-core', 'domain', 'protocol'):
|
||||
names.update(str(p.relative_to(CODE)) for p in (CODE / 'crates' / crate).rglob('*')
|
||||
if p.is_file() and p.suffix in ('.rs', '.c', '.h', '.idl', '.toml'))
|
||||
names.update('crates/agent/src/' + n + '.rs' for n in ('https_channel', 'transport', 'wire_channel'))
|
||||
require(all((CODE / n).is_file() and not (CODE / n).is_symlink() for n in names), 'complete fixed build sources')
|
||||
transport = {}
|
||||
for module in tuple(sys.modules.values()):
|
||||
raw = getattr(module, '__file__', None)
|
||||
if raw:
|
||||
path = Path(raw).resolve()
|
||||
if path.is_relative_to(ACCESS / 'deploy') and path.suffix == '.py':
|
||||
transport[str(path.relative_to(ACCESS))] = sha(path)
|
||||
require('deploy/windows/client_bootstrap.py' in transport, 'actual transport source binding')
|
||||
return {'code': {n: sha(CODE / n) for n in sorted(names)}, 'access_transport': dict(sorted(transport.items()))}
|
||||
|
||||
|
||||
def core_proof():
|
||||
require(sha(CORE) == CORE_SHA, 'exact original Linux-first Core manifest')
|
||||
manifest = cb.contract.protected_json(CORE)
|
||||
result = {'manifest_sha256': CORE_SHA}
|
||||
for platform, count in (('linux', 80), ('windows', 58)):
|
||||
path = CORE.parent / (platform + '-passed.json')
|
||||
proof = cb.contract.protected_json(path)
|
||||
require(proof['verified'] is True and proof['platform'] == platform
|
||||
and proof['manifest_sha256'] == CORE_SHA, 'actual same-manifest native Core proof')
|
||||
actual = proof['native']['reports']
|
||||
require(set(actual) == set(manifest['test_counts'][platform])
|
||||
and sum(len(v['names']) for v in actual.values()) == count, 'all native Core reports')
|
||||
for kind, item in actual.items():
|
||||
n = manifest['test_counts'][platform][kind]
|
||||
output = base64.b64decode(item['stdout_b64'], validate=True)
|
||||
require(item['exit_code'] == 0 and item['timed_out'] is False
|
||||
and item['names'] == manifest['test_names'][platform][kind]
|
||||
and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and re.search(rb'test result: ok\. ' + str(n).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', output),
|
||||
'complete actual native Core result')
|
||||
result[platform] = {'proof_sha256': sha(path), 'case_id': proof['case_id']}
|
||||
for name, digest in manifest['source_files'].items():
|
||||
if name.startswith(('crates/agent-core/', 'crates/domain/', 'crates/protocol/', 'proto/')):
|
||||
require(sha(CODE / name) == digest, 'isolated common source equals actual native Core proof')
|
||||
return result
|
||||
|
||||
|
||||
def reused_qualification():
|
||||
require(sha(LOCAL) == LOCAL_SHA, 'exact retained local qualification')
|
||||
value = cb.contract.protected_json(LOCAL)
|
||||
require(value['type'] == 'rmm.windows.pipe-drain-local-qualification'
|
||||
and value['source_before_after_equal'] is True and value['native_executed'] is False
|
||||
and value['clock_qualified'] is False and value['native_counts_expected'] == COUNTS
|
||||
and len(value['commands']) == 4 and all(c['exit_code'] == 0 for c in value['commands']),
|
||||
'actual previous cross-Clippy/release/unit-link qualification')
|
||||
for name, digest in value['source_files'].items():
|
||||
require(sha(CODE / name) == digest, 'all original qualified inputs remain unchanged')
|
||||
for item in list(value['artifacts'].values()) + list(value['unit_links'].values()):
|
||||
path = Path(item['path'])
|
||||
target = LOCAL.parent / 'target'
|
||||
require(path.is_relative_to(target), 'qualified link under private target')
|
||||
current = target
|
||||
for part in ('',) + path.relative_to(target).parts:
|
||||
if part:
|
||||
current = current / part
|
||||
info = current.lstat()
|
||||
require(not stat.S_ISLNK(info.st_mode) and info.st_uid in (0, os.getuid())
|
||||
and info.st_mode & 0o022 == 0, 'protected original compiler output')
|
||||
require(stat.S_ISREG(path.lstat().st_mode) and sha(path) == item['sha256']
|
||||
and path.stat().st_size == item['bytes'], 'retained exact qualified links')
|
||||
require(re.search(r'^pub const ADAPTER_QUALIFIED: bool = false;$',
|
||||
(CODE / 'crates/agent-windows/src/clock.rs').read_text(), re.M), 'production clock remains closed')
|
||||
return value
|
||||
|
||||
|
||||
def command(args, folder, name):
|
||||
with (folder / (name + '.stdout')).open('xb') as out, (folder / (name + '.stderr')).open('xb') as err:
|
||||
result = subprocess.run(args, stdout=out, stderr=err)
|
||||
save(folder / (name + '.json'), {'exit_code': result.returncode, 'local_only': True, 'arguments': args})
|
||||
require(result.returncode == 0, 'local build failed; original stdout/stderr retained')
|
||||
|
||||
|
||||
def build():
|
||||
before, common, prior = sources(), core_proof(), reused_qualification()
|
||||
folder = BUILD / ('build-' + str(uuid.uuid4()))
|
||||
folder.mkdir(mode=0o700, parents=True)
|
||||
save(folder / 'source-before.json', before)
|
||||
save(folder / 'reused-qualification.json', {'path': str(LOCAL), 'sha256': LOCAL_SHA, 'value': prior})
|
||||
image = prior['build_image']
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable compiler image')
|
||||
target = LOCAL.parent / 'target'
|
||||
# Only these two RELEASE examples were missing. Original Clippy, EXEs and
|
||||
# unit links are hash-bound above and are deliberately not rerun/rebuilt.
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||
'-v', str(CODE) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target',
|
||||
'--entrypoint', 'cargo', image, 'build', '--manifest-path', '/src/Cargo.toml', '--locked', '--offline',
|
||||
'--target', TARGET, '-p', 'rmm-agent-windows', '--features', 'system-helper', '--release',
|
||||
'--example', 'runtime_state', '--example', 'system_state'], folder, 'release-examples')
|
||||
selected = {'agent': Path(prior['artifacts']['agent']['path']), 'helper': Path(prior['artifacts']['helper']['path']),
|
||||
'lib': Path(prior['unit_links']['lib']['path']), 'bin': Path(prior['unit_links']['bin']['path']),
|
||||
'probe': target / TARGET / 'release/examples/runtime_state.exe',
|
||||
'system_probe': target / TARGET / 'release/examples/system_state.exe'}
|
||||
artifacts = {}
|
||||
for kind, original in selected.items():
|
||||
output, retained = folder / NAMES[kind], folder / (NAMES[kind] + '.linked')
|
||||
original_sha = sha(original)
|
||||
for destination in (retained, output):
|
||||
shutil.copyfile(original, destination)
|
||||
destination.chmod(0o600)
|
||||
if kind in COUNTS:
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(folder) + ':/artifacts',
|
||||
'--entrypoint', 'x86_64-w64-mingw32-strip', image, '--strip-debug', '/artifacts/' + NAMES[kind]],
|
||||
folder, 'strip-' + kind)
|
||||
require(sha(original) == sha(retained) == original_sha, 'original links retained unchanged')
|
||||
data = output.read_bytes()
|
||||
offset = int.from_bytes(data[60:64], 'little')
|
||||
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows AMD64 PE')
|
||||
artifacts[kind] = {'path': str(output), 'name': NAMES[kind], 'sha256': sha(output), 'bytes': len(data),
|
||||
'original_link_path': str(retained), 'original_link_sha256': original_sha,
|
||||
'release_build': kind not in COUNTS, 'debug_stripped': kind in COUNTS}
|
||||
require(sources() == before and core_proof() == common and reused_qualification() == prior,
|
||||
'compiler inputs, original links and native Core proof unchanged before/after')
|
||||
manifest = {'schema_version': 1, 'type': 'rmm.windows.pipe-v2-build', 'source_files': before,
|
||||
'source_before_after_equal': True, 'code_root': str(CODE), 'access_root': str(ACCESS),
|
||||
'artifacts': artifacts, 'test_names_expected': TESTS, 'native_counts_expected': COUNTS,
|
||||
'core_native_proofs': common, 'reused_local_qualification': {'path': str(LOCAL), 'sha256': LOCAL_SHA},
|
||||
'build_image_id': image, 'transport_version': 2, 'raw_v1_controls_qualified': False,
|
||||
'production_clock_qualified': False, 'native_executed': False}
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps({'manifest': str(folder / 'manifest.json'), 'native_executed': False}))
|
||||
|
||||
|
||||
SCRIPT = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('run','read')-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Pipe V2 unit case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('native-pipe-v2-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Private unit type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty unit ACL'};foreach($r in $rules){if($r.AccessControlType-ne'Allow'-or$r.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Unit ACL'}}}
|
||||
function WriteNew($path,$value){$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f=[IO.File]::Open($path,'CreateNew','Write','Read');try{$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function ReadPrivate($path){Safe $path $false;if((Get-Item -LiteralPath $path).Length-gt196608){throw 'Unit report bound'};return (Get-Content -LiteralPath $path -Raw|ConvertFrom-Json)}
|
||||
Safe $root $true
|
||||
if($p.action-eq'read'){
|
||||
if(!(Test-Path -LiteralPath $case)){@{case_exists=$false;completed=$false;readback_only=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$i=ReadPrivate (Join-Path $case 'intent.json');if($i.manifest_sha256-cne$p.manifest_sha256){throw 'Original unit intent'}
|
||||
$result=Join-Path $case 'result.json';if(Test-Path -LiteralPath $result){ReadPrivate $result|ConvertTo-Json -Depth 16 -Compress;exit 0}
|
||||
$lists=@{};$reports=@{};foreach($kind in @('lib','bin')){$file=Join-Path $case ('list-'+$kind+'.json');if(Test-Path -LiteralPath $file){$lists[$kind]=ReadPrivate $file};$file=Join-Path $case ('report-'+$kind+'.json');if(Test-Path -LiteralPath $file){$reports[$kind]=ReadPrivate $file}}
|
||||
@{case_exists=$true;completed=$false;readback_only=$true;started=(Test-Path -LiteralPath (Join-Path $case 'started.json'));lists=$lists;reports=$reports}|ConvertTo-Json -Depth 16 -Compress;exit 0
|
||||
}
|
||||
if(Test-Path -LiteralPath $case){throw 'Existing unit case: readback only'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p
|
||||
function Run($exe,$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit process start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(30000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt65536-or$e.Result.Length-gt65536){throw 'Bounded unit output collection'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout=$o.Result;stderr=$e.Result}}finally{$c.Dispose()}}
|
||||
$lists=@{};$paths=@{}
|
||||
foreach($kind in @('lib','bin')){
|
||||
$a=$p.artifacts.$kind;if($a.sha256-notmatch'^[a-f0-9]{64}$'-or$a.name-cne('windows-tests-'+$kind+'.exe')){throw 'Fixed test artifact'};$folder=Join-Path $root $a.sha256;Safe $folder $true;$exe=Join-Path $folder $a.name;Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$a.sha256-or(Get-Item -LiteralPath $exe).Length-ne$a.bytes){throw 'Exact unit artifact'}
|
||||
$listed=Run $exe '--list --format terse';[string[]]$names=@($listed.stdout-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($names,[StringComparer]::Ordinal)
|
||||
$value=@{sha256=$a.sha256;names=$names;listed=$listed};WriteNew (Join-Path $case ('list-'+$kind+'.json')) $value
|
||||
if($listed.exit_code-ne0-or$listed.timed_out-or$names.Count-ne$p.counts.$kind-or(($names-join"`n")-cne(@($p.test_names.$kind)-join"`n"))){throw 'Exact complete native list before ANY tests'};$lists[$kind]=$value;$paths[$kind]=$exe
|
||||
}
|
||||
WriteNew (Join-Path $case 'both-lists-verified.json') @{manifest_sha256=$p.manifest_sha256;both_lists_verified_before_any_test=$true}
|
||||
WriteNew (Join-Path $case 'started.json') @{start_once=$true};$reports=@{}
|
||||
foreach($kind in @('lib','bin')){$run=Run $paths[$kind] '--test-threads=1';$value=@{sha256=$lists[$kind].sha256;names=$lists[$kind].names;listed=$lists[$kind].listed;result=$run};WriteNew (Join-Path $case ('report-'+$kind+'.json')) $value;$reports[$kind]=$value;if($run.exit_code-ne0-or$run.timed_out){throw 'Native unit execution failed; readback only'}}
|
||||
$value=@{completed=$true;manifest_sha256=$p.manifest_sha256;reports=$reports;both_lists_verified_before_any_test=$true;bootstrap_administrator_units=$true;local_service_proof=$false;native_pipe_proof=$false;rmm_jobs=$false;product_state_writes=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def verified(path, current=True):
|
||||
path = private_file(path)
|
||||
require(path.parent.parent == BUILD and path.parent.name.startswith('build-')
|
||||
and str(uuid.UUID(path.parent.name[6:])) == path.parent.name[6:], 'fixed private build namespace')
|
||||
value = cb.contract.protected_json(path)
|
||||
require(value['type'] == 'rmm.windows.pipe-v2-build' and value['schema_version'] == 1
|
||||
and value['source_before_after_equal'] is True and value['production_clock_qualified'] is False
|
||||
and value['transport_version'] == 2 and value['raw_v1_controls_qualified'] is False
|
||||
and value['native_executed'] is False
|
||||
and value['reused_local_qualification'] == {'path': str(LOCAL), 'sha256': LOCAL_SHA}
|
||||
and value['native_counts_expected'] == COUNTS and value['test_names_expected'] == TESTS
|
||||
and value['code_root'] == str(CODE) and value['access_root'] == str(ACCESS), 'exact V2 build profile')
|
||||
if current:
|
||||
require(value['source_files'] == sources() and value['core_native_proofs'] == core_proof(), 'current source/Core proof binding')
|
||||
require(set(value['artifacts']) == set(NAMES), 'six exact artifacts')
|
||||
for kind, item in value['artifacts'].items():
|
||||
output, original = private_file(item['path']), private_file(item['original_link_path'])
|
||||
require(output == path.parent / NAMES[kind] and original == path.parent / (NAMES[kind] + '.linked')
|
||||
and sha(output) == item['sha256'] and output.stat().st_size == item['bytes']
|
||||
and sha(original) == item['original_link_sha256']
|
||||
and item['release_build'] is (kind not in COUNTS)
|
||||
and item['debug_stripped'] is (kind in COUNTS), 'exact retained delivery and original link')
|
||||
return value
|
||||
|
||||
|
||||
def native(path, ident=None):
|
||||
path = path.resolve()
|
||||
manifest = verified(path, current=ident is None)
|
||||
if ident is None:
|
||||
ident = str(uuid.uuid4());folder = NATIVE / ident;folder.mkdir(mode=0o700, parents=True)
|
||||
save(folder / 'intent.json', {'id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
|
||||
'runner_sha256': sha(__file__), 'script_sha256': hashlib.sha256(SCRIPT.encode()).hexdigest()})
|
||||
before = {'counts': auto.scopes(), 'flags': auto.status()}
|
||||
require(auto.flags_disabled(before['flags']), 'closed fault flags before native units')
|
||||
save(folder / 'server-before.json', before)
|
||||
for kind in COUNTS:
|
||||
previous.upload(manifest['artifacts'][kind])
|
||||
save(folder / 'started-local.json', {'start_once': True})
|
||||
action = 'run'
|
||||
else:
|
||||
require(str(uuid.UUID(ident)) == ident, 'canonical original native case')
|
||||
folder = NATIVE / ident;intent = cb.contract.protected_json(folder / 'intent.json')
|
||||
require(intent['manifest_sha256'] == sha(path) and intent['manifest_path'] == str(path)
|
||||
and intent['runner_sha256'] == sha(__file__)
|
||||
and intent['script_sha256'] == hashlib.sha256(SCRIPT.encode()).hexdigest(), 'same original case; readback only')
|
||||
action = 'read'
|
||||
result = cb.powershell(SCRIPT, {'id': ident, 'action': action, 'manifest_sha256': sha(path),
|
||||
'artifacts': {k: manifest['artifacts'][k] for k in COUNTS},
|
||||
'counts': COUNTS, 'test_names': TESTS}, timeout=150)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('completed') is not True:
|
||||
print(json.dumps({'verified': False, 'case_id': ident, 'readback_only': True, 'completed': False,
|
||||
'case_exists': result.get('case_exists'), 'tests_repeated': False}))
|
||||
return
|
||||
require(result['manifest_sha256'] == sha(path) and set(result['reports']) == set(COUNTS)
|
||||
and result['both_lists_verified_before_any_test'] is True
|
||||
and result['rmm_jobs'] is False and result['product_state_writes'] is False
|
||||
and result['local_service_proof'] is False and result['native_pipe_proof'] is False,
|
||||
'actual narrow unit result, no runtime proof')
|
||||
for kind, actual in result['reports'].items():
|
||||
run, listed = actual['result'], actual['listed']
|
||||
names = re.findall(r'^(.+): test\r?$', listed['stdout'], re.M)
|
||||
require(actual['sha256'] == manifest['artifacts'][kind]['sha256']
|
||||
and names == actual['names'] == TESTS[kind] and len(set(names)) == COUNTS[kind]
|
||||
and listed['exit_code'] == run['exit_code'] == 0 and not listed['timed_out'] and not run['timed_out']
|
||||
and re.search(r'test result: ok\. ' + str(COUNTS[kind])
|
||||
+ r' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;', run['stdout']),
|
||||
'every exact named native unit passed, none skipped/filtered')
|
||||
before = cb.contract.protected_json(folder / 'server-before.json')
|
||||
require(auto.scopes() == before['counts'] and auto.status() == before['flags'], 'both central counts and closed flags unchanged')
|
||||
if action == 'run':
|
||||
verified(path) # Full before/after source and retained-artifact check.
|
||||
proof = {'verified': True, 'case_id': ident, 'manifest_path': str(path), 'manifest_sha256': sha(path),
|
||||
'native': result, 'no_jobs': True, 'clock_adapter_qualified': False,
|
||||
'local_service_proof': False, 'native_pipe_proof': False}
|
||||
destination = folder / 'passed.json'
|
||||
if destination.exists():
|
||||
require(cb.contract.protected_json(destination) == proof, 'retain exact original proof')
|
||||
else:
|
||||
save(destination, proof)
|
||||
print(json.dumps({'verified': True, 'case_id': ident, 'tests': COUNTS, 'proof': str(destination)}))
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('phase', choices=('build-local', 'native-units', 'readback'))
|
||||
parser.add_argument('--access-root', required=True, type=Path)
|
||||
parser.add_argument('--manifest', type=Path)
|
||||
parser.add_argument('--case')
|
||||
args = parser.parse_args()
|
||||
require(args.access_root == ACCESS and not args.access_root.is_symlink(), 'exact existing access root')
|
||||
if args.phase == 'build-local':
|
||||
require(args.manifest is None and args.case is None, 'build only')
|
||||
build()
|
||||
else:
|
||||
require(args.manifest is not None and ((args.phase == 'readback') == bool(args.case)), 'explicit manifest and original readback case')
|
||||
native(args.manifest, args.case)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print('WINDOWS_PIPE_V2_QUALIFICATION_INCOMPLETE:' + type(error).__name__)
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,503 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M3 Event Log pure contracts: Linux VM FIRST, then Windows VM.
|
||||
|
||||
Only two fixed test executables run in separate bootstrap scratch directories.
|
||||
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
|
||||
Native execution is explicit; any lost reply permits same-case readback only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import vm_access_check as access
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / 'devstate/windows-eventlog-contracts'
|
||||
IMAGE = 'rust-discovery-durable-final-build:local'
|
||||
PROFILE = 'windows-eventlog-contracts-v1'
|
||||
LINUX_REMOTE = '/var/lib/rmm-windows-eventlog-contracts'
|
||||
KINDS = ('domain', 'contracts')
|
||||
REVIEWED_M3 = {'crates/agent-core/src/auth.rs': '360e6af153d7d5b31717e0f8fbc0e988850c7fa032eaa3a657962187f5a657e4',
|
||||
'crates/agent-core/tests/contracts.rs': '2482928f45e3236ae079329668849f5ccd2e01503e56cd3b8e37579af3f21e9c',
|
||||
'crates/agent-windows/Cargo.toml': '886f0ee1bc8b02133325bc1f1c4db76db3f0194435fba151eb1f3ca42e0660dc',
|
||||
'crates/agent-windows/src/actions.rs': 'a13e3746ee05619b993b6828e9c7b103fa5d3f9d47f1b52de595da3c57910180',
|
||||
'crates/agent-windows/src/event_log.rs': '00756bc178c5e67eca0de64fe55f6a1b3865e27d33f3e1c87fa575b5be81706d',
|
||||
'crates/agent-windows/src/event_log_job.rs': '08798cf194c405e93cd5874517857a06649aa47a0cc8c933fbd924018670113e',
|
||||
'crates/agent-windows/src/job_binding.rs': '488bab9f74b84023cf5b8f35f6f624903d98a82e886ef78d7ab93c8d99281e26',
|
||||
'crates/agent-windows/src/lib.rs': '391764708bfd6a8ab5546ef299d40f54dc4eefa02d4334dead7a16e46a22cd66',
|
||||
'crates/agent-windows/src/runtime.rs': '21c09cbc2a0b4caf5a4e273a20eac63dc870bb942a3683fb5b7ba6f7b36b4674',
|
||||
'crates/domain/src/jobs.rs': 'b9950270fc77086d06b3f7aa177aba2ad13155c10653b3ee73a2be436365cf1f',
|
||||
'crates/server/src/job_gateway.rs': '234542f4783c95cfcfd567495bfb7233f2c05a1b88dd87fb85a916d32eae5fc5',
|
||||
'crates/server/src/jobs.rs': '5bff6fe61fce601cd03721cebd82bca05b5af83d3640bf862ba6d603ceb7e3e9'}
|
||||
COUNTS = {'linux': {'domain': 17, 'contracts': 7}, 'windows': {'domain': 17, 'contracts': 6}}
|
||||
DOMAIN_NAMES = sorted(('apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
|
||||
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
|
||||
'inventory_document::tests::additive_metadata_and_bounds',
|
||||
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
|
||||
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
|
||||
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes', 'jobs::tests::codec_golden_and_exact_script_bytes',
|
||||
'jobs::tests::no_terminal_replay_or_unknown_restart', 'jobs::tests::permit_codec_golden_all_bindings',
|
||||
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
|
||||
'jobs::tests::windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes',
|
||||
'jobs::tests::windows_interpreter_and_capability_contract',
|
||||
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
|
||||
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
|
||||
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
|
||||
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
|
||||
'tests::production_never_accepts_development_auth'))
|
||||
CONTRACT_NAMES = sorted(('atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
|
||||
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
|
||||
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
|
||||
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
|
||||
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
|
||||
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
|
||||
'portable_acceptance_requires_platform_capability_and_exact_redelivery'))
|
||||
UNIX_ONLY = 'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering'
|
||||
EXPECTED = {'linux': {'domain': DOMAIN_NAMES, 'contracts': CONTRACT_NAMES},
|
||||
'windows': {'domain': DOMAIN_NAMES, 'contracts': [x for x in CONTRACT_NAMES if x != UNIX_ONLY]}}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def object_pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
item = Path(path).lstat()
|
||||
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
||||
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
||||
'private owned regular path')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
private(Path(path).parent, True)
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def setup_state():
|
||||
os.umask(0o077)
|
||||
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = STATE.parent.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
||||
'owned non-world-writable devstate parent')
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
private(STATE, True)
|
||||
|
||||
|
||||
def source_files():
|
||||
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
|
||||
'deploy/windows_eventlog_acceptance.py', 'deploy/remote_client_bootstrap.py',
|
||||
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/windows/client_bootstrap.py')]
|
||||
paths += list((ROOT / 'crates').rglob('Cargo.toml'))
|
||||
for name in ('domain', 'agent-core', 'protocol', 'server', 'agent-windows'):
|
||||
paths += [p for p in (ROOT / 'crates' / name).rglob('*') if p.is_file()]
|
||||
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
|
||||
for path in paths:
|
||||
require(not path.is_symlink() and path.is_file(), 'regular source inputs only')
|
||||
value = {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
|
||||
require(all(value[name] == digest for name, digest in REVIEWED_M3.items()), 'exact frozen reviewed M3 sources')
|
||||
return value
|
||||
|
||||
|
||||
def names(raw):
|
||||
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
|
||||
|
||||
|
||||
def check_list(raw, expected):
|
||||
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
|
||||
'terse list contains only exact tests, no benchmarks or extra entries')
|
||||
|
||||
|
||||
def check_output(raw, count):
|
||||
require(re.search(rb'^test result: ok\. ' + str(count).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
|
||||
'all tests passed without skipped or filtered tests')
|
||||
|
||||
|
||||
def command(args, folder, timeout=300):
|
||||
index = len(list(folder.glob('command-*.json')))
|
||||
try:
|
||||
done = subprocess.run(args, capture_output=True, timeout=timeout)
|
||||
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
|
||||
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||
require(done.returncode == 0, 'local qualification command failed; private output retained')
|
||||
return done.stdout
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('local qualification timed out; no automatic retry') from None
|
||||
|
||||
|
||||
def scripts():
|
||||
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
||||
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
|
||||
|
||||
|
||||
def build():
|
||||
setup_state()
|
||||
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
|
||||
before = source_files(); save(folder / 'source-before.json', before)
|
||||
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable local build image')
|
||||
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
|
||||
common = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||
'-v', str(ROOT) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target', '--entrypoint', 'cargo', image]
|
||||
artifacts = {'linux': {}, 'windows': {}}
|
||||
for platform, triple in [('linux', 'x86_64-unknown-linux-gnu'), ('windows', 'x86_64-pc-windows-gnu')]:
|
||||
for kind in KINDS:
|
||||
package, selection = ('rmm-domain', ['--lib']) if kind == 'domain' else ('rmm-agent-core', ['--test', 'contracts'])
|
||||
options = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline', '--target', triple, '-p', package]
|
||||
command(common + ['clippy'] + options + selection + ['--', '-D', 'warnings'], folder)
|
||||
raw = command(common + ['test'] + options + selection + ['--release', '--no-run', '--message-format=json'], folder)
|
||||
linked = []
|
||||
for line in raw.splitlines():
|
||||
try: item = json.loads(line)
|
||||
except ValueError: continue
|
||||
expected_name = 'rmm_domain' if kind == 'domain' else 'contracts'
|
||||
if item.get('reason') == 'compiler-artifact' and item.get('executable') and item.get('profile', {}).get('test') and item['target']['name'] == expected_name:
|
||||
linked.append(target / Path(item['executable']).relative_to('/target'))
|
||||
require(len(linked) == 1, 'exact selected unit executable')
|
||||
destination = folder / platform; destination.mkdir(mode=0o700, exist_ok=True)
|
||||
original = destination / (kind + '.linked')
|
||||
delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
|
||||
for path in (original, delivery): shutil.copyfile(linked[0], path); path.chmod(0o600)
|
||||
linked_sha = sha(original)
|
||||
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(destination) + ':/artifacts',
|
||||
'--entrypoint', tool, image, '--strip-debug', '/artifacts/' + delivery.name], folder)
|
||||
require(sha(linked[0]) == sha(original) == linked_sha, 'unstripped original link preserved')
|
||||
data = delivery.read_bytes()
|
||||
if platform == 'linux':
|
||||
require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
|
||||
else:
|
||||
offset = int.from_bytes(data[60:64], 'little')
|
||||
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
|
||||
artifacts[platform][kind] = dict(path=str(delivery.resolve()), sha256=sha(delivery), bytes=len(data),
|
||||
original_link_path=str(original.resolve()), original_link_sha256=linked_sha, debug_stripped_delivery=True)
|
||||
# Run exactly the deliverable Linux bytes in an offline disposable container.
|
||||
for kind, item in artifacts['linux'].items():
|
||||
invoke = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=128m',
|
||||
'-v', item['path'] + ':/unit:ro', '--entrypoint', 'python3', image, '-c']
|
||||
for mode in ('list', 'run'):
|
||||
args = ['--list', '--format', 'terse'] if mode == 'list' else ['--test-threads=1']
|
||||
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
|
||||
raw = command(invoke + [script], folder)
|
||||
save(folder / ('local-linux-' + kind + '-' + mode + '.json'), dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
if mode == 'list': check_list(raw.decode(), EXPECTED['linux'][kind])
|
||||
else: check_output(raw, COUNTS['linux'][kind])
|
||||
dynamic = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '-d', '/unit'], folder).decode()
|
||||
versions = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '--version-info', '/unit'], folder).decode()
|
||||
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda x: tuple(map(int, x.split('.'))))
|
||||
require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 39), 'VM-compatible glibc requirement')
|
||||
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))
|
||||
require(source_files() == before, 'source and runner unchanged through qualification')
|
||||
manifest = dict(schema_version=1, profile=PROFILE, source_files=before, source_before_after_equal=True,
|
||||
reviewed_m3_source_pins=REVIEWED_M3, m3_adapter_sources_hash_bound_only=True, live_eventlog_query=False,
|
||||
runner_sha256=sha(__file__), scripts=scripts(), test_names=EXPECTED, test_counts=COUNTS, artifacts=artifacts,
|
||||
build_image_id=image, both_targets_clippy_D_warnings=True, linux_lists_actual=True,
|
||||
windows_lists_expected_until_native=True, local_linux_tests_passed=24, native_linux_executed=False,
|
||||
native_windows_executed=False, product_state_writes=False, rmm_jobs=False)
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps(dict(manifest=str((folder / 'manifest.json').resolve()), manifest_sha256=sha(folder / 'manifest.json'),
|
||||
linux_tests=24, windows_tests_expected=23, native_executed=False)))
|
||||
|
||||
|
||||
def verified(path, new_run):
|
||||
path = path.absolute(); private(path.parent, True)
|
||||
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
|
||||
value = load(path)
|
||||
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
|
||||
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
|
||||
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
|
||||
and value['reviewed_m3_source_pins'] == REVIEWED_M3 and value['m3_adapter_sources_hash_bound_only'] is True
|
||||
and value['live_eventlog_query'] is False,
|
||||
'original manifest/runner/remote scripts/profile binding')
|
||||
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
|
||||
for platform in COUNTS:
|
||||
require(set(value['artifacts'][platform]) == set(KINDS), 'exact two artifacts')
|
||||
for kind, item in value['artifacts'][platform].items():
|
||||
suffix = '.exe' if platform == 'windows' else ''
|
||||
require(Path(item['path']) == path.parent / platform / (kind + suffix)
|
||||
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
|
||||
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
|
||||
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
|
||||
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def access_settings(root, platform):
|
||||
"""Read strictly parsed existing access only when the parent executes native."""
|
||||
require(root is not None and not root.is_symlink(), 'explicit real access-root required')
|
||||
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
||||
if platform == 'linux':
|
||||
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
||||
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
||||
else:
|
||||
cfg = access.load_config(root / 'credentials/server.conf')
|
||||
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
||||
credentials = root / 'credentials'; private(credentials, True)
|
||||
record = load(credentials / 'windows-dev-access.json')
|
||||
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
||||
expires = dt.datetime.fromisoformat(record['expires_at'])
|
||||
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
||||
key = str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
||||
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
||||
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
||||
private(credentials / 'windows-dev.known_hosts')
|
||||
return prefix
|
||||
|
||||
|
||||
def transport(prefix, command_text, data, folder, timeout=60):
|
||||
"""No stdout/stderr escapes the private case directory on transport failure."""
|
||||
try:
|
||||
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
||||
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
||||
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
||||
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
||||
return value
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('native reply lost; read original case only') from None
|
||||
|
||||
|
||||
def linux_rpc(prefix, payload, folder):
|
||||
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
||||
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return transport(prefix, 'python3 -', code.encode(), folder)
|
||||
|
||||
|
||||
def windows_rpc(prefix, payload, folder):
|
||||
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
||||
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
|
||||
|
||||
|
||||
def upload(prefix, item, destination, folder, kind):
|
||||
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
||||
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
||||
if '-p' in args: args[args.index('-p')] = '-P'
|
||||
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
||||
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
||||
try:
|
||||
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
||||
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
||||
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
||||
|
||||
|
||||
def linux_case(p):
|
||||
import resource
|
||||
import stat
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-eventlog-contracts-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain', 'contracts'}, 'fixed Linux root qualification')
|
||||
root = Path('/var/lib/rmm-windows-eventlog-contracts')
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
|
||||
os.umask(0o077)
|
||||
case = root / ident
|
||||
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
|
||||
if p['action'] == 'prepare':
|
||||
if not root.exists(): root.mkdir(mode=0o700)
|
||||
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
|
||||
return dict(id=ident, prepared=True)
|
||||
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
|
||||
original = json.loads((case / 'intent.json').read_bytes())
|
||||
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists(): return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start')
|
||||
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
|
||||
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
|
||||
temp = case / 'tmp'; temp.mkdir(mode=0o700)
|
||||
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
|
||||
listings = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
binary = case / kind; safe(binary, False)
|
||||
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
|
||||
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
|
||||
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
|
||||
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == {'domain': 17, 'contracts': 7}[kind], 'exact native test names before ANY test execution')
|
||||
listings[kind] = actual
|
||||
reports = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
timed = False
|
||||
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
|
||||
except subprocess.TimeoutExpired: timed = True; code = None
|
||||
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
|
||||
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
|
||||
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
|
||||
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
|
||||
write(case / (kind + '-result.json'), reports[kind])
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
|
||||
scripts=p['scripts'], reports=reports, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
|
||||
write(case / 'result.json', value); return value
|
||||
|
||||
|
||||
WINDOWS = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-eventlog-contracts-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-eventlog-contracts-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
|
||||
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
|
||||
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $root $true
|
||||
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
||||
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
|
||||
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
|
||||
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
|
||||
$lists=@{};$executables=@{}
|
||||
foreach($kind in @('domain','contracts')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''}|Sort-Object);$count=if($kind-eq'domain'){17}else{6};if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};$lists[$kind]=$actual;$executables[$kind]=$exe}
|
||||
$reports=@{};foreach($kind in @('domain','contracts')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
|
||||
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def check_result(manifest, platform, value, payload):
|
||||
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
||||
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
||||
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
|
||||
and value.get('environment_cleared') is True and set(value['reports']) == set(KINDS), 'complete native original binding')
|
||||
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
|
||||
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
|
||||
for kind, item in value['reports'].items():
|
||||
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
|
||||
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
|
||||
check_output(raw, COUNTS[platform][kind])
|
||||
|
||||
|
||||
def execute(path, platform, access_root, case_id=None):
|
||||
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
|
||||
prefix = access_settings(access_root, platform)
|
||||
if case_id is None:
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
|
||||
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED[platform])
|
||||
if platform == 'windows':
|
||||
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
|
||||
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
|
||||
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED['linux'])
|
||||
check_result(manifest, 'linux', proof['native'], linux_payload)
|
||||
payload['linux_proof_sha256'] = sha(proof_path)
|
||||
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
|
||||
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
|
||||
save(folder / 'intent.json', intent)
|
||||
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
run_read = False
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
|
||||
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
|
||||
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
|
||||
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
|
||||
payload = intent['payload']; run_read = True
|
||||
rpc = linux_rpc if platform == 'linux' else windows_rpc
|
||||
if not run_read:
|
||||
result = rpc(prefix, dict(payload, action='prepare'), folder)
|
||||
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS:
|
||||
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-eventlog-contracts-' + case_id + '/' + kind + '.exe'
|
||||
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
|
||||
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('status'):
|
||||
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
|
||||
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
|
||||
check_result(manifest, platform, result, payload)
|
||||
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
|
||||
destination = path.parent / (platform + '-passed.json')
|
||||
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
|
||||
else: save(destination, proof)
|
||||
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
|
||||
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
|
||||
manifest_sha256=sha(path), proof_sha256=sha(destination))))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
|
||||
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
|
||||
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
|
||||
if args.action == 'build-local':
|
||||
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
|
||||
elif args.action.startswith('readback-'):
|
||||
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
|
||||
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
|
||||
else:
|
||||
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
|
||||
execute(args.manifest, args.action, args.access_root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print(json.dumps(dict(error='WINDOWS_EVENTLOG_CONTRACT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,692 @@
|
||||
#!/usr/bin/env python3
|
||||
"""M4 MSI pure common contracts: Linux VM FIRST, then Windows VM.
|
||||
|
||||
Only fixed common test executables run in separate bootstrap scratch directories.
|
||||
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
|
||||
Native execution is explicit; any lost reply permits same-case readback only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import vm_access_check as access
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / 'devstate/windows-msi-contracts'
|
||||
IMAGE = 'rust-discovery-durable-final-build:local'
|
||||
PROFILE = 'windows-msi-contracts-v1'
|
||||
LINUX_REMOTE = '/var/lib/rmm-windows-msi-contracts'
|
||||
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||
BACKEND = ROOT / 'devstate/windows-msi-integration/local-qualification.json'
|
||||
BACKEND_SHA = 'b7bced0a341ffb88af8b584cbe8355ff1021add541004347f609f6136a684b74'
|
||||
# Actual local Linux RELEASE --list was obtained before fixing these lists.
|
||||
# Windows lists remain EXPECTED until the native Windows process emits them.
|
||||
REVIEWED_BACKEND = {'crates/domain/src/lib.rs': '7919c099a8b568259b9b197d1742cdc11844523c64654325b6c142ae437dda1f',
|
||||
'crates/domain/src/jobs.rs': 'ff7f086a28e5e17832fa4afc974ce8395c7887360c3291d27d1cc7ae12bab117',
|
||||
'crates/domain/src/windows_execution.rs': 'aa2c5916c9d6c9d9ab8e9bd0d1051920fcb2ae9ecf4c18cf6ee89c4668b9b460',
|
||||
'crates/agent-core/src/auth.rs': '86cda2e10321bcb3591013880f11e53a8bcb01c53521bbcc28d38d6b1f5402bd',
|
||||
'crates/agent-core/tests/contracts.rs': 'f57fe9b938b8e563229b9da7c77b6df7b419f0ba41ef05abb1f7f9e3ff2e61e9',
|
||||
'crates/server/src/agent_artifacts.rs': '5f68ea4a26de529d814b7365b85f978ced7715c7da8fa2a435021e3e953b506e',
|
||||
'crates/server/src/catalog.rs': 'c4c293271a36aba80fac00b72e2936ed2c11bccf49e511d7003bd95574fb0e04',
|
||||
'crates/server/src/job_gateway.rs': '421672d7a283fcda5bc00854b53eb86c4236621336d5cf6b72c43d288fad74de',
|
||||
'crates/server/src/jobs.rs': '725a2f9c61180c4d938bcf7383ee78c5d50b83b703665195502548140126fce6',
|
||||
'crates/server/src/main.rs': 'c8ddc2a1a7cd29122f5590902f25c2711eef6e2f5488e2e7869c034ddf27394e',
|
||||
'crates/server/src/windows_policy.rs': 'd0ffd67f4f2c56a681c44617962b3834f02cbbc6ba076461b856f4e87ce6c222',
|
||||
'crates/server/src/windows_msi_catalog.rs': 'dcb704b02a5d5d5bfff5b8e34a712cf5a0b9c32cb21af242252976d0c0b0ad84',
|
||||
'migrations/0014_windows_msi_catalog.sql': '893440fc75914d4e7e3a62055f693562c6a093924eab77a20f6b5428f63d20d0'}
|
||||
EXPECTED = {'linux': {'domain': ['apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
|
||||
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
|
||||
'inventory_document::tests::additive_metadata_and_bounds',
|
||||
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
|
||||
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
|
||||
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes',
|
||||
'jobs::tests::codec_golden_and_exact_script_bytes',
|
||||
'jobs::tests::no_terminal_replay_or_unknown_restart',
|
||||
'jobs::tests::permit_codec_golden_all_bindings',
|
||||
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
|
||||
'jobs::tests::windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes',
|
||||
'jobs::tests::windows_interpreter_and_capability_contract',
|
||||
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
|
||||
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
|
||||
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
|
||||
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
|
||||
'tests::production_never_accepts_development_auth',
|
||||
'windows_execution::tests::ensure_msi_action_is_strict_opt_in_and_system_windows_only_without_linux_byte_changes',
|
||||
'windows_execution::tests::immutable_fixture_recipe_rejects_reboot_url_transform_and_implicit_upgrade',
|
||||
'windows_execution::tests::major_upgrade_requires_explicit_exact_predecessor_new_package_and_same_family'],
|
||||
'contracts': ['atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
|
||||
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
|
||||
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
|
||||
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
|
||||
'historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority',
|
||||
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
|
||||
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
|
||||
'portable_acceptance_requires_platform_capability_and_exact_redelivery'],
|
||||
'helper-reconcile': ['abandon_after_expiry_records_deny_only_evidence_and_requires_normal_signed_unlock',
|
||||
'abandon_preserves_existing_known_unknown_missing_start_and_foreign_request_rows',
|
||||
'abandon_rejects_wrong_signature_scope_clock_boot_lineage_instance_and_dispatch_proof',
|
||||
'abandon_storage_failure_rolls_back_consumption_start_and_outcome_together',
|
||||
'both_live_profiles_apply_one_signature_and_checkpoint_without_inheriting_readiness',
|
||||
'checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor',
|
||||
'checkpoint_rollback_is_sticky_and_cannot_be_fixed_by_omission',
|
||||
'clean_ready_shared_lock_and_reopen_start_closed',
|
||||
'definitive_unlock_is_transactional_idempotent_and_keeps_tombstones',
|
||||
'exact_signatures_fake_key_wrong_domain_and_all_identity_bindings',
|
||||
'false_clock_expiry_and_invalid_independent_key_stay_closed',
|
||||
'general_and_apt_instances_share_fencing_but_never_inherit_a_process_gate',
|
||||
'independently_remembered_agent_journal_cannot_be_replaced_by_server_ready',
|
||||
'malformed_original_protobuf_or_digest_does_not_open_gate',
|
||||
'missing_signed_checkpoint_history_closes_the_live_gate_stickily',
|
||||
'mutated_root_ledger_after_capture_is_not_the_signed_snapshot',
|
||||
'old_process_response_fails_after_fresh_capture_even_inside_ttl',
|
||||
'omitted_unknown_root_row_is_sticky_despite_signed_ready',
|
||||
'real_local_boot_must_match_signed_reboot_completion',
|
||||
'root_and_system_are_distinct_explicit_helper_domains',
|
||||
'shared_database_only_and_missing_local_start_fail_closed',
|
||||
'signed_noncanonical_outcome_bytes_do_not_unlock_root_consumption',
|
||||
'stale_process_connection_does_not_poison_a_new_fenced_process',
|
||||
'targeted_final_unlock_does_not_release_an_unrelated_unknown',
|
||||
'unknown_code_or_no_result_never_unlocks_even_signed_ready',
|
||||
'unrelated_action_plan_and_previous_outcome_cannot_unlock'],
|
||||
'reconcile': ['accepted_unstarted_keeps_ids_and_never_consumes_or_executes',
|
||||
'authenticated_helper_outcome_is_imported_as_new_durable_evidence_not_reexecuted',
|
||||
'clean_reconnect_and_reopen_require_new_signed_challenge',
|
||||
'crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes',
|
||||
'crash_after_result_commit_before_finish_retains_exact_result_and_local_prior',
|
||||
'crash_before_running_event_recovers_real_consumption_without_inventing_completion',
|
||||
'definite_nonstart_result_is_unconsumed_not_ambiguous',
|
||||
'exact_signatures_all_identity_channel_checkpoint_and_request_bindings',
|
||||
'final_result_preserves_original_envelope_outputs_and_exact_acks',
|
||||
'foreign_ack_and_noncanonical_outcome_are_transactionally_rejected',
|
||||
'helper_gate_requires_exact_signed_instruction_and_applied_checkpoint',
|
||||
'helper_omitting_a_consumed_root_attempt_is_a_sticky_restore_fault',
|
||||
'independent_helper_checkpoint_regression_is_sticky',
|
||||
'independent_local_outcome_mismatch_never_unlocks',
|
||||
'missing_server_job_fault_is_sticky_even_if_attempt_disappears_later',
|
||||
'negative_server_revision_never_rolls_back_local_unknown_revision',
|
||||
'original_completion_after_reconnect_unknown_is_recovered_without_reexecuting',
|
||||
'reboot_keeps_lock_until_signed_new_authenticated_boot_inventory_evidence',
|
||||
'requesting_running_and_omitted_attempts_cannot_regain_readiness',
|
||||
'rollback_and_false_clock_close_mutations_but_do_not_destroy_journal',
|
||||
'signed_attempt_mutation_or_terminal_regression_is_rejected',
|
||||
'signed_terminal_nonstart_stays_unconsumed_across_sync_and_pending_denial',
|
||||
'signed_unlock_still_rejects_a_missing_local_outcome_in_legacy_crash_window',
|
||||
'system_helper_import_requires_explicit_system_identity_and_never_root_alias',
|
||||
'terminal_labels_never_override_grant_consumption_or_unclear_attempts',
|
||||
'uncertain_request_preserves_pending_request_and_last_applied_anchor'],
|
||||
'linux-helper': ['both_live_profiles_apply_one_signature_and_checkpoint_without_inheriting_readiness',
|
||||
'checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor',
|
||||
'checkpoint_rollback_is_sticky_and_cannot_be_fixed_by_omission',
|
||||
'clean_ready_shared_lock_and_reopen_start_closed',
|
||||
'definitive_unlock_is_transactional_idempotent_and_keeps_tombstones',
|
||||
'exact_signatures_fake_key_wrong_domain_and_all_identity_bindings',
|
||||
'false_clock_expiry_and_invalid_independent_key_stay_closed',
|
||||
'general_and_apt_instances_share_fencing_but_never_inherit_a_process_gate',
|
||||
'independently_remembered_agent_journal_cannot_be_replaced_by_server_ready',
|
||||
'malformed_original_protobuf_or_digest_does_not_open_gate',
|
||||
'missing_signed_checkpoint_history_closes_the_live_gate_stickily',
|
||||
'mutated_root_ledger_after_capture_is_not_the_signed_snapshot',
|
||||
'old_process_response_fails_after_fresh_capture_even_inside_ttl',
|
||||
'omitted_unknown_root_row_is_sticky_despite_signed_ready',
|
||||
'real_local_boot_must_match_signed_reboot_completion',
|
||||
'shared_database_only_and_missing_local_start_fail_closed',
|
||||
'signed_noncanonical_outcome_bytes_do_not_unlock_root_consumption',
|
||||
'stale_process_connection_does_not_poison_a_new_fenced_process',
|
||||
'targeted_final_unlock_does_not_release_an_unrelated_unknown',
|
||||
'unknown_code_or_no_result_never_unlocks_even_signed_ready',
|
||||
'unrelated_action_plan_and_previous_outcome_cannot_unlock']},
|
||||
'windows': {'domain': ['apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
|
||||
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
|
||||
'inventory_document::tests::additive_metadata_and_bounds',
|
||||
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
|
||||
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
|
||||
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes',
|
||||
'jobs::tests::codec_golden_and_exact_script_bytes',
|
||||
'jobs::tests::no_terminal_replay_or_unknown_restart',
|
||||
'jobs::tests::permit_codec_golden_all_bindings',
|
||||
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
|
||||
'jobs::tests::windows_event_log_fixture_scope_limits_and_exact_24h_preserve_linux_bytes',
|
||||
'jobs::tests::windows_interpreter_and_capability_contract',
|
||||
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
|
||||
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
|
||||
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
|
||||
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
|
||||
'tests::production_never_accepts_development_auth',
|
||||
'windows_execution::tests::ensure_msi_action_is_strict_opt_in_and_system_windows_only_without_linux_byte_changes',
|
||||
'windows_execution::tests::immutable_fixture_recipe_rejects_reboot_url_transform_and_implicit_upgrade',
|
||||
'windows_execution::tests::major_upgrade_requires_explicit_exact_predecessor_new_package_and_same_family'],
|
||||
'contracts': ['atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
|
||||
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
|
||||
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
|
||||
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
|
||||
'historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority',
|
||||
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
|
||||
'portable_acceptance_requires_platform_capability_and_exact_redelivery'],
|
||||
'helper-reconcile': ['abandon_after_expiry_records_deny_only_evidence_and_requires_normal_signed_unlock',
|
||||
'abandon_preserves_existing_known_unknown_missing_start_and_foreign_request_rows',
|
||||
'abandon_rejects_wrong_signature_scope_clock_boot_lineage_instance_and_dispatch_proof',
|
||||
'abandon_storage_failure_rolls_back_consumption_start_and_outcome_together',
|
||||
'both_live_profiles_apply_one_signature_and_checkpoint_without_inheriting_readiness',
|
||||
'checkpoint_repair_verifies_complete_signed_history_and_detects_removed_predecessor',
|
||||
'checkpoint_rollback_is_sticky_and_cannot_be_fixed_by_omission',
|
||||
'clean_ready_shared_lock_and_reopen_start_closed',
|
||||
'definitive_unlock_is_transactional_idempotent_and_keeps_tombstones',
|
||||
'exact_signatures_fake_key_wrong_domain_and_all_identity_bindings',
|
||||
'false_clock_expiry_and_invalid_independent_key_stay_closed',
|
||||
'general_and_apt_instances_share_fencing_but_never_inherit_a_process_gate',
|
||||
'independently_remembered_agent_journal_cannot_be_replaced_by_server_ready',
|
||||
'malformed_original_protobuf_or_digest_does_not_open_gate',
|
||||
'missing_signed_checkpoint_history_closes_the_live_gate_stickily',
|
||||
'mutated_root_ledger_after_capture_is_not_the_signed_snapshot',
|
||||
'old_process_response_fails_after_fresh_capture_even_inside_ttl',
|
||||
'omitted_unknown_root_row_is_sticky_despite_signed_ready',
|
||||
'real_local_boot_must_match_signed_reboot_completion',
|
||||
'root_and_system_are_distinct_explicit_helper_domains',
|
||||
'shared_database_only_and_missing_local_start_fail_closed',
|
||||
'signed_noncanonical_outcome_bytes_do_not_unlock_root_consumption',
|
||||
'stale_process_connection_does_not_poison_a_new_fenced_process',
|
||||
'targeted_final_unlock_does_not_release_an_unrelated_unknown',
|
||||
'unknown_code_or_no_result_never_unlocks_even_signed_ready',
|
||||
'unrelated_action_plan_and_previous_outcome_cannot_unlock'],
|
||||
'reconcile': ['accepted_unstarted_keeps_ids_and_never_consumes_or_executes',
|
||||
'authenticated_helper_outcome_is_imported_as_new_durable_evidence_not_reexecuted',
|
||||
'clean_reconnect_and_reopen_require_new_signed_challenge',
|
||||
'crash_after_durable_outcome_before_result_recovers_original_then_signed_sync_closes',
|
||||
'crash_after_result_commit_before_finish_retains_exact_result_and_local_prior',
|
||||
'crash_before_running_event_recovers_real_consumption_without_inventing_completion',
|
||||
'definite_nonstart_result_is_unconsumed_not_ambiguous',
|
||||
'exact_signatures_all_identity_channel_checkpoint_and_request_bindings',
|
||||
'final_result_preserves_original_envelope_outputs_and_exact_acks',
|
||||
'foreign_ack_and_noncanonical_outcome_are_transactionally_rejected',
|
||||
'helper_gate_requires_exact_signed_instruction_and_applied_checkpoint',
|
||||
'helper_omitting_a_consumed_root_attempt_is_a_sticky_restore_fault',
|
||||
'independent_helper_checkpoint_regression_is_sticky',
|
||||
'independent_local_outcome_mismatch_never_unlocks',
|
||||
'missing_server_job_fault_is_sticky_even_if_attempt_disappears_later',
|
||||
'negative_server_revision_never_rolls_back_local_unknown_revision',
|
||||
'original_completion_after_reconnect_unknown_is_recovered_without_reexecuting',
|
||||
'reboot_keeps_lock_until_signed_new_authenticated_boot_inventory_evidence',
|
||||
'requesting_running_and_omitted_attempts_cannot_regain_readiness',
|
||||
'rollback_and_false_clock_close_mutations_but_do_not_destroy_journal',
|
||||
'signed_attempt_mutation_or_terminal_regression_is_rejected',
|
||||
'signed_terminal_nonstart_stays_unconsumed_across_sync_and_pending_denial',
|
||||
'signed_unlock_still_rejects_a_missing_local_outcome_in_legacy_crash_window',
|
||||
'system_helper_import_requires_explicit_system_identity_and_never_root_alias',
|
||||
'terminal_labels_never_override_grant_consumption_or_unclear_attempts',
|
||||
'uncertain_request_preserves_pending_request_and_last_applied_anchor']}}
|
||||
COUNTS = {platform: {kind: len(names) for kind, names in lists.items()} for platform, lists in EXPECTED.items()}
|
||||
KINDS = {'linux': ('domain','contracts','helper-reconcile','reconcile','linux-helper'),
|
||||
'windows': ('domain','contracts','helper-reconcile','reconcile')}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def object_pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
item = Path(path).lstat()
|
||||
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
||||
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
||||
'private owned regular path')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
private(Path(path).parent, True)
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def setup_state():
|
||||
os.umask(0o077)
|
||||
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = STATE.parent.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
||||
'owned non-world-writable devstate parent')
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
private(STATE, True)
|
||||
|
||||
|
||||
def source_files():
|
||||
require(sha(BACKEND) == BACKEND_SHA, 'exact reviewed local backend qualification')
|
||||
reviewed = load(BACKEND)
|
||||
require(reviewed['source_files'] == REVIEWED_BACKEND, 'reviewed thirteen backend/common pins')
|
||||
names = {'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'deploy/windows_msi_contract_acceptance.py',
|
||||
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/remote_client_bootstrap.py',
|
||||
'deploy/windows/client_bootstrap.py', 'tools/apt-transaction/apt_transaction.py',
|
||||
'tools/apt-transaction/hook', 'deploy/linux/rmm-apt-helper.service',
|
||||
'tests/apt_transaction/fixtures/planning-canonical.json'}
|
||||
names.update(str(p.relative_to(ROOT)) for p in (ROOT / 'crates').glob('*/Cargo.toml'))
|
||||
for crate in ('domain', 'agent-core', 'agent-linux', 'privileged-helper', 'protocol'):
|
||||
names.update(str(p.relative_to(ROOT)) for p in (ROOT / 'crates' / crate).rglob('*')
|
||||
if p.is_file() and p.suffix in ('.rs', '.toml', '.c', '.h', '.idl', '.proto'))
|
||||
names.update(str(p.relative_to(ROOT)) for p in (ROOT / 'proto').rglob('*') if p.is_file())
|
||||
names.update(REVIEWED_BACKEND)
|
||||
for name in names: require((ROOT / name).is_file() and not (ROOT / name).is_symlink(), 'regular fixed source inputs')
|
||||
result = {name: sha(ROOT / name) for name in sorted(names)}
|
||||
require(all(result[name] == digest for name, digest in REVIEWED_BACKEND.items()), 'reviewed backend sources unchanged')
|
||||
# No web source is a compiler input or part of this common-contract proof.
|
||||
return result
|
||||
|
||||
|
||||
def names(raw):
|
||||
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
|
||||
|
||||
|
||||
def check_list(raw, expected):
|
||||
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
|
||||
'terse list contains only exact tests, no benchmarks or extra entries')
|
||||
|
||||
|
||||
def check_output(raw, count):
|
||||
require(re.search(rb'^test result: ok\. ' + str(count).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
|
||||
'all tests passed without skipped or filtered tests')
|
||||
|
||||
|
||||
def command(args, folder, timeout=300):
|
||||
index = len(list(folder.glob('command-*.json')))
|
||||
try:
|
||||
done = subprocess.run(args, capture_output=True, timeout=timeout)
|
||||
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
|
||||
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||
require(done.returncode == 0, 'local qualification command failed; private output retained')
|
||||
return done.stdout
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('local qualification timed out; no automatic retry') from None
|
||||
|
||||
|
||||
def scripts():
|
||||
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
||||
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
|
||||
|
||||
|
||||
def build():
|
||||
setup_state()
|
||||
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
|
||||
before = source_files(); save(folder / 'source-before.json', before)
|
||||
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable compiler image')
|
||||
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
|
||||
common = ['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m',
|
||||
'-v',str(ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','cargo',image]
|
||||
artifacts = {'linux': {}, 'windows': {}}
|
||||
for platform, triple in [('linux','x86_64-unknown-linux-gnu'),('windows','x86_64-pc-windows-gnu')]:
|
||||
options = ['--manifest-path','/src/Cargo.toml','--locked','--offline','--target',triple]
|
||||
packages = ['-p','rmm-domain','-p','rmm-agent-core'] + (['-p','rmm-privileged-helper'] if platform == 'linux' else [])
|
||||
command(common + ['clippy'] + options + packages + ['--all-targets','--','-D','warnings'], folder)
|
||||
selections = [(['-p','rmm-domain','--lib'], 'domain'),
|
||||
(['-p','rmm-agent-core'] + (['--features','openssl-verifier'] if platform == 'linux' else []) + ['--tests'], 'core')]
|
||||
if platform == 'linux': selections.append((['-p','rmm-privileged-helper','--test','reconcile'], 'linux-helper'))
|
||||
links = {}
|
||||
for selection, group in selections:
|
||||
raw = command(common + ['test'] + options + selection + ['--release','--no-run','--message-format=json'], folder)
|
||||
for line in raw.splitlines():
|
||||
try: item = json.loads(line)
|
||||
except ValueError: continue
|
||||
if item.get('reason') != 'compiler-artifact' or not item.get('executable') or not item.get('profile',{}).get('test'): continue
|
||||
name = item['target']['name']
|
||||
kind = 'domain' if group == 'domain' else 'linux-helper' if group == 'linux-helper' else {'contracts':'contracts','helper_reconcile':'helper-reconcile','reconcile':'reconcile'}.get(name)
|
||||
if kind is None: continue # empty Core lib harness is not this profile
|
||||
require(kind not in links and kind in KINDS[platform], 'exact distinct selected test link')
|
||||
links[kind] = target / Path(item['executable']).relative_to('/target')
|
||||
require(set(links) == set(KINDS[platform]), 'all selected native artifacts')
|
||||
destination = folder / platform; destination.mkdir(mode=0o700)
|
||||
for kind in KINDS[platform]:
|
||||
original = destination / (kind + '.linked'); delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
|
||||
for path in (original, delivery): shutil.copyfile(links[kind], path); path.chmod(0o600)
|
||||
linked_sha = sha(original)
|
||||
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
|
||||
command(['docker','run','--rm','--network','none','--read-only','-v',str(destination)+':/artifacts',
|
||||
'--entrypoint',tool,image,'--strip-debug','/artifacts/'+delivery.name], folder)
|
||||
require(sha(links[kind]) == sha(original) == linked_sha, 'original link preserved')
|
||||
data = delivery.read_bytes()
|
||||
if platform == 'linux': require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
|
||||
else:
|
||||
offset = int.from_bytes(data[60:64],'little'); require(data[:2] == b'MZ' and data[offset:offset+6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
|
||||
artifacts[platform][kind] = dict(path=str(delivery),sha256=sha(delivery),bytes=len(data),
|
||||
original_link_path=str(original),original_link_sha256=linked_sha,debug_stripped_delivery=True)
|
||||
# All local Linux lists precede any local tests, using exact delivery bytes.
|
||||
def invoke(item, args):
|
||||
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
|
||||
return command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,exec,size=128m',
|
||||
'-v',item['path']+':/unit:ro','--entrypoint','python3',image,'-c',script], folder)
|
||||
for kind, item in artifacts['linux'].items():
|
||||
raw = invoke(item, ['--list','--format','terse']); check_list(raw.decode(), EXPECTED['linux'][kind])
|
||||
save(folder / ('local-linux-'+kind+'-list.json'),dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
for kind, item in artifacts['linux'].items():
|
||||
raw = invoke(item, ['--test-threads=1']); check_output(raw, COUNTS['linux'][kind])
|
||||
save(folder / ('local-linux-'+kind+'-run.json'),dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
versions = command(['docker','run','--rm','--network','none','--read-only','-v',item['path']+':/unit:ro',
|
||||
'--entrypoint','readelf',image,'--version-info','/unit'],folder).decode()
|
||||
dynamic = command(['docker','run','--rm','--network','none','--read-only','-v',item['path']+':/unit:ro',
|
||||
'--entrypoint','readelf',image,'-d','/unit'],folder).decode()
|
||||
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)',versions)),key=lambda n:tuple(map(int,n.split('.'))))
|
||||
require(glibc and tuple(map(int,glibc[-1].split('.'))) <= (2,34), 'GLIBC at most 2.34 delivery requirement')
|
||||
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]',dynamic))
|
||||
require(source_files() == before, 'all sources and backend pins unchanged through build')
|
||||
manifest = dict(schema_version=1,profile=PROFILE,source_files=before,source_before_after_equal=True,
|
||||
reviewed_backend_source_pins=REVIEWED_BACKEND,backend_qualification_sha256=BACKEND_SHA,
|
||||
backend_sources_hash_bound_only=True,native_postgresql_executed=False,live_installer_executed=False,
|
||||
runner_sha256=sha(__file__),scripts=scripts(),test_names=EXPECTED,test_counts=COUNTS,artifacts=artifacts,
|
||||
build_image_id=image,both_targets_clippy_D_warnings=True,linux_lists_actual=True,
|
||||
windows_lists_expected_until_native=True,local_linux_tests_passed=sum(COUNTS['linux'].values()),
|
||||
native_linux_executed=False,native_windows_executed=False,product_state_writes=False,rmm_jobs=False)
|
||||
save(folder / 'manifest.json',manifest)
|
||||
print(json.dumps(dict(manifest=str(folder/'manifest.json'),manifest_sha256=sha(folder/'manifest.json'),
|
||||
linux_tests=sum(COUNTS['linux'].values()),windows_tests_expected=sum(COUNTS['windows'].values()),native_executed=False)))
|
||||
|
||||
|
||||
def verified(path, new_run):
|
||||
path = path.absolute(); private(path.parent, True)
|
||||
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
|
||||
value = load(path)
|
||||
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
|
||||
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
|
||||
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
|
||||
and value['reviewed_backend_source_pins'] == REVIEWED_BACKEND and value['backend_qualification_sha256'] == BACKEND_SHA
|
||||
and value['backend_sources_hash_bound_only'] is True and value['native_postgresql_executed'] is False
|
||||
and value['live_installer_executed'] is False,
|
||||
'original manifest/runner/remote scripts/profile binding')
|
||||
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
|
||||
for platform in COUNTS:
|
||||
require(set(value['artifacts'][platform]) == set(KINDS[platform]), 'all exact fixed artifacts')
|
||||
for kind, item in value['artifacts'][platform].items():
|
||||
suffix = '.exe' if platform == 'windows' else ''
|
||||
require(Path(item['path']) == path.parent / platform / (kind + suffix)
|
||||
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
|
||||
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
|
||||
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
|
||||
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def access_settings(root, platform):
|
||||
"""Read strictly parsed existing access only when the parent executes native."""
|
||||
require(root == ACCESS_ROOT and not root.is_symlink(), 'original Main access-root only; no copied credentials')
|
||||
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
||||
if platform == 'linux':
|
||||
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
||||
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
||||
else:
|
||||
cfg = access.load_config(root / 'credentials/server.conf')
|
||||
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
||||
credentials = root / 'credentials'; private(credentials, True)
|
||||
record = load(credentials / 'windows-dev-access.json')
|
||||
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
||||
expires = dt.datetime.fromisoformat(record['expires_at'])
|
||||
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
||||
key = str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
||||
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
||||
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
||||
private(credentials / 'windows-dev.known_hosts')
|
||||
return prefix
|
||||
|
||||
|
||||
def transport(prefix, command_text, data, folder, timeout=60):
|
||||
"""No stdout/stderr escapes the private case directory on transport failure."""
|
||||
try:
|
||||
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
||||
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
||||
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
||||
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
||||
return value
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('native reply lost; read original case only') from None
|
||||
|
||||
|
||||
def linux_rpc(prefix, payload, folder):
|
||||
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
||||
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return transport(prefix, 'python3 -', code.encode(), folder)
|
||||
|
||||
|
||||
def windows_rpc(prefix, payload, folder):
|
||||
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
||||
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
|
||||
|
||||
|
||||
def upload(prefix, item, destination, folder, kind):
|
||||
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
||||
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
||||
if '-p' in args: args[args.index('-p')] = '-P'
|
||||
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
||||
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
||||
try:
|
||||
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
||||
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
||||
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
||||
|
||||
|
||||
def linux_case(p):
|
||||
import resource
|
||||
import stat
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-msi-contracts-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain','contracts','helper-reconcile','reconcile','linux-helper'}, 'fixed Linux root qualification')
|
||||
root = Path('/var/lib/rmm-windows-msi-contracts')
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
|
||||
os.umask(0o077)
|
||||
case = root / ident
|
||||
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
|
||||
if p['action'] == 'prepare':
|
||||
if not root.exists(): root.mkdir(mode=0o700)
|
||||
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
|
||||
return dict(id=ident, prepared=True)
|
||||
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
|
||||
original = json.loads((case / 'intent.json').read_bytes())
|
||||
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists():
|
||||
partial = {}
|
||||
for kind in ('domain','contracts','helper-reconcile','reconcile','linux-helper'):
|
||||
for suffix in ('-list.json','-result.json'):
|
||||
path = case / (kind + suffix)
|
||||
if path.exists():
|
||||
safe(path, False); require(path.stat().st_size <= 2*1024*1024, 'bounded original partial receipt')
|
||||
partial[kind + suffix] = json.loads(path.read_bytes())
|
||||
return dict(id=ident,status='started_without_result' if (case/'started.json').exists() else 'prepared_without_start',
|
||||
both_lists_verified=(case/'all-lists-verified.json').exists(),tests_started=(case/'tests-started.json').exists(),partial=partial)
|
||||
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
|
||||
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
|
||||
temp = case / 'tmp'; temp.mkdir(mode=0o700)
|
||||
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
|
||||
listings = {}
|
||||
for kind in ('domain','contracts','helper-reconcile','reconcile','linux-helper'):
|
||||
binary = case / kind; safe(binary, False)
|
||||
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
|
||||
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
|
||||
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
|
||||
write(case / (kind+'-list.json'),dict(names=actual,exit_code=listed.returncode,sha256=p['artifacts'][kind]['sha256'],
|
||||
stdout_b64=base64.b64encode(listed.stdout).decode(),stderr_b64=base64.b64encode(listed.stderr).decode()))
|
||||
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == {'domain':20,'contracts':8,'helper-reconcile':26,'reconcile':26,'linux-helper':21}[kind], 'exact native test names before ANY test execution')
|
||||
listings[kind] = actual
|
||||
write(case/'all-lists-verified.json',dict(all_lists_before_any_tests=True,manifest_sha256=p['manifest_sha256']))
|
||||
write(case/'tests-started.json',dict(execute_tests_once=True))
|
||||
reports = {}
|
||||
for kind in ('domain','contracts','helper-reconcile','reconcile','linux-helper'):
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
timed = False
|
||||
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
|
||||
except subprocess.TimeoutExpired: timed = True; code = None
|
||||
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
|
||||
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
|
||||
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
|
||||
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
|
||||
write(case / (kind + '-result.json'), reports[kind])
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
|
||||
scripts=p['scripts'], reports=reports, all_lists_before_any_tests=True, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
|
||||
write(case / 'result.json', value); return value
|
||||
|
||||
|
||||
WINDOWS = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-msi-contracts-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-msi-contracts-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
|
||||
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts','helper-reconcile','reconcile')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
|
||||
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $root $true
|
||||
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
||||
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};$partial=@{};foreach($kind in @('domain','contracts','helper-reconcile','reconcile')){foreach($suffix in @('-list.json','-result.json')){$file=Join-Path $case ($kind+$suffix);if(Test-Path -LiteralPath $file){Safe $file $false;if((Get-Item -LiteralPath $file).Length-gt2097152){throw 'Partial report bound'};$partial[$kind+$suffix]=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json}}};@{id=$p.id;status=$status;all_lists_verified=(Test-Path -LiteralPath (Join-Path $case 'all-lists-verified.json'));tests_started=(Test-Path -LiteralPath (Join-Path $case 'tests-started.json'));partial=$partial}|ConvertTo-Json -Depth 16 -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
|
||||
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
|
||||
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
|
||||
$lists=@{};$executables=@{}
|
||||
foreach($kind in @('domain','contracts','helper-reconcile','reconcile')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};[string[]]$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($actual,[StringComparer]::Ordinal);$counts=@{domain=20;contracts=7;'helper-reconcile'=26;reconcile=26};$count=$counts[$kind];if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};WriteNew (Join-Path $case ($kind+'-list.json')) @{names=$actual;sha256=$item.sha256;listed=$list};$lists[$kind]=$actual;$executables[$kind]=$exe}
|
||||
WriteNew (Join-Path $case 'all-lists-verified.json') @{all_lists_before_any_tests=$true;manifest_sha256=$p.manifest_sha256};WriteNew (Join-Path $case 'tests-started.json') @{execute_tests_once=$true}
|
||||
$reports=@{};foreach($kind in @('domain','contracts','helper-reconcile','reconcile')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
|
||||
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;all_lists_before_any_tests=$true;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def check_result(manifest, platform, value, payload):
|
||||
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
||||
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
||||
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
|
||||
and value.get('environment_cleared') is True and value.get('all_lists_before_any_tests') is True and set(value['reports']) == set(KINDS[platform]), 'complete native original binding')
|
||||
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
|
||||
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
|
||||
for kind, item in value['reports'].items():
|
||||
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
|
||||
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
|
||||
check_output(raw, COUNTS[platform][kind])
|
||||
|
||||
|
||||
def execute(path, platform, access_root, case_id=None):
|
||||
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
|
||||
prefix = access_settings(access_root, platform)
|
||||
if case_id is None:
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
|
||||
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS[platform]}, names=EXPECTED[platform])
|
||||
if platform == 'windows':
|
||||
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
|
||||
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
|
||||
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS['linux']}, names=EXPECTED['linux'])
|
||||
check_result(manifest, 'linux', proof['native'], linux_payload)
|
||||
payload['linux_proof_sha256'] = sha(proof_path)
|
||||
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
|
||||
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
|
||||
save(folder / 'intent.json', intent)
|
||||
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
run_read = False
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
|
||||
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
|
||||
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
|
||||
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
|
||||
payload = intent['payload']; run_read = True
|
||||
rpc = linux_rpc if platform == 'linux' else windows_rpc
|
||||
if not run_read:
|
||||
result = rpc(prefix, dict(payload, action='prepare'), folder)
|
||||
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS[platform]:
|
||||
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-msi-contracts-' + case_id + '/' + kind + '.exe'
|
||||
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
|
||||
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('status'):
|
||||
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
|
||||
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
|
||||
check_result(manifest, platform, result, payload)
|
||||
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
|
||||
destination = path.parent / (platform + '-passed.json')
|
||||
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
|
||||
else: save(destination, proof)
|
||||
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
|
||||
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
|
||||
manifest_sha256=sha(path), proof_sha256=sha(destination))))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
|
||||
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
|
||||
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
|
||||
if args.action == 'build-local':
|
||||
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
|
||||
elif args.action.startswith('readback-'):
|
||||
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
|
||||
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
|
||||
else:
|
||||
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
|
||||
execute(args.manifest, args.action, args.access_root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print(json.dumps(dict(error='WINDOWS_MSI_CONTRACT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,559 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Windows MSI runtime Library/Binary units: Linux VM FIRST, then Windows VM.
|
||||
|
||||
Only fixed common test executables run in separate bootstrap scratch directories.
|
||||
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
|
||||
Native execution is explicit; any lost reply permits same-case readback only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import vm_access_check as access
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / 'devstate/windows-msi-runtime-units'
|
||||
IMAGE = 'rust-discovery-durable-final-build:local'
|
||||
PROFILE = 'windows-msi-runtime-units-v1'
|
||||
LINUX_REMOTE = '/var/lib/rmm-windows-msi-runtime-units'
|
||||
ACCESS_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery')
|
||||
QUALIFICATION = ROOT / 'devstate/windows-msi-runtime/qualified-ee6681c7-8d9d-4af9-8947-5325e1ea2e0f/qualification.json'
|
||||
QUALIFICATION_SHA = '17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816'
|
||||
COMMON_ROOT = Path('/home/kevin/Schreibtisch/Coding/rust-discovery-windows-msi-integration')
|
||||
COMMON = COMMON_ROOT / 'devstate/windows-msi-contracts/build-484a3761-6c84-426f-968d-25a638e9c6f7/manifest.json'
|
||||
COMMON_SHA = '2d96a07be72f3d71a8097510eb5f647ced6577086a45417c599b772018c29a53'
|
||||
COMMON_PROOFS = {'linux':'09fa24e32cd3f3563e80e91265c6cc7c612321b0fdd1febe7aef3ab6de53cf2a',
|
||||
'windows':'666ed196953abd0723de259a898b46c08ac84feee0140f1bb31d9db1fa1232c4'}
|
||||
# Linux ten names were actually executed in the frozen local qualification;
|
||||
# final Linux delivery --list/run is checked below. Windows is EXPECTED only.
|
||||
EXPECTED = {'linux': {'lib': ['event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits',
|
||||
'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable',
|
||||
'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata',
|
||||
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
|
||||
'journal::tests::durable_reopen_ack_identity_and_single_process',
|
||||
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
|
||||
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
|
||||
'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority',
|
||||
'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry',
|
||||
'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload']},
|
||||
'windows': {'lib': ['actions::tests::powershell_policy_is_an_exact_job_profile_before_file_not_a_mutable_default',
|
||||
'clock::tests::gate_requires_all_status_and_uncertainty_evidence',
|
||||
'clock::tests::production_clock_stays_closed_until_native_adapter_qualification',
|
||||
'clock::tests::suspend_closes_until_actual_post_resume_sync',
|
||||
'clock::tests::timeout_worker_stays_closed_without_a_second_call',
|
||||
'clock::tests::wall_step_and_overflow_fail_closed',
|
||||
'event_log::tests::job_mapping_is_only_fixed_unprivileged_live_logs_with_exact_limits',
|
||||
'event_log::tests::only_fixed_source_window_and_finite_limits_are_queryable',
|
||||
'event_log::tests::serialized_byte_budget_includes_xml_escaping_and_metadata',
|
||||
'event_log_job::tests::event_log_outcome_never_equates_valid_quality_with_complete_or_authorized_success',
|
||||
'event_log_job::tests::ticket_pre_read_boundary_excludes_keys_siblings_and_noncanonical_leaves',
|
||||
'helper_ipc::tests::pipe_client_rights_cannot_create_an_instance',
|
||||
'helper_ipc::tests::protocol_does_not_accept_a_shell_operation',
|
||||
'helper_ipc::tests::reconfigured_service_cannot_adopt_an_old_running_identity',
|
||||
'helper_ipc::tests::serialization_refuses_oversized_frame',
|
||||
'helper_ipc::tests::untrusted_lengths_are_rejected_before_body_allocation',
|
||||
'helper_runtime::intent::tests::additive_denial_column_preserves_original_legacy_intents_and_rejects_unknown_trigger',
|
||||
'helper_runtime::intent::tests::cancel_and_dispatch_cas_are_exclusive_and_history_cannot_be_rewritten',
|
||||
'helper_runtime::tests::msi_scope_requires_bound_independent_postconditions_and_exact_noop_or_installer_exit',
|
||||
'helper_runtime::tests::system_route_binds_original_request_shape_budget_and_reply_scope',
|
||||
'helper_system::tests::completed_scm_state_cannot_override_elapsed_runtime',
|
||||
'helper_system::tests::fixture_recovery_cannot_add_commands_reboots_or_restart_attempts',
|
||||
'helper_system::tests::old_settings_omit_new_scope_and_only_v2_exact_recipe_hash_and_budget_allow_msi',
|
||||
'helper_system::tests::service_adapter_exposes_only_implemented_states',
|
||||
'helper_system::tests::single_fixture_cannot_start_services_or_groups_as_dependencies',
|
||||
'journal::tests::bounded_existing_journal_preserves_identity_sequence_and_unacked_bytes',
|
||||
'journal::tests::durable_reopen_ack_identity_and_single_process',
|
||||
'journal::tests::migrates_original_passive_schema_without_rewriting_pending_envelopes',
|
||||
'journal::tests::unsupported_page_size_is_refused_without_mutating_existing_data',
|
||||
'native::tests::boot_identity_survives_independent_native_queries',
|
||||
'native::tests::native_inventory_has_real_windows_sources_and_no_fake_inodes',
|
||||
'package::tests::exit_code_never_substitutes_for_independent_postconditions_or_reboot_authority',
|
||||
'package::tests::late_exit_or_postcondition_cannot_retroactively_succeed_or_retry',
|
||||
'package::tests::upgrade_and_noop_need_independent_exact_products_family_and_payload',
|
||||
'process::tests::arguments_never_become_shell_code_and_trailing_slashes_are_quoted'],
|
||||
'bin': ['https_channel::endpoint_tests::configured_dns_identity_cannot_inject_a_url_or_disable_name_checks',
|
||||
'runtime::tests::bound_helper_unknown_repairs_generic_crash_gap_without_ack_or_duplicate_result',
|
||||
'runtime::tests::legacy_inventory_keeps_original_bytes_until_concrete_core_ack',
|
||||
'runtime::tests::old_passive_configuration_cannot_enable_jobs_or_read_the_clock',
|
||||
'runtime::tests::worker_fence_requires_same_generation_and_entire_clock_interval',
|
||||
'wire_channel::tests::auto_fallback_classifies_upgrade_refusal_but_never_authentication',
|
||||
'wire_channel::tests::explicit_transport_names_cannot_enable_verification_bypasses']}}
|
||||
COUNTS = {platform:{kind:len(names) for kind,names in values.items()} for platform,values in EXPECTED.items()}
|
||||
KINDS = {'linux':('lib',),'windows':('lib','bin')}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def object_pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
item = Path(path).lstat()
|
||||
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
||||
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
||||
'private owned regular path')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
private(Path(path).parent, True)
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def setup_state():
|
||||
os.umask(0o077)
|
||||
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = STATE.parent.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
||||
'owned non-world-writable devstate parent')
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
private(STATE, True)
|
||||
|
||||
|
||||
def source_qualification():
|
||||
require(sha(QUALIFICATION)==QUALIFICATION_SHA,'exact independently reviewed Runtime qualification')
|
||||
value=load(QUALIFICATION)
|
||||
require(value['type']=='rmm.windows.msi-runtime.local-source-qualification'
|
||||
and value['source_before_after_equal'] is True and value['native_execution'] is False
|
||||
and value['checks']['windows_default_alltargets_clippy']=='passed'
|
||||
and value['checks']['windows_system_helper_alltargets_clippy']=='passed'
|
||||
and value['checks']['windows_lib_bin_unit_link']=='passed_not_executed','real frozen source/Clippy/link qualification')
|
||||
require(all(sha(ROOT/name)==digest for name,digest in value['source_files'].items()),'all 82 qualified compiler inputs unchanged')
|
||||
for name,item in value['artifacts'].items():
|
||||
file=QUALIFICATION.parent/name;private(file)
|
||||
require(sha(file)==item['sha256'] and file.stat().st_size==item['bytes'],'unchanged qualified original/delivery artifact')
|
||||
return value
|
||||
|
||||
|
||||
def common_proof():
|
||||
require(sha(COMMON)==COMMON_SHA,'exact existing common build, never relabelled')
|
||||
manifest=load(COMMON)
|
||||
require(manifest['profile']=='windows-msi-contracts-v1' and manifest['source_before_after_equal'] is True,
|
||||
'original common contract profile')
|
||||
for name,digest in manifest['source_files'].items():
|
||||
require(sha(COMMON_ROOT/name)==digest,'preserved complete common source archive')
|
||||
if name.startswith(('crates/agent-core/','crates/domain/','crates/protocol/','proto/')) or name in ('Cargo.toml','Cargo.lock'):
|
||||
require(sha(ROOT/name)==digest,'Runtime uses the same actual native-qualified common source')
|
||||
result={'manifest_sha256':COMMON_SHA}
|
||||
for platform,total in (('linux',101),('windows',79)):
|
||||
path=COMMON.parent/(platform+'-passed.json');require(sha(path)==COMMON_PROOFS[platform],'exact actual original common native proof')
|
||||
proof=load(path);actual=proof['native']
|
||||
require(proof['verified'] is True and proof['platform']==platform and proof['manifest_sha256']==COMMON_SHA
|
||||
and actual['manifest_sha256']==COMMON_SHA and actual['runner_sha256']==manifest['runner_sha256']
|
||||
and actual['scripts']==manifest['scripts'] and actual['product_state_writes'] is False and actual['rmm_jobs'] is False
|
||||
and actual['all_lists_before_any_tests'] is True and set(actual['reports'])==set(manifest['test_counts'][platform]),'actual complete common profile proof')
|
||||
for kind,item in actual['reports'].items():
|
||||
require(item['names']==manifest['test_names'][platform][kind]
|
||||
and item['sha256']==manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code']==0 and item['timed_out'] is False,'every original common native artifact/list/exit')
|
||||
check_output(base64.b64decode(item['stdout_b64'],validate=True),manifest['test_counts'][platform][kind])
|
||||
require(sum(len(item['names']) for item in actual['reports'].values())==total,'exact original native count')
|
||||
result[platform]={'proof_sha256':sha(path),'case_id':proof['case_id'],'tests':total}
|
||||
return result
|
||||
|
||||
|
||||
def source_files():
|
||||
value=source_qualification()
|
||||
result=dict(value['source_files'])
|
||||
for name in ('deploy/windows_msi_runtime_acceptance.py','deploy/vm_access_check.py','deploy/vm_mvp_acceptance.py'):
|
||||
require(not (ROOT/name).is_symlink(),'regular local driver/transport input');result[name]=sha(ROOT/name)
|
||||
return dict(sorted(result.items()))
|
||||
|
||||
|
||||
def names(raw):
|
||||
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
|
||||
|
||||
|
||||
def check_list(raw, expected):
|
||||
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
|
||||
'terse list contains only exact tests, no benchmarks or extra entries')
|
||||
|
||||
|
||||
def check_output(raw, count):
|
||||
require(re.search(rb'^test result: ok\. ' + str(count).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
|
||||
'all tests passed without skipped or filtered tests')
|
||||
|
||||
|
||||
def command(args, folder, timeout=300):
|
||||
index = len(list(folder.glob('command-*.json')))
|
||||
try:
|
||||
done = subprocess.run(args, capture_output=True, timeout=timeout)
|
||||
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
|
||||
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||
require(done.returncode == 0, 'local qualification command failed; private output retained')
|
||||
return done.stdout
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('local qualification timed out; no automatic retry') from None
|
||||
|
||||
|
||||
def scripts():
|
||||
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
||||
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
|
||||
|
||||
|
||||
def build():
|
||||
setup_state();folder=STATE/('build-'+str(uuid.uuid4()));folder.mkdir(mode=0o700)
|
||||
before=source_files();qualified=source_qualification();common=common_proof();save(folder/'source-before.json',before)
|
||||
image=qualified['image_id'];require(re.fullmatch(r'sha256:[a-f0-9]{64}',image),'immutable source-qualified compiler image')
|
||||
target=STATE/'target';target.mkdir(mode=0o700,exist_ok=True);private(target,True)
|
||||
docker=['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,size=512m',
|
||||
'-v',str(ROOT)+':/src:ro','-v',str(target)+':/target','-e','CARGO_TARGET_DIR=/target','--entrypoint','cargo',image]
|
||||
options=['--manifest-path','/src/Cargo.toml','--locked','--offline','--target','x86_64-unknown-linux-gnu','-p','rmm-agent-windows','--lib']
|
||||
command(docker+['clippy']+options+['--','-D','warnings'],folder)
|
||||
raw=command(docker+['test']+options+['--release','--no-run','--message-format=json'],folder)
|
||||
links=[]
|
||||
for line in raw.splitlines():
|
||||
try:item=json.loads(line)
|
||||
except ValueError:continue
|
||||
if item.get('reason')=='compiler-artifact' and item.get('executable') and item.get('profile',{}).get('test') and item['target']['name']=='rmm_agent_windows':links.append(target/Path(item['executable']).relative_to('/target'))
|
||||
require(len(links)==1,'exact Linux library test link')
|
||||
artifacts={'linux':{},'windows':{}}
|
||||
for platform in KINDS:
|
||||
destination=folder/platform;destination.mkdir(mode=0o700)
|
||||
for kind in KINDS[platform]:
|
||||
linked=links[0] if platform=='linux' else QUALIFICATION.parent/('windows-'+kind+'-tests.original.exe')
|
||||
delivery_source=linked if platform=='linux' else QUALIFICATION.parent/('windows-'+kind+'-tests.exe')
|
||||
original=destination/(kind+'.linked');output=destination/(kind+('.exe' if platform=='windows' else ''))
|
||||
for source,dest in ((linked,original),(delivery_source,output)):shutil.copyfile(source,dest);dest.chmod(0o600)
|
||||
original_sha=sha(linked)
|
||||
if platform=='linux':command(['docker','run','--rm','--network','none','--read-only','-v',str(destination)+':/artifacts','--entrypoint','strip',image,'--strip-debug','/artifacts/lib'],folder)
|
||||
require(sha(linked)==sha(original)==original_sha,'unchanged original linked bytes')
|
||||
data=output.read_bytes()
|
||||
if platform=='linux':require(data[:6]==b'\x7fELF\x02\x01' and data[18:20]==b'\x3e\0','Linux x64 ELF')
|
||||
else:
|
||||
offset=int.from_bytes(data[60:64],'little');require(data[:2]==b'MZ' and data[offset:offset+6]==b'PE\0\0\x64\x86','Windows x64 PE')
|
||||
require(all(name.encode() in data for name in EXPECTED['windows'][kind]),'expected native names present in linked Windows bytes, not an executed list')
|
||||
artifacts[platform][kind]=dict(path=str(output),sha256=sha(output),bytes=len(data),original_link_path=str(original),original_link_sha256=original_sha,debug_stripped_delivery=True)
|
||||
item=artifacts['linux']['lib']
|
||||
for mode,args in (('list',['--list','--format','terse']),('run',['--test-threads=1'])):
|
||||
code='import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+'+repr(args)+',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
|
||||
raw=command(['docker','run','--rm','--network','none','--read-only','--tmpfs','/tmp:rw,exec,size=128m','-v',item['path']+':/unit:ro','--entrypoint','python3',image,'-c',code],folder)
|
||||
save(folder/('local-linux-lib-'+mode+'.json'),dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
if mode=='list':check_list(raw.decode(),EXPECTED['linux']['lib'])
|
||||
else:check_output(raw,10)
|
||||
versions=command(['docker','run','--rm','--network','none','--read-only','-v',item['path']+':/unit:ro','--entrypoint','readelf',image,'--version-info','/unit'],folder).decode()
|
||||
glibc=sorted(set(re.findall(r'GLIBC_(\d+\.\d+)',versions)),key=lambda x:tuple(map(int,x.split('.'))));require(glibc and tuple(map(int,glibc[-1].split('.'))) <= (2,34),'GLIBC at most 2.34')
|
||||
item['glibc_max']=glibc[-1]
|
||||
require(source_files()==before and common_proof()==common,'all sources, original qualification and common proofs unchanged')
|
||||
manifest=dict(schema_version=1,profile=PROFILE,source_files=before,source_before_after_equal=True,
|
||||
source_qualification=dict(path=str(QUALIFICATION),sha256=QUALIFICATION_SHA),common_native_proofs=common,
|
||||
original_windows_clippy_and_units_reused=True,backend_and_installer_native_claim=False,
|
||||
runner_sha256=sha(__file__),scripts=scripts(),test_names=EXPECTED,test_counts=COUNTS,artifacts=artifacts,
|
||||
build_image_id=image,both_targets_clippy_D_warnings=True,linux_lists_actual=True,windows_lists_expected_until_native=True,
|
||||
local_linux_tests_passed=10,native_linux_executed=False,native_windows_executed=False,product_state_writes=False,rmm_jobs=False)
|
||||
save(folder/'manifest.json',manifest);print(json.dumps(dict(manifest=str(folder/'manifest.json'),manifest_sha256=sha(folder/'manifest.json'),linux_tests=10,windows_tests_expected=42,native_executed=False)))
|
||||
|
||||
|
||||
def verified(path, new_run):
|
||||
path = path.absolute(); private(path.parent, True)
|
||||
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
|
||||
value = load(path)
|
||||
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
|
||||
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
|
||||
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True
|
||||
and value['source_qualification'] == dict(path=str(QUALIFICATION),sha256=QUALIFICATION_SHA)
|
||||
and value['original_windows_clippy_and_units_reused'] is True and value['backend_and_installer_native_claim'] is False,
|
||||
'original manifest/runner/remote scripts/profile binding')
|
||||
if new_run: require(value['source_files'] == source_files() and value['common_native_proofs'] == common_proof(), 'new execution requires exact runtime/common source proofs')
|
||||
for platform in COUNTS:
|
||||
require(set(value['artifacts'][platform]) == set(KINDS[platform]), 'all exact fixed artifacts')
|
||||
for kind, item in value['artifacts'][platform].items():
|
||||
suffix = '.exe' if platform == 'windows' else ''
|
||||
require(Path(item['path']) == path.parent / platform / (kind + suffix)
|
||||
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
|
||||
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
|
||||
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
|
||||
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def access_settings(root, platform):
|
||||
"""Read strictly parsed existing access only when the parent executes native."""
|
||||
require(root == ACCESS_ROOT and not root.is_symlink(), 'original Main access-root only; no copied credentials')
|
||||
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
||||
if platform == 'linux':
|
||||
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
||||
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
||||
else:
|
||||
cfg = access.load_config(root / 'credentials/server.conf')
|
||||
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
||||
credentials = root / 'credentials'; private(credentials, True)
|
||||
record = load(credentials / 'windows-dev-access.json')
|
||||
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
||||
expires = dt.datetime.fromisoformat(record['expires_at'])
|
||||
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
||||
key = str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
||||
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
||||
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
||||
private(credentials / 'windows-dev.known_hosts')
|
||||
return prefix
|
||||
|
||||
|
||||
def transport(prefix, command_text, data, folder, timeout=60):
|
||||
"""No stdout/stderr escapes the private case directory on transport failure."""
|
||||
try:
|
||||
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
||||
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
||||
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
||||
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
||||
return value
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('native reply lost; read original case only') from None
|
||||
|
||||
|
||||
def linux_rpc(prefix, payload, folder):
|
||||
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
||||
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return transport(prefix, 'python3 -', code.encode(), folder)
|
||||
|
||||
|
||||
def windows_rpc(prefix, payload, folder):
|
||||
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
||||
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
|
||||
|
||||
|
||||
def upload(prefix, item, destination, folder, kind):
|
||||
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
||||
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
||||
if '-p' in args: args[args.index('-p')] = '-P'
|
||||
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
||||
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
||||
try:
|
||||
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
||||
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
||||
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
||||
|
||||
|
||||
def linux_case(p):
|
||||
import resource
|
||||
import stat
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-msi-runtime-units-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'lib'}, 'fixed Linux root qualification')
|
||||
root = Path('/var/lib/rmm-windows-msi-runtime-units')
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
|
||||
os.umask(0o077)
|
||||
case = root / ident
|
||||
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
|
||||
if p['action'] == 'prepare':
|
||||
if not root.exists(): root.mkdir(mode=0o700)
|
||||
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
|
||||
return dict(id=ident, prepared=True)
|
||||
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
|
||||
original = json.loads((case / 'intent.json').read_bytes())
|
||||
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists():
|
||||
partial = {}
|
||||
for kind in ('lib',):
|
||||
for suffix in ('-list.json','-result.json'):
|
||||
path = case / (kind + suffix)
|
||||
if path.exists():
|
||||
safe(path, False); require(path.stat().st_size <= 2*1024*1024, 'bounded original partial receipt')
|
||||
partial[kind + suffix] = json.loads(path.read_bytes())
|
||||
return dict(id=ident,status='started_without_result' if (case/'started.json').exists() else 'prepared_without_start',
|
||||
both_lists_verified=(case/'all-lists-verified.json').exists(),tests_started=(case/'tests-started.json').exists(),partial=partial)
|
||||
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
|
||||
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
|
||||
temp = case / 'tmp'; temp.mkdir(mode=0o700)
|
||||
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
|
||||
listings = {}
|
||||
for kind in ('lib',):
|
||||
binary = case / kind; safe(binary, False)
|
||||
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
|
||||
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
|
||||
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
|
||||
write(case / (kind+'-list.json'),dict(names=actual,exit_code=listed.returncode,sha256=p['artifacts'][kind]['sha256'],
|
||||
stdout_b64=base64.b64encode(listed.stdout).decode(),stderr_b64=base64.b64encode(listed.stderr).decode()))
|
||||
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == {'lib':10}[kind], 'exact native test names before ANY test execution')
|
||||
listings[kind] = actual
|
||||
write(case/'all-lists-verified.json',dict(all_lists_before_any_tests=True,manifest_sha256=p['manifest_sha256']))
|
||||
write(case/'tests-started.json',dict(execute_tests_once=True))
|
||||
reports = {}
|
||||
for kind in ('lib',):
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
timed = False
|
||||
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
|
||||
except subprocess.TimeoutExpired: timed = True; code = None
|
||||
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
|
||||
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
|
||||
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
|
||||
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
|
||||
write(case / (kind + '-result.json'), reports[kind])
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
|
||||
scripts=p['scripts'], reports=reports, all_lists_before_any_tests=True, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
|
||||
write(case / 'result.json', value); return value
|
||||
|
||||
|
||||
WINDOWS = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-msi-runtime-units-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-msi-runtime-units-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
|
||||
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('lib','bin')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
|
||||
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $root $true
|
||||
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
||||
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};$partial=@{};foreach($kind in @('lib','bin')){foreach($suffix in @('-list.json','-result.json')){$file=Join-Path $case ($kind+$suffix);if(Test-Path -LiteralPath $file){Safe $file $false;if((Get-Item -LiteralPath $file).Length-gt2097152){throw 'Partial report bound'};$partial[$kind+$suffix]=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json}}};@{id=$p.id;status=$status;all_lists_verified=(Test-Path -LiteralPath (Join-Path $case 'all-lists-verified.json'));tests_started=(Test-Path -LiteralPath (Join-Path $case 'tests-started.json'));partial=$partial}|ConvertTo-Json -Depth 16 -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
|
||||
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$rmmGuardSystemDrive=$env:SystemDrive;if($rmmGuardSystemDrive-notmatch'^[A-Za-z]:$'-or!$systemRoot.StartsWith(($rmmGuardSystemDrive+'\'),[StringComparison]::OrdinalIgnoreCase)){throw 'Original Windows system drive required'};$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['SystemDrive']=$rmmGuardSystemDrive;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
|
||||
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
|
||||
$lists=@{};$executables=@{}
|
||||
foreach($kind in @('lib','bin')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};[string[]]$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''});[Array]::Sort($actual,[StringComparer]::Ordinal);$counts=@{lib=35;bin=7};$count=$counts[$kind];if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};WriteNew (Join-Path $case ($kind+'-list.json')) @{names=$actual;sha256=$item.sha256;listed=$list};$lists[$kind]=$actual;$executables[$kind]=$exe}
|
||||
WriteNew (Join-Path $case 'all-lists-verified.json') @{all_lists_before_any_tests=$true;manifest_sha256=$p.manifest_sha256};WriteNew (Join-Path $case 'tests-started.json') @{execute_tests_once=$true}
|
||||
$reports=@{};foreach($kind in @('lib','bin')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
|
||||
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;all_lists_before_any_tests=$true;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def check_result(manifest, platform, value, payload):
|
||||
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
||||
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
||||
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
|
||||
and value.get('environment_cleared') is True and value.get('all_lists_before_any_tests') is True and set(value['reports']) == set(KINDS[platform]), 'complete native original binding')
|
||||
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
|
||||
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
|
||||
for kind, item in value['reports'].items():
|
||||
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
|
||||
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
|
||||
check_output(raw, COUNTS[platform][kind])
|
||||
|
||||
|
||||
def execute(path, platform, access_root, case_id=None):
|
||||
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
|
||||
prefix = access_settings(access_root, platform)
|
||||
if case_id is None:
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
|
||||
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS[platform]}, names=EXPECTED[platform])
|
||||
if platform == 'windows':
|
||||
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
|
||||
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
|
||||
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS['linux']}, names=EXPECTED['linux'])
|
||||
check_result(manifest, 'linux', proof['native'], linux_payload)
|
||||
payload['linux_proof_sha256'] = sha(proof_path)
|
||||
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
|
||||
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
|
||||
save(folder / 'intent.json', intent)
|
||||
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
run_read = False
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
|
||||
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
|
||||
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
|
||||
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
|
||||
payload = intent['payload']; run_read = True
|
||||
rpc = linux_rpc if platform == 'linux' else windows_rpc
|
||||
if not run_read:
|
||||
result = rpc(prefix, dict(payload, action='prepare'), folder)
|
||||
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS[platform]:
|
||||
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-msi-runtime-units-' + case_id + '/' + kind + '.exe'
|
||||
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
|
||||
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('status'):
|
||||
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
|
||||
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
|
||||
check_result(manifest, platform, result, payload)
|
||||
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
|
||||
destination = path.parent / (platform + '-passed.json')
|
||||
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
|
||||
else: save(destination, proof)
|
||||
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
|
||||
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
|
||||
manifest_sha256=sha(path), proof_sha256=sha(destination))))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
|
||||
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
|
||||
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
|
||||
if args.action == 'build-local':
|
||||
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
|
||||
elif args.action.startswith('readback-'):
|
||||
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
|
||||
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
|
||||
else:
|
||||
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
|
||||
execute(args.manifest, args.action, args.access_root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print(json.dumps(dict(error='WINDOWS_MSI_RUNTIME_UNIT_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
|
||||
raise SystemExit(2) from None
|
||||
@@ -0,0 +1,485 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Package24 pure profile contracts: Linux VM FIRST, then Windows VM.
|
||||
|
||||
Only two fixed test executables run in separate bootstrap scratch directories.
|
||||
No RMM job, daemon, live database, PKI, policy, enrollment or capability change.
|
||||
Native execution is explicit; any lost reply permits same-case readback only.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import inspect
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
import vm_access_check as access
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / 'devstate/windows-profile'
|
||||
IMAGE = 'rust-discovery-durable-final-build:local'
|
||||
PROFILE = 'windows-process-profile-v1'
|
||||
LINUX_REMOTE = '/var/lib/rmm-windows-profile-units'
|
||||
KINDS = ('domain', 'contracts')
|
||||
COUNTS = {'linux': {'domain': 16, 'contracts': 7}, 'windows': {'domain': 16, 'contracts': 6}}
|
||||
DOMAIN_NAMES = sorted(('apt_transaction::tests::closure_bytes_archives_and_code_are_bound',
|
||||
'apt_transaction::tests::helper_schema_two_roundtrip_and_strict_action_binding',
|
||||
'inventory_document::tests::additive_metadata_and_bounds',
|
||||
'inventory_document::tests::exact_linux_recovery_scope_does_not_admit_other_hyphens_or_windows',
|
||||
'inventory_document::tests::windows_scope_does_not_weaken_linux_or_accept_platform_spoofing',
|
||||
'jobs::tests::additive_recipe_refs_preserve_legacy_plan_bytes', 'jobs::tests::codec_golden_and_exact_script_bytes',
|
||||
'jobs::tests::no_terminal_replay_or_unknown_restart', 'jobs::tests::permit_codec_golden_all_bindings',
|
||||
'jobs::tests::updates_require_exact_versions_and_never_implicit_reboot',
|
||||
'jobs::tests::windows_interpreter_and_capability_contract',
|
||||
'jobs::tests::windows_remote_signed_profile_is_optional_exact_and_capability_bound',
|
||||
'jobs::tests::windows_system_scm_is_explicit_and_preserves_linux_service_bytes',
|
||||
'reconciliation::tests::outcome_codec_keeps_raw_output_and_sorts_evidence',
|
||||
'reconciliation::tests::reconciliation_cannot_be_a_permit_or_unbounded_ticket',
|
||||
'tests::production_never_accepts_development_auth'))
|
||||
CONTRACT_NAMES = sorted(('atomic_begin_execution_rolls_back_both_rows_on_missing_witness_or_start_insert_failure',
|
||||
'completion_cas_preserves_original_bytes_and_recovers_only_verified_bound_evidence',
|
||||
'consumed_attempt_and_unknown_lock_survive_reopen_without_reexecution',
|
||||
'exact_permit_bytes_time_and_all_identity_hash_bindings_are_required',
|
||||
'historical_request_and_binding_codecs_keep_field_order_arrays_and_strictness',
|
||||
'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering',
|
||||
'portable_acceptance_requires_platform_capability_and_exact_redelivery'))
|
||||
UNIX_ONLY = 'openssl_and_portable_ed25519_agree_on_current_keys_bytes_and_tampering'
|
||||
EXPECTED = {'linux': {'domain': DOMAIN_NAMES, 'contracts': CONTRACT_NAMES},
|
||||
'windows': {'domain': DOMAIN_NAMES, 'contracts': [x for x in CONTRACT_NAMES if x != UNIX_ONLY]}}
|
||||
|
||||
|
||||
def require(value, code):
|
||||
if not value:
|
||||
raise RuntimeError(code)
|
||||
|
||||
|
||||
def sha(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def object_pairs(items):
|
||||
value = {}
|
||||
for key, item in items:
|
||||
require(key not in value, 'duplicate JSON field')
|
||||
value[key] = item
|
||||
return value
|
||||
|
||||
|
||||
def private(path, directory=False):
|
||||
item = Path(path).lstat()
|
||||
require(not stat.S_ISLNK(item.st_mode) and item.st_uid == os.getuid()
|
||||
and stat.S_IMODE(item.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(item.st_mode) if directory else stat.S_ISREG(item.st_mode) and item.st_nlink == 1),
|
||||
'private owned regular path')
|
||||
|
||||
|
||||
def load(path):
|
||||
private(path)
|
||||
require(Path(path).stat().st_size <= 2 * 1024 * 1024, 'bounded private JSON')
|
||||
return json.loads(Path(path).read_bytes(), object_pairs_hook=object_pairs)
|
||||
|
||||
|
||||
def save(path, value):
|
||||
private(Path(path).parent, True)
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
json.dump(value, stream, indent=2); stream.write('\n'); stream.flush(); os.fsync(stream.fileno())
|
||||
|
||||
|
||||
def setup_state():
|
||||
os.umask(0o077)
|
||||
STATE.parent.mkdir(mode=0o700, exist_ok=True)
|
||||
metadata = STATE.parent.lstat()
|
||||
require(stat.S_ISDIR(metadata.st_mode) and metadata.st_uid == os.getuid() and not metadata.st_mode & 0o002,
|
||||
'owned non-world-writable devstate parent')
|
||||
STATE.mkdir(mode=0o700, exist_ok=True)
|
||||
private(STATE, True)
|
||||
|
||||
|
||||
def source_files():
|
||||
paths = [ROOT / p for p in ('Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml',
|
||||
'deploy/windows_profile_acceptance.py', 'deploy/remote_client_bootstrap.py',
|
||||
'deploy/vm_access_check.py', 'deploy/vm_mvp_acceptance.py', 'deploy/windows/client_bootstrap.py')]
|
||||
paths += list((ROOT / 'crates').rglob('Cargo.toml'))
|
||||
for name in ('domain', 'agent-core', 'protocol'):
|
||||
paths += [p for p in (ROOT / 'crates' / name).rglob('*') if p.is_file()]
|
||||
paths += [p for p in (ROOT / 'proto').rglob('*') if p.is_file()]
|
||||
for path in paths:
|
||||
require(not path.is_symlink() and path.is_file(), 'regular source inputs only')
|
||||
return {str(p.relative_to(ROOT)): sha(p) for p in sorted(set(paths))}
|
||||
|
||||
|
||||
def names(raw):
|
||||
return sorted(re.findall(r'^([A-Za-z0-9_:]+): test\r?$', raw, re.M))
|
||||
|
||||
|
||||
def check_list(raw, expected):
|
||||
require(names(raw) == expected and len(set(expected)) == len(expected), 'all exact test names before execution')
|
||||
require(all(not line.strip() or re.fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in raw.splitlines()),
|
||||
'terse list contains only exact tests, no benchmarks or extra entries')
|
||||
|
||||
|
||||
def check_output(raw, count):
|
||||
require(re.search(rb'^test result: ok\. ' + str(count).encode()
|
||||
+ rb' passed; 0 failed; 0 ignored; 0 measured; 0 filtered out;[^\r\n]*\r?$', raw, re.M),
|
||||
'all tests passed without skipped or filtered tests')
|
||||
|
||||
|
||||
def command(args, folder, timeout=300):
|
||||
index = len(list(folder.glob('command-*.json')))
|
||||
try:
|
||||
done = subprocess.run(args, capture_output=True, timeout=timeout)
|
||||
save(folder / ('command-%03d.json' % index), dict(returncode=done.returncode,
|
||||
stdout_b64=base64.b64encode(done.stdout).decode(), stderr_b64=base64.b64encode(done.stderr).decode()))
|
||||
require(done.returncode == 0, 'local qualification command failed; private output retained')
|
||||
return done.stdout
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('command-%03d.json' % index), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('local qualification timed out; no automatic retry') from None
|
||||
|
||||
|
||||
def scripts():
|
||||
return {'linux_case_sha256': hashlib.sha256(inspect.getsource(linux_case).encode()).hexdigest(),
|
||||
'windows_script_sha256': hashlib.sha256(WINDOWS.encode()).hexdigest()}
|
||||
|
||||
|
||||
def build():
|
||||
setup_state()
|
||||
folder = STATE / ('build-' + str(uuid.uuid4())); folder.mkdir(mode=0o700)
|
||||
before = source_files(); save(folder / 'source-before.json', before)
|
||||
image = command(['docker', 'image', 'inspect', '--format', '{{.Id}}', IMAGE], folder).decode().strip()
|
||||
require(re.fullmatch(r'sha256:[a-f0-9]{64}', image), 'immutable local build image')
|
||||
target = STATE / 'target'; target.mkdir(mode=0o700, exist_ok=True); private(target, True)
|
||||
common = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,size=512m',
|
||||
'-v', str(ROOT) + ':/src:ro', '-v', str(target) + ':/target', '-e', 'CARGO_TARGET_DIR=/target', '--entrypoint', 'cargo', image]
|
||||
artifacts = {'linux': {}, 'windows': {}}
|
||||
for platform, triple in [('linux', 'x86_64-unknown-linux-gnu'), ('windows', 'x86_64-pc-windows-gnu')]:
|
||||
for kind in KINDS:
|
||||
package, selection = ('rmm-domain', ['--lib']) if kind == 'domain' else ('rmm-agent-core', ['--test', 'contracts'])
|
||||
options = ['--manifest-path', '/src/Cargo.toml', '--locked', '--offline', '--target', triple, '-p', package]
|
||||
command(common + ['clippy'] + options + selection + ['--', '-D', 'warnings'], folder)
|
||||
raw = command(common + ['test'] + options + selection + ['--release', '--no-run', '--message-format=json'], folder)
|
||||
linked = []
|
||||
for line in raw.splitlines():
|
||||
try: item = json.loads(line)
|
||||
except ValueError: continue
|
||||
expected_name = 'rmm_domain' if kind == 'domain' else 'contracts'
|
||||
if item.get('reason') == 'compiler-artifact' and item.get('executable') and item.get('profile', {}).get('test') and item['target']['name'] == expected_name:
|
||||
linked.append(target / Path(item['executable']).relative_to('/target'))
|
||||
require(len(linked) == 1, 'exact selected unit executable')
|
||||
destination = folder / platform; destination.mkdir(mode=0o700, exist_ok=True)
|
||||
original = destination / (kind + '.linked')
|
||||
delivery = destination / (kind + ('.exe' if platform == 'windows' else ''))
|
||||
for path in (original, delivery): shutil.copyfile(linked[0], path); path.chmod(0o600)
|
||||
linked_sha = sha(original)
|
||||
tool = 'x86_64-w64-mingw32-strip' if platform == 'windows' else 'strip'
|
||||
command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', str(destination) + ':/artifacts',
|
||||
'--entrypoint', tool, image, '--strip-debug', '/artifacts/' + delivery.name], folder)
|
||||
require(sha(linked[0]) == sha(original) == linked_sha, 'unstripped original link preserved')
|
||||
data = delivery.read_bytes()
|
||||
if platform == 'linux':
|
||||
require(data[:6] == b'\x7fELF\x02\x01' and data[18:20] == b'\x3e\0', 'Linux x64 ELF')
|
||||
else:
|
||||
offset = int.from_bytes(data[60:64], 'little')
|
||||
require(data[:2] == b'MZ' and data[offset:offset + 6] == b'PE\0\0\x64\x86', 'Windows x64 PE')
|
||||
artifacts[platform][kind] = dict(path=str(delivery.resolve()), sha256=sha(delivery), bytes=len(data),
|
||||
original_link_path=str(original.resolve()), original_link_sha256=linked_sha, debug_stripped_delivery=True)
|
||||
# Run exactly the deliverable Linux bytes in an offline disposable container.
|
||||
for kind, item in artifacts['linux'].items():
|
||||
invoke = ['docker', 'run', '--rm', '--network', 'none', '--read-only', '--tmpfs', '/tmp:rw,exec,size=128m',
|
||||
'-v', item['path'] + ':/unit:ro', '--entrypoint', 'python3', image, '-c']
|
||||
for mode in ('list', 'run'):
|
||||
args = ['--list', '--format', 'terse'] if mode == 'list' else ['--test-threads=1']
|
||||
script = 'import shutil,os,subprocess;shutil.copyfile("/unit","/tmp/unit");os.chmod("/tmp/unit",0o500);subprocess.run(["/tmp/unit"]+' + repr(args) + ',check=True,cwd="/tmp",env={"PATH":"/usr/bin:/bin","LANG":"C.UTF-8","TMPDIR":"/tmp","RUST_BACKTRACE":"0"})'
|
||||
raw = command(invoke + [script], folder)
|
||||
save(folder / ('local-linux-' + kind + '-' + mode + '.json'), dict(stdout_b64=base64.b64encode(raw).decode()))
|
||||
if mode == 'list': check_list(raw.decode(), EXPECTED['linux'][kind])
|
||||
else: check_output(raw, COUNTS['linux'][kind])
|
||||
dynamic = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '-d', '/unit'], folder).decode()
|
||||
versions = command(['docker', 'run', '--rm', '--network', 'none', '--read-only', '-v', item['path'] + ':/unit:ro',
|
||||
'--entrypoint', 'readelf', image, '--version-info', '/unit'], folder).decode()
|
||||
glibc = sorted(set(re.findall(r'GLIBC_(\d+\.\d+)', versions)), key=lambda x: tuple(map(int, x.split('.'))))
|
||||
require(glibc and tuple(map(int, glibc[-1].split('.'))) <= (2, 39), 'VM-compatible glibc requirement')
|
||||
item['glibc_max'] = glibc[-1]; item['needed'] = sorted(re.findall(r'Shared library: \[([^\]]+)\]', dynamic))
|
||||
require(source_files() == before, 'source and runner unchanged through qualification')
|
||||
manifest = dict(schema_version=1, profile=PROFILE, source_files=before, source_before_after_equal=True,
|
||||
runner_sha256=sha(__file__), scripts=scripts(), test_names=EXPECTED, test_counts=COUNTS, artifacts=artifacts,
|
||||
build_image_id=image, both_targets_clippy_D_warnings=True, linux_lists_actual=True,
|
||||
windows_lists_expected_until_native=True, local_linux_tests_passed=23, native_linux_executed=False,
|
||||
native_windows_executed=False, product_state_writes=False, rmm_jobs=False)
|
||||
save(folder / 'manifest.json', manifest)
|
||||
print(json.dumps(dict(manifest=str((folder / 'manifest.json').resolve()), manifest_sha256=sha(folder / 'manifest.json'),
|
||||
linux_tests=23, windows_tests_expected=22, native_executed=False)))
|
||||
|
||||
|
||||
def verified(path, new_run):
|
||||
path = path.absolute(); private(path.parent, True)
|
||||
require(path.name == 'manifest.json' and path.parent.parent == STATE and re.fullmatch(r'build-[0-9a-f-]{36}', path.parent.name), 'fixed build manifest path')
|
||||
value = load(path)
|
||||
require(value['schema_version'] == 1 and value['profile'] == PROFILE and value['runner_sha256'] == sha(__file__)
|
||||
and value['scripts'] == scripts() and value['test_names'] == EXPECTED and value['test_counts'] == COUNTS
|
||||
and value['source_before_after_equal'] is True and value['both_targets_clippy_D_warnings'] is True,
|
||||
'original manifest/runner/remote scripts/profile binding')
|
||||
if new_run: require(value['source_files'] == source_files(), 'new execution requires same current qualified source')
|
||||
for platform in COUNTS:
|
||||
require(set(value['artifacts'][platform]) == set(KINDS), 'exact two artifacts')
|
||||
for kind, item in value['artifacts'][platform].items():
|
||||
suffix = '.exe' if platform == 'windows' else ''
|
||||
require(Path(item['path']) == path.parent / platform / (kind + suffix)
|
||||
and Path(item['original_link_path']) == path.parent / platform / (kind + '.linked'), 'fixed private artifact paths')
|
||||
for field, digest in [('path', item['sha256']), ('original_link_path', item['original_link_sha256'])]:
|
||||
private(item[field]); require(sha(item[field]) == digest, 'immutable original/delivery bytes')
|
||||
require(Path(item['path']).stat().st_size == item['bytes'], 'artifact size unchanged')
|
||||
return value
|
||||
|
||||
|
||||
def access_settings(root, platform):
|
||||
"""Read strictly parsed existing access only when the parent executes native."""
|
||||
require(root is not None and not root.is_symlink(), 'explicit real access-root required')
|
||||
root = root.absolute(); require(root.is_dir() and root.resolve() == root, 'canonical access-root')
|
||||
if platform == 'linux':
|
||||
cfg = access.load_config(root / 'credentials/linux-vm.conf')
|
||||
require(cfg['address'] == '116.203.20.85' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed Cloud Linux bootstrap target')
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', '-i', str(Path(cfg['ssh_key_path']).expanduser()), 'root@116.203.20.85']
|
||||
else:
|
||||
cfg = access.load_config(root / 'credentials/server.conf')
|
||||
require(cfg['address'] == '88.99.80.202' and cfg['username'] == 'root' and cfg.get('port', '22') == '22'
|
||||
and cfg.get('ssh_key_path'), 'fixed server reverse-jump only')
|
||||
credentials = root / 'credentials'; private(credentials, True)
|
||||
record = load(credentials / 'windows-dev-access.json')
|
||||
require(set(record) == {'ssh_prefix', 'expires_at'}, 'known Windows access schema')
|
||||
expires = dt.datetime.fromisoformat(record['expires_at'])
|
||||
require(expires.utcoffset() is not None and dt.datetime.now(dt.timezone.utc) < expires, 'existing dev access still valid')
|
||||
key = str(Path(cfg['ssh_key_path']).expanduser())
|
||||
jump = ['ssh', '-F', '/dev/null', '-T', '-p', '22', '-i', key, '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'ForwardAgent=no', '-o', 'IdentitiesOnly=yes', '-W', '127.0.0.1:22240', 'root@88.99.80.202']
|
||||
prefix = ['ssh', '-F', '/dev/null', '-T', '-i', key, '-o', 'ProxyCommand=' + shlex.join(jump),
|
||||
'-o', 'HostKeyAlias=rmm-windows-dev', '-o', 'UserKnownHostsFile=' + str(credentials / 'windows-dev.known_hosts'),
|
||||
'-o', 'GlobalKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=yes', '-o', 'BatchMode=yes',
|
||||
'-o', 'IdentitiesOnly=yes', '-o', 'ForwardAgent=no', '-o', 'ConnectTimeout=10', 'rmm-dev@127.0.0.1']
|
||||
require(record['ssh_prefix'] == prefix, 'exact registered pinned reverse SSH prefix')
|
||||
private(credentials / 'windows-dev.known_hosts')
|
||||
return prefix
|
||||
|
||||
|
||||
def transport(prefix, command_text, data, folder, timeout=60):
|
||||
"""No stdout/stderr escapes the private case directory on transport failure."""
|
||||
try:
|
||||
result = subprocess.run(prefix + [command_text], input=data, capture_output=True, timeout=timeout)
|
||||
save(folder / ('transport-' + str(uuid.uuid4()) + '.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'native transport incomplete; same-case readback only')
|
||||
value = json.loads(result.stdout.decode('utf-8-sig'), object_pairs_hook=object_pairs)
|
||||
require(isinstance(value, dict) and 'bootstrap_error' not in value, 'native bootstrap incomplete; private receipt retained')
|
||||
return value
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transport-timeout-' + str(uuid.uuid4()) + '.json'), dict(timed_out=True,
|
||||
stdout_b64=base64.b64encode(error.stdout or b'').decode(), stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('native reply lost; read original case only') from None
|
||||
|
||||
|
||||
def linux_rpc(prefix, payload, folder):
|
||||
code = 'import os,json,subprocess,base64,hashlib,uuid\nfrom pathlib import Path\n' + inspect.getsource(require) + '\n' + inspect.getsource(linux_case)
|
||||
code += '\ntry:\n print(json.dumps(linux_case(' + repr(payload) + ')))\nexcept Exception as e:\n print(json.dumps(dict(bootstrap_error=True,error_class=type(e).__name__)))\n'
|
||||
return transport(prefix, 'python3 -', code.encode(), folder)
|
||||
|
||||
|
||||
def windows_rpc(prefix, payload, folder):
|
||||
script = 'try {\n' + WINDOWS + '\n} catch {[pscustomobject]@{bootstrap_error=$true;error_id=$_.FullyQualifiedErrorId;line=$_.InvocationInfo.ScriptLineNumber}|ConvertTo-Json -Compress;exit 1}'
|
||||
command_text = 'powershell.exe -NoLogo -NoProfile -NonInteractive -EncodedCommand ' + base64.b64encode(script.encode('utf-16le')).decode()
|
||||
return transport(prefix, command_text, (json.dumps(payload) + '\n').encode(), folder)
|
||||
|
||||
|
||||
def upload(prefix, item, destination, folder, kind):
|
||||
args = ['sftp'] + [part for part in prefix[1:-1] if part != '-T'] + ['-b', '-', prefix[-1]]
|
||||
# Linux sftp uses uppercase -P; Windows prefix has no -p option.
|
||||
if '-p' in args: args[args.index('-p')] = '-P'
|
||||
batch = ('put ' + json.dumps(item['path']) + ' ' + json.dumps(destination) + '\n').encode()
|
||||
save(folder / ('transfer-' + kind + '-intent.json'), dict(sha256=item['sha256'], bytes=item['bytes']))
|
||||
try:
|
||||
result = subprocess.run(args, input=batch, capture_output=True, timeout=60)
|
||||
save(folder / ('transfer-' + kind + '-result.json'), dict(returncode=result.returncode,
|
||||
stdout_b64=base64.b64encode(result.stdout).decode(), stderr_b64=base64.b64encode(result.stderr).decode()))
|
||||
require(result.returncode == 0, 'fixed artifact transfer failed; no retry')
|
||||
except subprocess.TimeoutExpired as error:
|
||||
save(folder / ('transfer-' + kind + '-timeout.json'), dict(timed_out=True,
|
||||
stderr_b64=base64.b64encode(error.stderr or b'').decode()))
|
||||
raise RuntimeError('artifact transfer incomplete; no retry') from None
|
||||
|
||||
|
||||
def linux_case(p):
|
||||
import resource
|
||||
import stat
|
||||
ident = str(uuid.UUID(p['id']))
|
||||
require(ident == p['id'] and p['action'] in ('prepare', 'run', 'read') and p['profile'] == 'windows-process-profile-v1', 'fixed unit case')
|
||||
require(os.geteuid() == 0 and os.uname().machine == 'x86_64' and set(p['artifacts']) == {'domain', 'contracts'}, 'fixed Linux root qualification')
|
||||
root = Path('/var/lib/rmm-windows-profile-units')
|
||||
def safe(path, directory):
|
||||
s = path.lstat()
|
||||
require(s.st_uid == 0 and stat.S_IMODE(s.st_mode) == (0o700 if directory else 0o600)
|
||||
and (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode) and s.st_nlink == 1), 'private fixed unit path')
|
||||
def write(path, value):
|
||||
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW, 0o600)
|
||||
with os.fdopen(fd, 'w') as out: json.dump(value, out); out.flush(); os.fsync(out.fileno())
|
||||
os.umask(0o077)
|
||||
case = root / ident
|
||||
if p['action'] == 'read' and not case.exists(): return dict(id=ident, status='remote_case_absent')
|
||||
if p['action'] == 'prepare':
|
||||
if not root.exists(): root.mkdir(mode=0o700)
|
||||
safe(root, True); case.mkdir(mode=0o700); write(case / 'intent.json', p)
|
||||
return dict(id=ident, prepared=True)
|
||||
safe(root, True); safe(case, True); safe(case / 'intent.json', False)
|
||||
original = json.loads((case / 'intent.json').read_bytes())
|
||||
require({k: v for k, v in p.items() if k != 'action'} == {k: v for k, v in original.items() if k != 'action'}, 'original complete unit intent')
|
||||
if p['action'] == 'read':
|
||||
if not (case / 'result.json').exists(): return dict(id=ident, status='started_without_result' if (case / 'started.json').exists() else 'prepared_without_start')
|
||||
safe(case / 'result.json', False); return json.loads((case / 'result.json').read_bytes())
|
||||
write(case / 'started.json', dict(manifest_sha256=p['manifest_sha256'], execute_once=True))
|
||||
temp = case / 'tmp'; temp.mkdir(mode=0o700)
|
||||
env = {'PATH': '/usr/bin:/bin', 'LANG': 'C.UTF-8', 'LC_ALL': 'C.UTF-8', 'TMPDIR': str(temp), 'RUST_BACKTRACE': '0'}
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_CORE, (0, 0)); resource.setrlimit(resource.RLIMIT_CPU, (15, 15)); resource.setrlimit(resource.RLIMIT_FSIZE, (1048576, 1048576))
|
||||
require(subprocess.run(['/usr/bin/unshare', '--net', '--', '/usr/bin/true'], env=env, capture_output=True, timeout=3).returncode == 0, 'network namespace required')
|
||||
listings = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
binary = case / kind; safe(binary, False)
|
||||
require(hashlib.sha256(binary.read_bytes()).hexdigest() == p['artifacts'][kind]['sha256'], 'exact Linux delivery')
|
||||
binary.chmod(0o500)
|
||||
listed = subprocess.run(['/usr/bin/unshare', '--net', '--', str(binary), '--list', '--format', 'terse'], cwd=case, env=env, capture_output=True, timeout=5, preexec_fn=limits)
|
||||
require(listed.returncode == 0 and len(listed.stdout) <= 65536 and len(listed.stderr) <= 65536, 'bounded actual listing')
|
||||
actual = sorted(line[:-6] for line in listed.stdout.decode().splitlines() if line.endswith(': test'))
|
||||
require(all(not line.strip() or __import__('re').fullmatch(r'[A-Za-z0-9_:]+: test', line) for line in listed.stdout.decode().splitlines())
|
||||
and actual == p['names'][kind] and len(actual) == {'domain': 16, 'contracts': 7}[kind], 'exact native test names before ANY test execution')
|
||||
listings[kind] = actual
|
||||
reports = {}
|
||||
for kind in ('domain', 'contracts'):
|
||||
with (case / (kind + '-stdout.bin')).open('xb') as out, (case / (kind + '-stderr.bin')).open('xb') as err:
|
||||
timed = False
|
||||
try: code = subprocess.run(['/usr/bin/unshare', '--net', '--', str(case / kind), '--test-threads=1'], cwd=case, env=env,
|
||||
stdin=subprocess.DEVNULL, stdout=out, stderr=err, timeout=18, preexec_fn=limits).returncode
|
||||
except subprocess.TimeoutExpired: timed = True; code = None
|
||||
out.flush(); err.flush(); os.fsync(out.fileno()); os.fsync(err.fileno())
|
||||
raw, errors = [(case / (kind + '-' + stream + '.bin')).read_bytes() for stream in ('stdout', 'stderr')]
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native output')
|
||||
reports[kind] = dict(sha256=p['artifacts'][kind]['sha256'], names=listings[kind], exit_code=code, timed_out=timed,
|
||||
stdout_b64=base64.b64encode(raw).decode(), stderr_b64=base64.b64encode(errors).decode())
|
||||
write(case / (kind + '-result.json'), reports[kind])
|
||||
value = dict(id=ident, platform='linux', profile=p['profile'], manifest_sha256=p['manifest_sha256'], runner_sha256=p['runner_sha256'],
|
||||
scripts=p['scripts'], reports=reports, network_namespace=True, environment_cleared=True, product_state_writes=False, rmm_jobs=False)
|
||||
write(case / 'result.json', value); return value
|
||||
|
||||
|
||||
WINDOWS = r'''
|
||||
$ErrorActionPreference='Stop';$p=([Console]::In.ReadLine()|ConvertFrom-Json)
|
||||
if([string]([guid]$p.id)-cne$p.id-or$p.action-notin@('prepare','run','read')-or$p.profile-cne'windows-process-profile-v1'-or$p.manifest_sha256-notmatch'^[a-f0-9]{64}$'-or$p.linux_proof_sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed Linux-first profile case'}
|
||||
$root='C:\ProgramData\RustDiscoveryBootstrap';$case=Join-Path $root ('windows-profile-'+$p.id)
|
||||
function Safe($path,$dir){$i=Get-Item -LiteralPath $path -Force;if($i.PSIsContainer-ne$dir-or($i.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Unit path type'};$a=Get-Acl -LiteralPath $path;if($a.GetOwner([Security.Principal.SecurityIdentifier]).Value-notin@('S-1-5-18','S-1-5-32-544')){throw 'Private unit owner'};$rules=@($a.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier]));if(!$rules.Count){throw 'Empty private ACL'};foreach($e in $rules){if($e.AccessControlType-ne'Allow'-or$e.IdentityReference.Value-notin@('S-1-5-18','S-1-5-32-544')-or($e.PropagationFlags-band[Security.AccessControl.PropagationFlags]::InheritOnly)){throw 'Broad private unit ACL'}}}
|
||||
function WriteNew($path,$value){$f=[IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read);try{$b=[Text.Encoding]::UTF8.GetBytes(($value|ConvertTo-Json -Depth 16 -Compress));$f.Write($b,0,$b.Length);$f.Flush($true)}finally{$f.Dispose()}}
|
||||
function MatchIntent($old){if($old.id-cne$p.id-or$old.profile-cne$p.profile-or$old.manifest_sha256-cne$p.manifest_sha256-or$old.runner_sha256-cne$p.runner_sha256-or$old.linux_proof_sha256-cne$p.linux_proof_sha256-or$old.scripts.linux_case_sha256-cne$p.scripts.linux_case_sha256-or$old.scripts.windows_script_sha256-cne$p.scripts.windows_script_sha256){throw 'Original profile intent'};foreach($kind in @('domain','contracts')){if($old.artifacts.$kind.sha256-cne$p.artifacts.$kind.sha256-or$old.artifacts.$kind.bytes-ne$p.artifacts.$kind.bytes-or(@($old.names.$kind)-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'Original artifact/test tuple'}}}
|
||||
if($p.action-eq'read'-and!(Test-Path -LiteralPath $case)){@{id=$p.id;status='remote_case_absent'}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $root $true
|
||||
if($p.action-eq'prepare'){if(Test-Path -LiteralPath $case){throw 'Existing case retained'};New-Item -ItemType Directory -Path $case|Out-Null;Safe $case $true;WriteNew (Join-Path $case 'intent.json') $p;@{id=$p.id;prepared=$true}|ConvertTo-Json -Compress;exit 0}
|
||||
Safe $case $true;$intent=Join-Path $case 'intent.json';Safe $intent $false;MatchIntent (Get-Content -LiteralPath $intent -Raw|ConvertFrom-Json)
|
||||
if($p.action-eq'read'){$result=Join-Path $case 'result.json';if(!(Test-Path -LiteralPath $result)){$status=if(Test-Path -LiteralPath (Join-Path $case 'started.json')){'started_without_result'}else{'prepared_without_start'};@{id=$p.id;status=$status}|ConvertTo-Json -Compress;exit 0};Safe $result $false;Get-Content -LiteralPath $result -Raw;exit 0}
|
||||
function RunUnit($exe,[string]$arguments){$s=New-Object Diagnostics.ProcessStartInfo;$s.FileName=$exe;$s.Arguments=$arguments;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.WorkingDirectory=$case;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$systemRoot=$env:WINDIR;$s.EnvironmentVariables.Clear();$s.EnvironmentVariables['SystemRoot']=$systemRoot;$s.EnvironmentVariables['WINDIR']=$systemRoot;$s.EnvironmentVariables['PATH']=$systemRoot+'\System32';$s.EnvironmentVariables['TEMP']=$script:temp;$s.EnvironmentVariables['TMP']=$script:temp;$s.EnvironmentVariables['RUST_BACKTRACE']='0';$c=New-Object Diagnostics.Process;$c.StartInfo=$s;if(!$c.Start()){throw 'Unit start'};try{$o=$c.StandardOutput.ReadToEndAsync();$e=$c.StandardError.ReadToEndAsync();$timed=$false;if(!$c.WaitForExit(18000)){$timed=$true;$c.Kill();if(!$c.WaitForExit(2000)){throw 'Own unit process did not exit'}};if(!$o.Wait(2000)-or!$e.Wait(2000)-or$o.Result.Length-gt1048576-or$e.Result.Length-gt1048576){throw 'Bounded unit output'};return @{exit_code=$c.ExitCode;timed_out=$timed;stdout_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($o.Result));stderr_b64=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($e.Result))}}finally{$c.Dispose()}}
|
||||
WriteNew (Join-Path $case 'started.json') @{execute_once=$true;manifest_sha256=$p.manifest_sha256};$script:temp=Join-Path $case 'tmp';New-Item -ItemType Directory -Path $script:temp|Out-Null;Safe $script:temp $true
|
||||
$lists=@{};$executables=@{}
|
||||
foreach($kind in @('domain','contracts')){$item=$p.artifacts.$kind;if($item.sha256-notmatch'^[a-f0-9]{64}$'){throw 'Fixed unit hash'};$exe=Join-Path $case ($kind+'.exe');Safe $exe $false;if((Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant()-cne$item.sha256-or(Get-Item -LiteralPath $exe).Length-ne$item.bytes){throw 'Exact unit bytes'};$list=RunUnit $exe '--list --format terse';if($list.exit_code-ne0-or$list.timed_out){throw 'Actual Windows listing'};$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($list.stdout_b64));$unexpected=@($text-split'\r?\n'|Where-Object{$_.Trim()-and$_-notmatch'^[A-Za-z0-9_:]+: test$'});if($unexpected.Count){throw 'Only exact terse test entries'};$actual=@($text-split'\r?\n'|Where-Object{$_-match': test$'}|ForEach-Object{$_-replace': test$',''}|Sort-Object);$count=if($kind-eq'domain'){16}else{6};if($actual.Count-ne$count-or($actual-join"`n")-cne(@($p.names.$kind)-join"`n")){throw 'All exact names BEFORE any tests'};$lists[$kind]=$actual;$executables[$kind]=$exe}
|
||||
$reports=@{};foreach($kind in @('domain','contracts')){$value=RunUnit $executables[$kind] '--test-threads=1';$value.sha256=$p.artifacts.$kind.sha256;$value.names=$lists[$kind];WriteNew (Join-Path $case ($kind+'-result.json')) $value;$reports[$kind]=$value}
|
||||
$value=@{id=$p.id;platform='windows';profile=$p.profile;manifest_sha256=$p.manifest_sha256;runner_sha256=$p.runner_sha256;scripts=$p.scripts;linux_proof_sha256=$p.linux_proof_sha256;reports=$reports;bootstrap_administrator_units=$true;local_service_proof=$false;environment_cleared=$true;product_state_writes=$false;rmm_jobs=$false};WriteNew (Join-Path $case 'result.json') $value;$value|ConvertTo-Json -Depth 16 -Compress
|
||||
'''
|
||||
|
||||
|
||||
def check_result(manifest, platform, value, payload):
|
||||
require(value.get('id') == payload['id'] and value.get('platform') == platform and value.get('profile') == PROFILE
|
||||
and value.get('manifest_sha256') == payload['manifest_sha256'] and value.get('runner_sha256') == manifest['runner_sha256']
|
||||
and value.get('scripts') == manifest['scripts'] and value.get('product_state_writes') is False and value.get('rmm_jobs') is False
|
||||
and value.get('environment_cleared') is True and set(value['reports']) == set(KINDS), 'complete native original binding')
|
||||
if platform == 'linux': require(value.get('network_namespace') is True, 'actual Linux netns proof')
|
||||
else: require(value.get('linux_proof_sha256') == payload['linux_proof_sha256'] and value.get('local_service_proof') is False, 'original Linux proof and honest account scope')
|
||||
for kind, item in value['reports'].items():
|
||||
require(item['names'] == EXPECTED[platform][kind] and item['sha256'] == manifest['artifacts'][platform][kind]['sha256']
|
||||
and item['exit_code'] == 0 and item['timed_out'] is False, 'all native exact test names/artifacts/exits')
|
||||
raw = base64.b64decode(item['stdout_b64'], validate=True); errors = base64.b64decode(item['stderr_b64'], validate=True)
|
||||
require(len(raw) <= 1048576 and len(errors) <= 1048576, 'bounded native outputs')
|
||||
check_output(raw, COUNTS[platform][kind])
|
||||
|
||||
|
||||
def execute(path, platform, access_root, case_id=None):
|
||||
setup_state(); path = path.absolute(); manifest = verified(path, new_run=case_id is None)
|
||||
prefix = access_settings(access_root, platform)
|
||||
if case_id is None:
|
||||
case_id = str(uuid.uuid4()); folder = STATE / case_id; folder.mkdir(mode=0o700)
|
||||
payload = dict(id=case_id, profile=PROFILE, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], scripts=manifest['scripts'],
|
||||
artifacts={kind: {k: manifest['artifacts'][platform][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED[platform])
|
||||
if platform == 'windows':
|
||||
proof_path = path.parent / 'linux-passed.json'; proof = load(proof_path)
|
||||
require(proof['verified'] is True and proof['manifest_sha256'] == sha(path), 'same-manifest real Linux proof FIRST')
|
||||
linux_payload = dict(payload, id=proof['case_id'], artifacts={kind: {k: manifest['artifacts']['linux'][kind][k] for k in ('sha256', 'bytes')} for kind in KINDS}, names=EXPECTED['linux'])
|
||||
check_result(manifest, 'linux', proof['native'], linux_payload)
|
||||
payload['linux_proof_sha256'] = sha(proof_path)
|
||||
intent = dict(id=case_id, platform=platform, manifest_path=str(path), manifest_sha256=sha(path), runner_sha256=sha(__file__),
|
||||
scripts=scripts(), access_root_sha256=hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), payload=payload)
|
||||
save(folder / 'intent.json', intent)
|
||||
save(folder / 'started-local.json', dict(create_once=True, no_retry=True))
|
||||
run_read = False
|
||||
else:
|
||||
require(str(uuid.UUID(case_id)) == case_id, 'original canonical case id')
|
||||
folder = STATE / case_id; private(folder, True); intent = load(folder / 'intent.json'); load(folder / 'started-local.json')
|
||||
require(intent['id'] == case_id and intent['platform'] == platform and intent['manifest_path'] == str(path)
|
||||
and intent['manifest_sha256'] == sha(path) and intent['runner_sha256'] == sha(__file__) and intent['scripts'] == scripts()
|
||||
and intent['access_root_sha256'] == hashlib.sha256(str(access_root.absolute()).encode()).hexdigest(), 'immutable same-case readback')
|
||||
payload = intent['payload']; run_read = True
|
||||
rpc = linux_rpc if platform == 'linux' else windows_rpc
|
||||
if not run_read:
|
||||
result = rpc(prefix, dict(payload, action='prepare'), folder)
|
||||
save(folder / 'prepared-remote.json', result); require(result == dict(id=case_id, prepared=True), 'fresh fixed case prepared')
|
||||
for kind in KINDS:
|
||||
destination = LINUX_REMOTE + '/' + case_id + '/' + kind if platform == 'linux' else '/C:/ProgramData/RustDiscoveryBootstrap/windows-profile-' + case_id + '/' + kind + '.exe'
|
||||
upload(prefix, manifest['artifacts'][platform][kind], destination, folder, kind)
|
||||
result = rpc(prefix, dict(payload, action='read' if run_read else 'run'), folder)
|
||||
save(folder / ('readback-' + str(uuid.uuid4()) + '.json'), result)
|
||||
if result.get('status'):
|
||||
require(run_read and result.get('id') == case_id and result['status'] in ('remote_case_absent', 'prepared_without_start', 'started_without_result'), 'fixed read-only incomplete status')
|
||||
print(json.dumps(dict(verified=False, platform=platform, case_id=case_id, status=result['status'], retry_allowed=False))); return
|
||||
check_result(manifest, platform, result, payload)
|
||||
proof = dict(verified=True, case_id=case_id, platform=platform, manifest_sha256=sha(path), runner_sha256=manifest['runner_sha256'], native=result)
|
||||
destination = path.parent / (platform + '-passed.json')
|
||||
if destination.exists(): require(load(destination) == proof, 'preserve identical native proof')
|
||||
else: save(destination, proof)
|
||||
save(folder / 'verified.json', dict(verified=True, proof_sha256=sha(destination))) if not (folder / 'verified.json').exists() else require(load(folder / 'verified.json') == dict(verified=True, proof_sha256=sha(destination)), 'same verified receipt')
|
||||
print(json.dumps(dict(verified=True, platform=platform, case_id=case_id, tests=sum(COUNTS[platform].values()),
|
||||
manifest_sha256=sha(path), proof_sha256=sha(destination))))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('build-local', 'linux', 'windows', 'readback-linux', 'readback-windows'))
|
||||
parser.add_argument('--manifest', type=Path); parser.add_argument('--case'); parser.add_argument('--access-root', type=Path)
|
||||
parser.add_argument('--execute-native-tests', action='store_true'); args = parser.parse_args()
|
||||
if args.action == 'build-local':
|
||||
require(not (args.manifest or args.case or args.access_root or args.execute_native_tests), 'local build only'); build()
|
||||
elif args.action.startswith('readback-'):
|
||||
require(args.manifest and args.case and args.access_root and not args.execute_native_tests, 'original case readback only')
|
||||
execute(args.manifest, args.action.removeprefix('readback-'), args.access_root, args.case)
|
||||
else:
|
||||
require(args.manifest and args.access_root and args.execute_native_tests and not args.case, 'explicit new native platform run')
|
||||
execute(args.manifest, args.action, args.access_root)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except Exception as error:
|
||||
print(json.dumps(dict(error='WINDOWS_PROFILE_QUALIFICATION_INCOMPLETE', error_class=type(error).__name__, details_suppressed=True)))
|
||||
raise SystemExit(2) from None
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Linux-first-Entwicklung und reale VM-Abnahme
|
||||
|
||||
Stand: 2026-11-14 · Spezifikation 1.18. Das begrenzte Linux-MVP ist inzwischen
|
||||
Stand: 2026-11-14 · Spezifikation 1.19. Das begrenzte Linux-MVP ist inzwischen
|
||||
dokumentiert abgenommen; aktuelle Nachweise stehen in [handover.md](handover.md).
|
||||
Die getrennte Windows-SYSTEM-Grenze ist in Spezifikation0.1 und
|
||||
[windows-system-policy.md](windows-system-policy.md) präzisiert; Quellen-/Build-
|
||||
|
||||
@@ -1,6 +1,27 @@
|
||||
# Verbindliche Projektentscheidungen
|
||||
|
||||
Stand: **2026-11-14**, Spezifikation **1.18** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung.
|
||||
Stand: **2026-11-14**, Spezifikation **1.19** (`Rust_RMM_Implementierungsspezifikation.md`). Die ausdrücklichen normativen Entscheidungen in Kapitel 0 haben Vorrang vor früheren Architekturannahmen. Version 1.6 ersetzt die lokale Servertopologie durch den dedizierten Internetserver; Version 1.7 präzisiert das Notebook als reinen Entwicklungsrechner; Version 1.8 erlaubt vorgezogene parallele Windows-Entwicklung.
|
||||
|
||||
## Enger Windows-M4-MSI-Schnitt (Version1.19)
|
||||
|
||||
Die beauftragte Windows-MVP-Fortsetzung erhält als nächsten getrennten Schnitt
|
||||
zwei feste eigene MSI-Rezepte1.0 und1.0→1.1. Dies ist eine explizite technische
|
||||
Präzisierung innerhalb des bereits beauftragten M4-Umfangs, keine neue pauschale
|
||||
Userfreigabe für Paketwirkungen. Kapitel0 bindet vollständiges optionales
|
||||
Windowsmanifest, unveränderlichen Tenantkatalog, exakte automatisch abgeleitete
|
||||
Job-/Versuch-/Artefaktreferenz, neue getrennte SYSTEM-Paketerlaubnis und sichtbare
|
||||
Planbytes. Alte SCM-only-Policies erteilen keine Paketrechte. Native
|
||||
Installation/Upgrade/Noop bleiben jeweils eigene WebUI-genehmigte Jobs.
|
||||
|
||||
APT-/Windowsmanifest schließen sich aus; alte Linuxbytes und freie Linux-
|
||||
Artefaktpfade behalten ihre bisherigen Verträge. Kein freier Installer oder
|
||||
Rezeptargumentvektor, kein Repair/Downgrade/Fresh1.1, keine EXE-/Skript-/Reboot-
|
||||
Erlaubnis in diesem Schnitt. Cache-/Provider-/Installerwirkung bleibt bei
|
||||
Abandon ausgeschlossen. Noop und tatsächliche Nachbedingungen müssen innerhalb
|
||||
des ursprünglichen Budgets unter gültigem Clock-/Fence-/Abbruchkontext liegen.
|
||||
Ein später belegter Zustand heilt keinen Timeout. Die ursprünglichen MSI-
|
||||
Artefakt- und Nativeberichte bleiben unverändert. Quelle/Build/Unitnachweis
|
||||
öffnet keine Capability und ist keine tatsächliche Paketabnahme.
|
||||
|
||||
## Begrenzte Windowsfreigaben des Users (Version1.18)
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Numerische Windows-Zeitdienstdiagnose
|
||||
|
||||
Stand2026-11-14: Diagnosequelle implementiert und unabhängig vom Produktions-
|
||||
Clockpfad gebaut. Keine Lockerung von Statusguard, ALPC-/Identitätsprüfung,
|
||||
`NativeClock.now()` oder `ADAPTER_QUALIFIED=false`. Keine neue Clockauthority.
|
||||
Die feste zusätzliche Named-Pipe-Statusabfrage liefert ausschließlich acht
|
||||
numerische Felder: Phase, tatsächliche RPC-Rückgabe samt Presenceflag,
|
||||
aufgefangene Ausnahme und Strukturgrößen-/Zeigerpräsenz. Keine Quellen-/Peer-
|
||||
Namen, Pointerwerte oder zusätzlichen Rückgabeeinträge werden veröffentlicht.
|
||||
Eigener begrenzter Diagnoseworker; nach Timeout kein Ersatz/Retry.
|
||||
|
||||
Lokal tatsächlich bestanden: Windows-Example-Clippy mit Warnungen als Fehler,
|
||||
fünf Linux-Clocktests, Windows-Testlink (nicht nativ ausgeführt) und Release-
|
||||
Link.125Quellinputs vorher/nachher identisch. Originale Werkzeugabweichung
|
||||
(Buildimage ohne WIDL) privat erhalten; erfolgreicher Build mit vorhandenem
|
||||
unveränderlichem Clockimage. Artefakt `ecad703ad7208d55681c63ba9513fcf4c73b671951d4d1b5db1af9df49f43bdf`,
|
||||
1779541Bytes. Privater Build `release-ca9a63b8-127c-4933-a45d-9e82449d6980`,
|
||||
Qualifikation `36ce552e…`.
|
||||
|
||||
Danach tatsächlich auf der Windows-VM unter dem separaten LocalService-
|
||||
Bootstrapdienst ausgeführt, Fall `2996df8c-b261-466a-8963-a526babf7f67`.
|
||||
NativeReport und getrennter Readback identisch, eigener Dienst entfernt.
|
||||
ALPC weiter1753/kein Endpunkt, keine erfolgreichen Identitätsnegativkontrollen.
|
||||
Zusätzliche unabhängige Abfrage:1783, `stage=90`, `rpc_exception=1783`,
|
||||
`native_rpc_return_present=0`, `status_present=0`. **Eine aufgefangene RPC-/
|
||||
NDR-Ausnahme vor normaler Stub-Rückkehr ist belegt; der eigene nachgelagerte
|
||||
Strukturguard wurde nicht erreicht.** Das Nullwertfeld `native_rpc_return=0`
|
||||
ist ohne Presenceflag ausdrücklich kein erfolgreicher nativer Return.
|
||||
|
||||
Die genaue RPC-/NDR-Ursache bleibt offen. Source-/IDL-Prüfung folgt anhand
|
||||
des [Microsoft-IDL](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-w32t/5793e908-22ef-4cea-962f-fca8a72c485a).
|
||||
W32Time wurde für diese Diagnose nicht umkonfiguriert, keine Uhr gesetzt und
|
||||
kein RMM-Job ausgeführt. Zentrale Windows0/0/0/0 und Linux30/30/26/0 samt
|
||||
geschlossenen Testhooks/Rootpolicy erhalten. Dieses Ergebnis qualifiziert
|
||||
weder Named-Pipe-Serveridentität noch eine vertrauenswürdige Uhr. Erst recht
|
||||
öffnet es keinen Grant-/Jobpfad.
|
||||
|
||||
## Enger WIDL-Zeigervertrag: lokal korrigierter Kandidat
|
||||
|
||||
Die erhaltene generierte WIDL7-Typbeschreibung kodiert den ursprünglichen
|
||||
Status-Ausgabeparameter als `FC_RP→FC_RP→STATUS`. Der dokumentierte Vertrag
|
||||
verlangt außen eine Referenz, innen den Unique-Statuspointer. Auch die neu aus
|
||||
Microsofts vollständigem IDL erzeugte WIDL7-Datei zeigt den doppelten Ref:
|
||||
Es handelt sich präziser um die rekursive Parameterattributbehandlung dieses
|
||||
Compilers, nicht lediglich um eine andere Schreibweise unseres Narrow-IDL.
|
||||
[Pointerregeln](https://learn.microsoft.com/en-us/windows/win32/rpc/three-pointer-types),
|
||||
[Typformat](https://learn.microsoft.com/en-us/windows/win32/rpc/pointers-tfs),
|
||||
[WIDL7-Compilerquelle](https://raw.githubusercontent.com/wine-mirror/wine/wine-7.0/tools/widl/typegen.c).
|
||||
|
||||
Der enge Kandidat deklariert den inneren Typ ausdrücklich `[unique]` und lässt
|
||||
das redundante äußere `[ref]` zugunsten des dokumentierten Parameterdefaults
|
||||
weg. WIDL erzeugt tatsächlich `FC_RP→FC_UP→STATUS`; kein Stubbyte wurde gepatcht.
|
||||
Ganze Procedureformatfolge/Opnum6 unverändert, alle19Statusfeldoffsets und120B-
|
||||
Struktur gegen frisch erzeugte Microsoft-Full-IDL-Header per AMD64-Clangassert
|
||||
geprüft. C/Auth/Statusguard/Clockgate unverändert. MicrosoftMIDL wurde mangels
|
||||
nativer Werkzeuge ausdrücklich noch nicht ausgeführt.
|
||||
|
||||
Neuer privater Buildfall `f5805176-4a5a-468d-b1b2-088030253c8d`, Qualifikation
|
||||
`e96baaf6…`:63Compilerinputs vorher/nachher gleich, fünf Clocktests tatsächlich
|
||||
bestanden, beide WindowsGNU-Alltargets-Clippyprofile, Release- und Unitlink
|
||||
bestanden. Ein zunächst0Tests selektierender Aufruf und ein falscher lokaler
|
||||
Harnesslink bleiben als unvollständige Vorgängerlogs erhalten. Neues Artefakt
|
||||
`91889303e1650d8612b946512f069a3421eb686c7bed315426c48bd62b18a1fd`,
|
||||
Original-Linkdatei erhalten. Nur `native/w32time.idl` geändert, SHA `37da4acb…`.
|
||||
|
||||
**Native Prüfung dieses Kandidaten noch nicht ausgeführt.** Der tatsächliche
|
||||
Auslöser der bisherigen1783-Ausnahme ist damit weiter nicht bewiesen. Kein
|
||||
Clockvertrauen aus Codegenerierung oder lokalem Build, keine Rückstufung vom
|
||||
unqualifizierten ALPC-Pfad auf eine nur vermeintlich authentisierte Pipe.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Native M3-Eventlog-Vertragsprüfung
|
||||
|
||||
`deploy/windows_eventlog_acceptance.py` ist ein neuer, separater Bootstraprunner.
|
||||
Der unveränderte Profilrunner und dessen16/7- beziehungsweise16/6-Belege bleiben
|
||||
readbackfähig. Neuer Namespace: `windows-eventlog-contracts`.
|
||||
|
||||
Der neue Pack enthält ausschließlich Domain-Lib17 und Core-Contracts7 auf Linux,
|
||||
danach Domain-Lib17 und Core-Contracts6 auf Windows. Der Unix-OpenSSL-Paritätstest
|
||||
entfällt unter Windows. Server-/Windows-M3-Quellen werden zusätzlich exakt an den
|
||||
geprüften Stand gebunden, einschließlich Schemars-Metadatenfix und Gateway-
|
||||
Ergebnisprüfung. Diese Adapterquellen werden durch die beiden Vertrags-EXEs
|
||||
**nicht** als native Eventlogprovider qualifiziert. Es gibt weder Liveabfrage
|
||||
noch RMM-Job, Capabilityaktivierung, Dienst-/Produktdatenbank-/PKIänderung.
|
||||
|
||||
Tatsächlich auf Cloud-Linux bestanden:24Prüfungen ohne Skips, Fall
|
||||
`6f9bdfb7-3902-462e-a08f-ec612e36c635`. Gemeinsamer Build
|
||||
`afb44f9b-8040-4efa-ac2c-fd6c3a43f8a6`, Manifest-SHA256
|
||||
`ed1371e9b058f8e7f874b071fcfce1bc409769546d5e63235295adadb5ec1de7`,
|
||||
Linuxproof-SHA256
|
||||
`d37ce1644dd169c932176e3e9bd33cee22b9fa4698e9faa0f5aea0f2de09f7d4`.
|
||||
Anschließend bestanden auf der Windows-VM alle23Prüfungen ohne Skips, Fall
|
||||
`ccb258a7-5930-4e02-b955-d522f98f0c36`, Windowsproof-SHA256
|
||||
`ee1ba206637f2465e7a066b6e23ca2f8bf9b57c0ae08ddc80fe23e0199b027e1`.
|
||||
Dieser Beleg bindet denselben Build und den ursprünglichen Linuxproof.
|
||||
Der lokale Build mit
|
||||
98identischen Vorher-/Nachher-Inputs, vier erhaltenen Original-Linkdateien,
|
||||
beiden Ziel-Clippyprüfungen und24lokalen Linux-Vertragstests ist bestanden.
|
||||
|
||||
Der lokale Offlinebuild erhält Original-Linkdateien neben gestrippten
|
||||
Lieferkopien, prüft Clippy für beide Vertragsziele und führt die tatsächlichen
|
||||
Linux-Lieferbytes mit exakter Liste und ungefiltert aus. Windowslisten bleiben
|
||||
bis zur tatsächlichen Windowsausgabe erwartet. Vor/nach müssen sämtliche
|
||||
gebundenen Cargo-/Toolchain-/Domain-/Core-/Protocol-/Proto-/Server-/Windows- und
|
||||
Runner-/Bootstrapquellen gleich sein. Ein weiterer Backend-/PG-Testlauf ist
|
||||
nicht Bestandteil dieses Runners.
|
||||
|
||||
**Aufrufschema; beide obigen nativen Fälle tatsächlich ausgeführt:**
|
||||
|
||||
```sh
|
||||
python3 deploy/windows_eventlog_acceptance.py build-local
|
||||
python3 deploy/windows_eventlog_acceptance.py linux --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
python3 deploy/windows_eventlog_acceptance.py windows --manifest devstate/windows-eventlog-contracts/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
```
|
||||
|
||||
Artefakte und lokale Belege bleiben im isolierten Eventlogworktree. Ausschließlich
|
||||
`--access-root` liest bei ausdrücklicher nativer Ausführung streng geparste
|
||||
bestehende SSH-Konfigurationen für Cloud-Linux116.203.20.85 beziehungsweise den
|
||||
bekannten gepinnten Windows-Reversezugang. Keine Credentialkopie oder neue
|
||||
Hostkeyannahme. Windows bindet den SHA256 des zuvor tatsächlich verifizierten
|
||||
Linuxbelegs desselben Manifests.
|
||||
|
||||
Jeder native Fall hat eigene Create-once-Intents und Startbelege. Linux nutzt
|
||||
privaten Rootscratch, geleerte Umgebung und eigene Netzwerknamespace. Beide
|
||||
Plattformen prüfen vor dem ersten Teststart die vollständigen Testnamen beider
|
||||
Programme. Windows läuft als Bootstrapadministrator, kein LocalService-Nachweis.
|
||||
Ausgaben und Transportfehler bleiben privat; stdout enthält nur Status und
|
||||
Nachweishashes.
|
||||
|
||||
Nach Antwortverlust ausschließlich `readback-linux` beziehungsweise
|
||||
`readback-windows` mit ursprünglichem Manifest, `--case UUID` und `--access-root`.
|
||||
Readback lädt nichts hoch und startet nichts neu. Er bindet unveränderliche
|
||||
Originalintents, Manifest sowie Runner-/Remotescripthashes; spätere
|
||||
Produktquellenänderungen erzwingen keinen neuen Lauf. Nur neue Starts benötigen
|
||||
den aktuellen exakt qualifizierten Quellstand. Unvollständige Fälle bleiben
|
||||
unvollständig; kein automatischer zweiter Versuch.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Windows-M3: begrenztes Ereignisprotokoll
|
||||
|
||||
Stand2026-11-14: Quelle implementiert und unabhängig gegenseitig geprüft,
|
||||
noch nicht auf dem Windowsgast installiert oder als RMM-Aktion ausgeführt.
|
||||
Der isolierte Branch enthält auch das bereits separat nativ qualifizierte
|
||||
optionale PowerShell-Prozessprofil. Keine Capability wurde veröffentlicht.
|
||||
|
||||
`query_logs` bindet ausschließlich Quelle
|
||||
`windows.eventlog.application.rustdiscovery-mvp-test`, Kanal `Application`
|
||||
und Provider `RustDiscovery-MVP-Test`. Erforderlich sind Windows-/Sync- und
|
||||
eigene Fixturecapability, `logs:read` und `agent_service`. Kein SYSTEM-Logpfad,
|
||||
kein freies XPath, kein angeforderter Liveabruf als passives Inventar.
|
||||
UTC-Zeitfenster höchstens24Stunden, höchstens65536Ausgabebytes und feste
|
||||
innere5Sekunden-Grenze; äußerer Jobrahmen10–120Sekunden. Alle Werte stehen
|
||||
aus hashgeprüften gespeicherten Planbytes vor der WebUI-Genehmigung fest.
|
||||
|
||||
Die synchrone native Eventlog-API läuft im begrenzten eigenen Prozess innerhalb
|
||||
des vorhandenen atomaren JobObjects. Der Child prüft tatsächlichen LocalService-
|
||||
Token samt Agent-Service-SID, echten SCM-/Kernel-Elternprozess, geschützte
|
||||
Konfiguration, signierten Originalrequest, aktuelle qualifizierte Uhr und Boot,
|
||||
den bereits dauerhaft gebuchten Verbrauch/Start samt tatsächlichem SQLite-
|
||||
Dateihandle sowie einen einmaligen Startmarker. Der Aufruf über den festen
|
||||
CLI-Modus allein verleiht keine Berechtigung. Keine Schlüssel-/Requestbytes
|
||||
auf der Kommandozeile. Uhr-/Jobgates bleiben geschlossen.
|
||||
|
||||
Worker und Server prüfen konkrete Herkunft, Zeitfenster, Budget, Vollständigkeit
|
||||
und Fehler. Bekannte Ereignis-/Byte-/Einzelereignisgrenzen bleiben ausdrücklich
|
||||
partiell; Zeitüberschreitung oder Berechtigungsfehler werden kein vollständiger
|
||||
Erfolg. Eine im Review gefundene Lücke im serverseitigen Successguard wurde
|
||||
geschlossen: `win32_error` ausdrücklichnull, kein Neustartbedarf und generisches
|
||||
Kürzungsflag identisch zur konkreten Evidenz.
|
||||
|
||||
Lokal tatsächlich bestanden:238Rusttests, ein isolierter PostgreSQL-Fall und
|
||||
38Webtests samt Typecheck/Build/Clippy. Der PG-Fall prüfte unter anderem fehlendes
|
||||
`logs:read`, verlorene Capability und `pending_approval` mit0Jobs/Outbox/Grants.
|
||||
Nach dem Successguard-Fix wurden dessen bestehende Mutationsmatrix und
|
||||
Server-Clippy gezielt erneut ausgeführt. Drei portable Provider-/Ergebnistests
|
||||
liefen tatsächlich im Linux-Buildcontainer; zwei Windows-Workerprüfungen sind
|
||||
bisher nur crosskompiliert. Keine dieser Ebenen ersetzt den Nativepfad.
|
||||
|
||||
Private Quellenbelege: `devstate/windows-eventlog-backend/qualification.json`
|
||||
(`facab5cc…`), `qualification-success-flags.json` (`f5972644…`) und
|
||||
`devstate/windows-eventlog/windows-source-qualification.json` (`feb16e79…`).
|
||||
Die gesonderte Vertragsabnahme ist zuerst auf Cloud-Linux24, danach Windows23
|
||||
ohne Skips bestanden. Manifest `ed1371e9…`; Linuxfall `6f9bdfb7…`, Windowsfall
|
||||
`ccb258a7…`. [Native Runnerdokumentation](windows-eventlog-contract-acceptance.md)
|
||||
hält genaue Bindungen und Grenzen fest. Kein Live-Eventlog-/Workerrollenbeweis.
|
||||
|
||||
Weiter offen: reale LocalService-Eventlog-API, eigene Fixtureereignisse,
|
||||
Filter-/Zeit-/Ausgabe-/Fehlergrenzen und vollständiger WebUI-genehmigter Job.
|
||||
Keine Registrierung oder Erhebung auf dem Ziel wurde durch diese Quellarbeiten
|
||||
ausgeführt. Der Schemars-Attributfix entfernt lediglich die irreführende
|
||||
Nullable-Angabe des optionalen Prozessprofils; strikte Deserialisierung und
|
||||
fehlendes Feld bleiben unverändert. Die vorherigen Nativebelege bleiben an
|
||||
ihre ursprünglichen Quellen gebunden.
|
||||
@@ -0,0 +1,112 @@
|
||||
# Windows Helper: begrenzte Transportbestätigung
|
||||
|
||||
Dieser Schnitt ist im isolierten Zweig `codex/windows-pipe-drain` implementiert.
|
||||
Eine native Ausführung des neuen Framings und ein Komponentenupgrade sind noch
|
||||
nicht nachgewiesen. Die bestehenden Nachweise des Agenten `89004ad3…` und Helpers
|
||||
`e6aacbdd…` bleiben historische Belege ihres ursprünglichen Framings.
|
||||
|
||||
## Anlass und Beleggrenze
|
||||
|
||||
Beim tatsächlichen Agenten wurde `client_read_reply / HELPER_PIPE_IO / 233`
|
||||
beobachtet; die Helperdiagnose war nicht vorhanden. Der bisherige Dienst rief
|
||||
auch nach erfolgreichem Schreiben der Antwort sofort `DisconnectNamedPipe` auf.
|
||||
Microsoft dokumentiert, dass dabei ungelesene Pipebytes verworfen werden. Das
|
||||
ist ein konkreter möglicher Fehlerpfad, aber kein Nachweis, dass genau dieser
|
||||
Pfad die beobachtete Störung verursacht hat.
|
||||
[DisconnectNamedPipe](https://learn.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)
|
||||
|
||||
Eine fehlende Diagnose beweist weder einen erfolgreichen Peercheck noch eine
|
||||
bestimmte Ablehnung: strukturierte `Denied`-Antworten erzeugen keinen privaten
|
||||
Pipefehlerbeleg, Connect-Leerlauf kann ohne Beleg enden, und das begrenzte
|
||||
Diagnoseschreiben selbst kann fehlschlagen. Diese Pfade werden hier nicht
|
||||
umgedeutet oder gelockert.
|
||||
|
||||
## Framing v2 und Reihenfolge
|
||||
|
||||
Agent und Helper verwenden ausschließlich `\\.\pipe\RustDiscovery-System-v2`.
|
||||
Jeder JSON-Frame beginnt mit acht ASCIIbytes `RDPIPC02`, gefolgt von vier Bytes
|
||||
Länge in Big Endian und den bisherigen, maximal 1 MiB großen JSONbytes.
|
||||
V1 und V2 haben unterschiedliche Endpunkte; zusätzlich verweigert der V2-Parser
|
||||
alte oder fremde Framingtags. Es gibt keinen stillen Fallback. Beide EXEs müssen
|
||||
als gemeinsam qualifiziertes, gegenseitig gepinntes Paar bereitgestellt werden.
|
||||
Die JSONschemas von Call/Reply, `helper.system.v1`, Systempolicy-Schema 1 und
|
||||
RMM-Jobbytes ändern sich nicht.
|
||||
|
||||
Nach dem vollständigen Lesen der Antwort prüft der Agent weiterhin den tatsächlichen
|
||||
Helperprozess, Schema, Challenge, Enrollmentbindung, Policyhash, Helperbinaryhash
|
||||
und die Operation/Antwort-Zuordnung. Erst danach schreibt er genau 56 Bytes:
|
||||
`RDPACK02` (8), ursprüngliche UUID-Challenge in UUID-Bytefolge (16), SHA-256 der
|
||||
**exakt empfangenen JSON-Antwortbytes** (32). Es findet keine Re-Serialisierung
|
||||
für diese Prüfsumme statt. Auch eine vollständig geprüfte `Denied`-Antwort wird
|
||||
so transportseitig bestätigt, ohne sie in einen Erfolg umzuwandeln.
|
||||
|
||||
Der Helper prüft denselben bereits authentifizierten Peer vor dem Schreiben und
|
||||
nach dem Lesen der Bestätigung. Schreiben, Empfang und Prüfung der Bestätigung
|
||||
teilen dieselbe bisherige Antwortdeadline von fünf Sekunden; der Client behält
|
||||
seine bisherige Gesamtdeadline. Erst danach trennt die Dienstschleife die Pipe.
|
||||
Fehlende, falsche oder verspätete Bestätigung schließt den bestehenden Syncgate
|
||||
und trennt die Verbindung über den bisherigen Fehlerpfad; statische Diagnosen
|
||||
unterscheiden `server_drain_receipt` und `client_drain_receipt`. Es gibt keinen
|
||||
weiteren Aufruf, Retry oder erneute Ausführung.
|
||||
|
||||
Diese Bestätigung bestätigt nur den Empfang der Antwortbytes. Sie ist kein
|
||||
JobResult-, Journal-, SignedSync-, Grant-, Freigabe- oder Wirkungsbeleg und löscht
|
||||
keinen dauerhaften Zustand. Ein bereits ausgeführter Auftrag wird durch einen
|
||||
fehlenden Transport-ACK nicht zurückgenommen oder wiederholt.
|
||||
|
||||
`FlushFileBuffers` wird nicht verwendet: dieser synchrone Pipeaufruf wartet laut
|
||||
Microsoft bis zum Lesen aller gepufferten Daten und bietet hier keine passende
|
||||
begrenzte Warteoperation.
|
||||
[FlushFileBuffers](https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-flushfilebuffers)
|
||||
|
||||
## Prüfung und verbleibender nativer Nachweis
|
||||
|
||||
Die bestehenden IPC-Codecfälle prüfen zusätzlich fremde/alte Frameversionen,
|
||||
begrenzte Längen sowie manipulierte ACK-Tags, Challenge und Prüfsumme. Eine andere
|
||||
JSON-Bytefolge mit gleichem JSON-Inhalt darf den ursprünglichen Frame nicht
|
||||
bestätigen. Die bestehenden Unitfallzahlen bleiben dadurch unverändert.
|
||||
Lokale Qualifikation wird separat in einem geschützten `devstate/`-Beleg mit
|
||||
Quellen- und Artefakthashes erfasst. Cross-Clippy und Linken sind kein nativer
|
||||
Pipebeleg. Vor einem Zielupgrade sind unabhängiger Quellreview, die nativen
|
||||
Windows-Units des gleichen Manifests und ein eigener erhaltender Paarupgrade mit
|
||||
explizitem Backup sowie anschließendem tatsächlichen Agent/Helper-Austausch
|
||||
notwendig. Alle Produktgates bleiben geschlossen.
|
||||
|
||||
Lokale Ausführung: Default- und `system-helper`-Clippy für alle Windows-GNU-Targets
|
||||
mit `-D warnings`, Release-Build beider EXEs und Linken beider Unitprogramme waren
|
||||
erfolgreich. 61 gebundene Quelldateien blieben vor/nach dem Lauf gleich. Die
|
||||
bestehenden 23 Library- und 7 Binary-Unitfälle sind weiterhin die **erwartete**
|
||||
native Liste; hier wurde kein Windows-Testprogramm ausgeführt. Geschützter
|
||||
Beleg: `devstate/windows-pipe-drain/qualification-1e0f2b22-1e74-41af-b8ed-0a356be054ba/qualification.json`.
|
||||
|
||||
## Separater Build-/Unitrunner
|
||||
|
||||
`deploy/windows/system_pipe_acceptance.py` erstellt einen neuen Pack unter
|
||||
`devstate/windows-pipe-drain-build/`. Er prüft den unveränderten lokalen
|
||||
Qualifikationsbeleg samt ursprünglichen Links und verwendet die bereits
|
||||
bestandenen Clippy-/Release-/Unitlinkschritte wieder. Nur die fehlenden beiden
|
||||
Release-Stateprobes werden ergänzt. Alle sechs Auslieferungsdateien erhalten
|
||||
eine unveränderte `.linked`-Kopie; ausschließlich die Unit-Auslieferungskopien
|
||||
werden von Debuginformationen befreit. Neue Quellen einschließlich Runner,
|
||||
Compilerimage, Cargo-/Protoinputs und tatsächlich verwendeter Bootstrapmodule
|
||||
sind vor/nach dem Build gebunden.
|
||||
|
||||
`--access-root` muss der ursprüngliche Hauptcheckout sein. Nur dort werden die
|
||||
vorhandenen geschützten Zugangskonfigurationen für den bereits gepinnten
|
||||
Bootstraptransport und die tatsächlichen Linux-80-/Windows-58-Corebelege gelesen.
|
||||
Es werden keine Zugangsdaten oder Main-`devstate`-Bäume kopiert oder verlinkt.
|
||||
Neue Build-, Upload- und Unitfallbelege gehören zum isolierten Pipeworktree.
|
||||
|
||||
Der Native-Unitfall verwendet den neuen Namespace `native-pipe-v2`. **Beide**
|
||||
vollständigen nativen Listen müssen exakt den erwarteten 23 Library- und 7
|
||||
Binary-Namen entsprechen, bevor irgendein Unitfall ausgeführt wird. Intent,
|
||||
Listen, Start und einzelne Testergebnisse werden create-only gespeichert.
|
||||
Nach einem Antwortverlust darf ausschließlich derselbe Fall gelesen werden;
|
||||
auch ein fehlender oder unvollständiger Fall löst keinen erneuten Start aus.
|
||||
Die Units laufen als Bootstrapadministrator, nicht als Produkt-LocalService,
|
||||
und beweisen keinen tatsächlichen Pipeaustausch. Zentral gespeicherte
|
||||
Gerätezähler und geschlossene Fault-/Policyflags werden vor/nach verglichen.
|
||||
|
||||
Der bestehende rohe `helper_peer_controls::raw`-Probe schreibt weiterhin einen
|
||||
V1-Header. Sein Ablehnungsresultat ist deshalb **kein** V2-Peernegativnachweis;
|
||||
Runner und Manifest behaupten ausdrücklich keine solche Qualifikation.
|
||||
@@ -0,0 +1,83 @@
|
||||
# Gemeinsame MSI-Verträge: Linux-first-Unitpack
|
||||
|
||||
Der neue Runner `deploy/windows_msi_contract_acceptance.py` gehört zum isolierten
|
||||
Worktree `rust-discovery-windows-msi-integration`. Historische M3-, Profil- und
|
||||
NoStart-Runner sowie ihre ursprünglichen Manifeste bleiben unverändert.
|
||||
|
||||
Dieser Pack prüft gemeinsame Daten-/Autorisierungs-/Ledger-/Syncverträge und die
|
||||
bestehenden selbstisolierten Unixhelper-Dateiguards. Er installiert kein MSI,
|
||||
startet keinen RMM-Dienst, verändert keine Produktjournale oder Identitäten und
|
||||
erzeugt keine Jobs oder Genehmigungen. Insbesondere ist er kein tatsächlicher
|
||||
SYSTEM-, Clock-, Cache-, Download-, Installer- oder WebUI-Wirkungsnachweis.
|
||||
|
||||
## Exakte Listen und Quellen
|
||||
|
||||
Die zunächst tatsächlich lokal aus den Release-Testprogrammen ermittelten
|
||||
Linuxlisten enthalten Domain20, Corecontracts8, Helpersync26, Agentsync26 und
|
||||
Unixhelper21: insgesamt101 Fälle. Der zusätzliche MSI-Corevertrag heißt
|
||||
`historical_msi_nonstart_keeps_full_signature_binding_and_never_becomes_root_authority`.
|
||||
Die Windowsliste ist bis zur tatsächlichen nativen Ausgabe ausdrücklich
|
||||
**erwartet**:20+7+26+26=79. Nur der Unix-OpenSSL-Vergleich und die gesamte
|
||||
Unixhelper-Dateiguardsuite entfallen dort. Es gibt keine Mindestzahlen oder
|
||||
Überspringen/Filtern von Fällen zur Erfüllung dieser Zahlen.
|
||||
|
||||
Das Manifest bindet68 Quellen einschließlich vollständiger Domain-/Core-/
|
||||
Unixhelper-/Linuxadapterquellen, Cargo-/Protoinputs, eng benötigter Fixtures,
|
||||
des neuen Runners und seiner Bootstraptransportquellen vor/nach dem Build.
|
||||
Die13 separat geprüften Domain-/Backend-/SQL-Pins sind exakt an den lokalen
|
||||
Qualifikationsbeleg `b7bced0a341ffb88af8b584cbe8355ff1021add541004347f609f6136a684b74`
|
||||
gebunden. Diese Backendpins sind ausschließlich Quellenbindung: der Unitpack
|
||||
führt weder PostgreSQL noch einen Server aus. Webquellen sind kein Compilerinput
|
||||
und gehören zum unabhängigen UI-Nachweis ihres Owners.
|
||||
|
||||
## Tatsächlich lokal ausgeführt
|
||||
|
||||
Linux- und Windows-GNU-Clippy der ausgewählten Pakete mit allen Targets und
|
||||
`-D warnings`, Release-Linken der fünf Linux- und vier Windows-Testprogramme,
|
||||
Prüfung beider Dateiformate und der unveränderten Original-Links waren erfolgreich.
|
||||
Alle fünf tatsächlichen Linux-Lieferdateien wurden mit vollständiger Liste und
|
||||
101 erfolgreichen, ungefilterten Tests im isolierten Offlinecontainer geprüft.
|
||||
Alle Linux-Dateien referenzieren maximal GLIBC2.34. Nur Auslieferungskopien wurden
|
||||
von Debuginformationen befreit; `.linked`-Originale bleiben separat erhalten.
|
||||
|
||||
Python-Syntax und PowerShell-AST sind geprüft. Enge lokale Driverguards verweigern
|
||||
fehlende/doppelte/fremde Listen und übersprungene/gefilterte Resultate. Ein
|
||||
Mocklauf ohne Zielaufruf verlor die Antwort nach dem alleinigen Ausführungsaufruf;
|
||||
der nachfolgende gleichnamige Readback lud keine Artefakte erneut hoch und
|
||||
startete keinen Test erneut. Beide Plattformen verlangen sämtliche tatsächlichen
|
||||
Listen vor irgendeinem Unitfall. Teilbelege bleiben create-only erhalten.
|
||||
|
||||
Geschütztes lokales Buildmanifest:
|
||||
`devstate/windows-msi-contracts/build-484a3761-6c84-426f-968d-25a638e9c6f7/manifest.json`,
|
||||
SHA256 `2d96a07be72f3d71a8097510eb5f647ced6577086a45417c599b772018c29a53`.
|
||||
Die reine lokale Listenerhebung davor sowie Compiler-/Fehlerausgaben bleiben
|
||||
privat erhalten. Es wurden durch diesen Arbeitsschritt keine VM-/SSH-Aufrufe,
|
||||
Upload-, Server-, Dienst-, Registry- oder Installeraktionen ausgeführt.
|
||||
|
||||
## Noch geplante native Abnahme
|
||||
|
||||
Nach unabhängiger Prüfung führt Root zuerst dieselben Lieferdateien auf der
|
||||
tatsächlichen Linux-VM aus. Erst deren erfolgreicher, unveränderlich an dasselbe
|
||||
Manifest gebundener Beleg erlaubt die Windows-Unitphase. Native Ausführung ist
|
||||
ein ausdrücklicher CLI-Schritt mit dem ursprünglichen Main-`--access-root` nur
|
||||
für den vorhandenen gepinnten SSH-Transport. Zugangsdaten und Main-`devstate`
|
||||
werden weder kopiert noch verlinkt; alle neuen lokalen Belege bleiben im Worktree.
|
||||
|
||||
Beide Zielseiten erhalten eigene create-only Bootstrapfälle unter
|
||||
`windows-msi-contracts`. Vor Tests müssen alle fünf beziehungsweise vier
|
||||
nativen Listen exakt stimmen. Antwortverlust erlaubt ausschließlich denselben
|
||||
Fall zu lesen, auch bei fehlenden oder unvollständigen Ergebnissen; kein Retry
|
||||
oder automatisches Resume. Unter Linux laufen die Units zusätzlich in einem
|
||||
neuen Netzwerknamespace mit begrenztem Prozess-/Ausgabebudget; ihre temporären
|
||||
Dateien gehören zum eigenen Bootstrapfall. Windows läuft ehrlich als
|
||||
Bootstrapadministrator, nicht als Produkt-LocalService oder SYSTEM-Executor.
|
||||
|
||||
Auf der tatsächlichen Cloud-Linux-VM anschließend alle101Prüfungen ohne Skips
|
||||
bestanden: Fall `d015f861-e459-4b82-8ce5-460c3e4c570c`, gemeinsames Manifest
|
||||
`2d96a07be72f3d71a8097510eb5f647ced6577086a45417c599b772018c29a53`,
|
||||
Linuxproof-SHA256
|
||||
`09fa24e32cd3f3563e80e91265c6cc7c612321b0fdd1febe7aef3ab6de53cf2a`.
|
||||
Windows79 weiterhin **geplant, nicht nativ ausgeführt**. Der Linux-Unit-PASS
|
||||
ist keine Installation-/Upgrade-/Noop-Abnahme: jede tatsächliche
|
||||
Paketwirkung benötigt weiterhin ihren eigenen unveränderlichen Antrag und die
|
||||
Genehmigung in der WebUI.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Windows-M4: Domain und Backend
|
||||
|
||||
Stand2026-11-14, Spezifikation1.19. Implementierter und unabhängig geprüfter
|
||||
Quellenschnitt im Branch `codex/windows-msi-integration`; **kein Clouddeployment
|
||||
und keine native Paketabnahme**. Die folgenden Teile ergänzen die getrennten
|
||||
[MSI-Providerquellen](windows-msi11-source.md).
|
||||
|
||||
`ensure_package` erhält das optionale, bei Vorhandensein strikt objektförmige
|
||||
`windows_msi_manifest`. Intern Box, auf dem Draht unverändertes flaches
|
||||
Rezeptobjekt; fehlend ausgelassen. Explizites Null, unbekannte Felder und
|
||||
Objektformen der String-Enums werden verweigert. APT und MSI schließen sich aus.
|
||||
Nur `msi`/`rmm-windows-msi-fixture`/`x64`/`machine`/SYSTEM mit exakt gebundener
|
||||
Rezept-ID/-Version und gewünschter Produktversion. Alte Linux-Goldenbytes bleiben
|
||||
erhalten. MSI-Jobrahmen10–120Sekunden und1024–65536Ausgabebytes.
|
||||
|
||||
Eigener unveränderlicher Windows-MSI-Katalog mit Migration0014, FORCE-Tenant-RLS,
|
||||
zusammengesetztem Tenant-/Artifact-ID-/SHA-/Längen-FK und bestehenden interaktiven
|
||||
Katalogrechten. Import/List sind vom APT-Katalog getrennt. Pro MSI-Job/Versuch
|
||||
wird genau eine Artefaktreferenz automatisch aus dem Rezept abgeleitet; freie
|
||||
`artifact_ids` sind hier verboten. Fehlende, zusätzliche oder doppelte Artefakte
|
||||
und abweichende gesamte Rezeptmengen werden bei Planung, Revalidation,
|
||||
Zustellung, Permit und Geräte-mTLS-Download verweigert. Linux-Artefaktpfade
|
||||
behalten ihre bisherigen Verträge.
|
||||
|
||||
SYSTEM-Policyversion2 verlangt die eigene explizite Allowlist von höchstens
|
||||
zwei vollständigen MSI-Rezepthashes, bestehende Geräte-/Principal-/Helperpins,
|
||||
`system:execute` und getrennte Paketcaps. Schema1 bleibt SCM-only und verweigert
|
||||
MSI. Die historische Core-Nichtstartprüfung kennt nur den zusätzlichen exakt
|
||||
validierten MSI-Actiontyp; keine Missing-Row-/Signatur-/Lineageausnahme,
|
||||
Installer- oder Cachewirkung durch Abandon.
|
||||
|
||||
Tatsächlich lokal bestanden:118betroffene Domain-/Core-/Servertests, danach
|
||||
gezielter Test der verschärften vollständigen Rezeptmenge; isolierter realer
|
||||
PostgreSQL-Fall mit Migration/RLS/Tenant-FK/Immutabilität/Planreferenzmutationen
|
||||
und `pending_approval` mit0Jobs/Outbox/Permits. Fehlendes `system:execute`
|
||||
verweigert. Fünf bestehende Serverfälle bleiben ausdrücklich ignoriert.
|
||||
Linux-Clippy einschließlich Agent/privilegiertem Helper und WindowsGNU-
|
||||
System-helper-Alltargets sowie Format-/Diffprüfung bestanden.
|
||||
|
||||
Der erste PG-Lauf belegte einen unnötigen `FOR SHARE`-Lock, der zusätzliche
|
||||
UPDATE-Rechte erfordert hätte. Ausschließlich der Lock wurde entfernt;
|
||||
Unveränderlichkeit/SELECT-/INSERT-Rechte bleiben erhalten. Fehlversuchslog
|
||||
privat unverändert. Der erfolgreiche PG-Fall nutzte ausdrücklich opake
|
||||
Metadaten-Testbytes, kein tatsächlich geprüftes oder installiertes MSI.
|
||||
Lokaler Beleg `devstate/windows-msi-integration/local-qualification.json`,
|
||||
SHA256 `b7bced0a341ffb88af8b584cbe8355ff1021add541004347f609f6136a684b74`,
|
||||
bindet13Quelldateien. Unabhängiger Quellenreview ohne weiteren konkreten Blocker.
|
||||
|
||||
Weiter offen: Windows-Nativevertragsnachweise, tatsächliche WebUI-Abnahme,
|
||||
Windowsdownload und geschützter SYSTEM-Cache, Helper-/Runtimeverdrahtung und
|
||||
jeweils echte WebUI-genehmigte Installation/Upgrade/Noops. Keine Capability,
|
||||
Helperpolicy oder Clock-/Jobkonfiguration auf der VM wurde geöffnet. Die
|
||||
vorherige UI verweigerte SYSTEM-Nicht-SCM-Pläne bis zum folgenden separaten
|
||||
Schnitt. Quellen/Units sind keine Paketfreigabe.
|
||||
|
||||
## Getrennter WebUI-Quellenschnitt
|
||||
|
||||
Feste SYSTEM-MSI-Auswahl und eigener kleiner Katalogbereich implementiert;
|
||||
APT bleibt getrennt. Anzeige enthält Product-/Upgrade-/gegebenenfalls1.1-
|
||||
PackageCode, Version, Artifact/Rezept/Nutzdateihashes, Vorgänger, feste Argumente
|
||||
und No-Reboot-/Budgetvertrag. Sie stammt aus kopierter typisierter Projection
|
||||
hashgeprüfter gespeicherter Planbytes. Alle Preview-Aliase und spätere Änderungen
|
||||
werden vor Anzeige sowie erneut vor Submit/Genehmigung geprüft. Keine neue
|
||||
Genehmigungsabkürzung oder Policy-/Capabilityveröffentlichung.
|
||||
|
||||
Rootreview fand einen echten Codecfehler: die erste UI-Fassung erwartete
|
||||
`apt_manifest:null`, Rust lässt `None` tatsächlich aus. Die ursprünglichen
|
||||
TS-Fixtures spiegelten diesen Fehler. Eng korrigiert: gespeicherte MSI-Actions
|
||||
verlangen das fehlende Feld; nur das Formular akzeptiert fehlend/null, kein
|
||||
APT-Objekt. Zwei echte, vom unveränderten Rust-Domaincodec erzeugte synthetische
|
||||
PlanPayload-Goldens1.0/1.1 werden nun im bestehenden Webtest verifiziert und
|
||||
gerendert. Keine Signer, realen Geräte oder Nativewirkungen in diesen Fixtures.
|
||||
|
||||
Abschließend42Webtests, Typecheck und Build bestanden; fünf Webdateien und
|
||||
sämtliche Webinputs vor/nach gebunden, Rust13 unverändert. Neuer privater Beleg
|
||||
`devstate/windows-msi-ui/wire-fix-955acab2-35af-4507-bb2b-d7cd1fa49347/qualification.json`,
|
||||
SHA256 `f84d4962ab9a6ef64ef0327fcf7c524efb0bd4064d2416f174a9dfffb524a8a1`.
|
||||
Der ursprüngliche `fe02…`-Beleg bleibt historisch und ist ausdrücklich wegen
|
||||
des Codecfehlers abgelöst. Kein Clouddeployment, Browser-Nativlauf, Installer-
|
||||
oder tatsächlicher WebUI-Freigabenachweis durch diese Quelltests.
|
||||
|
||||
## Tatsächlicher Linux-first-Vertragsnachweis
|
||||
|
||||
Auf der tatsächlichen Cloud-Linux-Test-VM bestanden anschließend alle101
|
||||
ungefilterten Prüfungen ohne Skips: Domain20, Corecontracts8, HelperSync26,
|
||||
AgentSync26 und Unixhelper21. Fall `d015f861-e459-4b82-8ce5-460c3e4c570c`,
|
||||
Manifest `2d96a07b…`, Proof `09fa24e3…`. Nur eigene isolierte Unitprogramme,
|
||||
kein RMM-Job, Dienst-/Agentdeployment, Produktjournal-/Schlüsselzugriff oder
|
||||
Cloudserver-/MSI-/WebUI-Nativnachweis. Windows79 sind weiterhin erwartet und
|
||||
noch nicht nativ ausgeführt. [Genauer Runnervertrag](windows-msi-contracts.md).
|
||||
@@ -0,0 +1,123 @@
|
||||
# Getrennter MSI-Runtime-Unitpack
|
||||
|
||||
**Aktueller nativer Stand:** Cloud-Linux10 und anschließend Windows35+7
|
||||
bestanden. Die folgenden ursprünglichen Erwartungen bleiben als Verlauf
|
||||
erhalten; der abschließende Abschnitt enthält Fehler, Harnesskorrektur und
|
||||
die tatsächlichen neuen Belege. Keine Installerwirkung oder Runtimeinstallation.
|
||||
|
||||
`deploy/windows_msi_runtime_acceptance.py` ergänzt ausschließlich die Units der
|
||||
aktuellen Windows-Runtime. Er verändert keine historischen Runner oder
|
||||
Manifeste. Der vorhandene Common-Pack bleibt mit seinen tatsächlichen
|
||||
Linux101-/Windows79-Belegen separat gebunden; dessen gemeinsame Core-/Domain-/
|
||||
Proto-/Cargoquellen sind zur Runtime identisch. Er wird nicht als Runtime-Test
|
||||
umetikettiert.
|
||||
|
||||
## Tatsächliche lokale Qualifikation
|
||||
|
||||
Der eingefrorene Runtime-Quellenbeleg
|
||||
`17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816`
|
||||
bindet82 Compilerinputs und die unabhängig geprüften acht Runtimeänderungen.
|
||||
Seine bestandenen Windows-GNU-Clippy-Läufe sowie seine unveränderten Windows-
|
||||
Library-/Binary-Testdateien und Original-Links werden direkt wiederverwendet.
|
||||
Es findet keine erneute Windows-Kompilierung oder Strip-Operation statt.
|
||||
|
||||
Zusätzlich gebaut und ausgeführt wurden nur die fehlende Linux-Release-
|
||||
Library-Lieferdatei sowie deren Clippyprüfung. Die vollständige tatsächliche
|
||||
Liste enthält10 Fälle: vier Journal-, drei Eventlog-Vertrags- und drei MSI-
|
||||
Klassifikations-/Nachbedingungsfälle. Alle10 Lieferbyte-Tests bestanden ohne
|
||||
Skip, Filter oder Fehler im isolierten lokalen Offlinecontainer. Die Datei
|
||||
benötigt maximal GLIBC2.34; der unveränderte Original-Link ist archiviert.
|
||||
|
||||
Für Windows sind35 Library- und7 Binaryfälle **erwartet**, insgesamt42.
|
||||
Die Namen wurden aus dem vorhandenen nativen23er-Profil und den additiven
|
||||
kompilierten Testfällen vollständig aufgelöst und in den qualifizierten
|
||||
Windowsbytes gefunden. Das ist kein ausgeführtes Windows-`--list` und kein
|
||||
nativer42er-PASS. Die echte vollständige Liste muss vor dem ersten Windows-
|
||||
Unitfall exakt übereinstimmen. Neue Testfälle wurden dafür nicht geschrieben.
|
||||
|
||||
Das neue Manifest bindet85 Inputs: die82 unveränderten Compilerinputs, den
|
||||
neuen Runner und seine zwei Parser-/Bootstrapquellen. Python-Syntax,
|
||||
PowerShell-AST und gezielte lokale Driverguards sind geprüft. Ein reiner
|
||||
Mocklauf mit verlorener Antwort erlaubte nachfolgend nur den gleichen
|
||||
Readbackfall; es erfolgte kein erneuter Upload oder Ausführungsaufruf.
|
||||
|
||||
Geschütztes Buildmanifest:
|
||||
`devstate/windows-msi-runtime-units/build-9458b2f4-3e1b-4931-ae68-f9306993ce12/manifest.json`,
|
||||
SHA256 `620255bcc57de32044cf23331511937565ac3415514f6ce4d953dad7c5286250`.
|
||||
|
||||
## Getrennt geplante native Schritte
|
||||
|
||||
Nach Root-Review wird zuerst ausschließlich die neue Linux-Library auf der
|
||||
Cloud-Test-VM geprüft. Erst deren unveränderlicher gleiches-Manifest-PASS erlaubt
|
||||
den neuen Windows-Unitfall. Beide Windowslisten müssen vor irgendeinem
|
||||
Testfall stimmen. Die Vorgängerbelege Linux101/Windows79 bleiben dabei erhalten.
|
||||
Alle neuen Bootstrapfälle, Listen und Resultate sind create-only; Antwortverlust
|
||||
oder fehlende Teilresultate erlauben ausschließlich gleichnamigen Readback,
|
||||
keinen Retry oder automatisches Resume. Prozess- und Ausgabe-Nachwartezeiten
|
||||
sind begrenzt. Linux verwendet einen eigenen Netzwerknamespace und temporäre
|
||||
Dateien; Windows läuft ehrlich als Bootstrapadministrator.
|
||||
|
||||
Native Ausführung liest den expliziten ursprünglichen Main-`--access-root`
|
||||
ausschließlich für den vorhandenen gepinnten SSH-Transport. Keine Credential-
|
||||
oder Main-`devstate`-Kopien/Symlinks. Neue Belege gehören zum isolierten
|
||||
Runtimeworktree. Produktdienste, Journale, Identitäten, Schlüssel, Capabilities,
|
||||
Clock- und SYSTEM-Policies werden nicht verändert.
|
||||
|
||||
Die unten belegte Linux10-Phase ist inzwischen nativ bestanden; die
|
||||
Windows42-Phase bleibt **geplant, nicht ausgeführt**. Der Pack
|
||||
belegt keine LocalService-/SYSTEM-Ausführung, keinen Cache-/PERSIST-Datei-
|
||||
Parallelzugriff, keinen MSI-Installations-/Upgrade-/Noop-Job und keinen
|
||||
vertrauenswürdigen Windowsclockadapter. Diese Abnahmen bleiben getrennt und
|
||||
unterliegen vor jeder tatsächlichen RMM-Wirkung weiterhin der WebUI-Grenze.
|
||||
|
||||
|
||||
## Tatsächlich auf der Cloud-Linux-VM bestanden
|
||||
|
||||
Root führte nach unabhängigem Driverreview dieselbe Lieferdatei auf der
|
||||
permanenten x86-64-Linux-VM aus. Alle10Tests ohne Skips/Filter bestanden,
|
||||
Fall `050c33bd-026e-4f89-83e5-d84b1d468827`, ManifestSHA256
|
||||
`620255bcc57de32044cf23331511937565ac3415514f6ce4d953dad7c5286250`,
|
||||
LinuxproofSHA256
|
||||
`679ac094e60f6a5f18c2e461d55ef0a447517287c3eb80f2d9a1b9a5a5fe31dd`.
|
||||
Die exakte vollständige native Liste wurde vor irgendeinem Test geprüft;
|
||||
eigenes Bootstrap-Scratchverzeichnis, leere Prozessumgebung und neuer
|
||||
Netzwerknamespace. Keine RMM-Dienste, Produktdaten, PKI oder Paketstände geändert.
|
||||
|
||||
Windows35+7 bleiben **erwartet, noch nicht nativ ausgeführt**. Der befristete
|
||||
Entwicklungszugang war abgelaufen; Serverhälfte separat erneuert, konkrete
|
||||
Konsolenrecovery durch den Benutzer noch offen. Kein Ersatz des Windowsbelegs
|
||||
und keine Paket-/SYSTEM-/Clock-/Jobcapability aus dem Linux-PASS ableiten.
|
||||
|
||||
## Tatsächlicher Windowsfehler und korrigierter neuer Nachweis
|
||||
|
||||
Der erste Windowsfall `25971084-7006-410b-8374-b2f5821b49b9` blieb
|
||||
fehlgeschlagen: Binary7 bestanden, Library34 bestanden und1 fehlgeschlagen.
|
||||
`native_inventory_has_real_windows_sources_and_no_fake_inodes` verweigerte mit
|
||||
`SYSTEM_DRIVE`. Der Runner hatte die Prozessumgebung geleert und dabei die
|
||||
notwendige ursprüngliche Variable `SystemDrive` nicht wieder übergeben.
|
||||
Kein Inventar-Produktcodefehler und kein erfolgreicher ursprünglicher Lauf
|
||||
werden daraus abgeleitet. Alte Resultate und der ursprüngliche Runner833…
|
||||
bleiben erhalten; kein Test wurde entfernt, gefiltert oder ignoriert.
|
||||
|
||||
Nur der Runner wurde korrigiert: Er übernimmt das ursprüngliche `SystemDrive`
|
||||
nach Prüfung auf Laufwerksformat und Übereinstimmung mit `WINDIR`. Alle82
|
||||
Compilerinputs, Original-Links und Windowslieferbytes bleiben unverändert.
|
||||
Neuer RunnerSHA256
|
||||
`4e260bdf06a158360cf4207233e9418d2f775ab67e86ad60d6d62a5e651f5275`,
|
||||
neues Manifest `build-d53016d9-e265-47e1-ad9f-a3c4a3d86169`, SHA256
|
||||
`341866b79f56e820134487db3589f88eacc047713d9a47b89bb88556ad9870bc`.
|
||||
Python- und PowerShellsyntax wurden lokal geprüft.
|
||||
|
||||
Mit diesem neuen Manifest tatsächlich zuerst **Cloud-Linux10 bestanden**,
|
||||
Fall `a8978cd0-7870-42c7-b761-6b8fab1ff91b`, ProofSHA256
|
||||
`7c314685b08600188afcc586057aeaa379d012188e7a1ef12554edc07eb636bb`.
|
||||
Danach **Windows35 Library+7 Binary bestanden**, ohne Skips oder Filter,
|
||||
Fall `b377daad-e16b-44c9-a2ed-fa977fc0694e`, ProofSHA256
|
||||
`9bf7aef448e43659df2fb354c98fabc96192201c3faca708b18be64ec6419438`.
|
||||
Beide vollständigen Windowslisten wurden vor irgendeinem Test exakt geprüft.
|
||||
Der Windowsbeleg bindet den tatsächlichen gleichnamigen Linuxproof.
|
||||
|
||||
Das sind Bootstrap-Vertragsunits. Keine produktive LocalService-/SYSTEM-
|
||||
Jobausführung, MSIinstallation, Cache-/PERSIST-Abnahme, neue Capability oder
|
||||
Clockqualifikation. Die Priorität liegt jetzt auf der separat beauftragten
|
||||
Shell-/PowerShell-Skriptkonsole; weitere Paketwirkungen sind nachgeordnet.
|
||||
@@ -0,0 +1,92 @@
|
||||
# Windows MSI runtime: implementierter, noch nicht nativ abgenommener Schnitt
|
||||
|
||||
Stand 2026-11-14, isolierter Zweig `codex/windows-msi-runtime`, Basis `66c1855`.
|
||||
Dies ist ein Quellen-/Lokalnachweis. Es wurde damit kein Windows-Installer,
|
||||
RMM-Job, Dienstwechsel oder Bootstrap am Ziel ausgeführt. Die nativen
|
||||
Domain-/Backend-Nachweise des vorhergehenden M4-Schritts ersetzen die folgenden
|
||||
noch offenen Runtime-Nachweise nicht.
|
||||
|
||||
## Implementierte Grenze
|
||||
|
||||
Der Network-Agent lädt ausschließlich das im genehmigten Originaljob gebundene
|
||||
MSI-Artefakt über den bestehenden mTLS-Client und den festen Agent-Endpunkt.
|
||||
Es gibt keine Installer-URL, Weiterleitung, Bearer-Abkürzung oder abgeschaltete
|
||||
TLS-Prüfung. Länge und SHA-256 sind auf das Manifest und höchstens 256 KiB
|
||||
begrenzt. Das Staging liegt unter dem festen Agentzustandsverzeichnis.
|
||||
|
||||
Der SYSTEM-Helper nimmt weiterhin nur die originale signierte Request an,
|
||||
keinen Callerpfad und keine Installerbytes. Settings-Schema 1 bleibt SCM-only;
|
||||
Schema 2 kann höchstens zwei genaue Recipe-SHA-256 freigeben. Fehlende neue
|
||||
Settings-Felder werden beim Serialisieren ausgelassen; vorhandenes `null` ist
|
||||
kein erlaubter Recipe-Allowlistwert. Die lokale Allowlist begrenzt ausschließlich
|
||||
und ersetzt weder Plan, Startgrant, Clock noch signierten Sync.
|
||||
|
||||
Vor einer SYSTEM-Cachekopie persistiert der Helper den atomaren Originalstart
|
||||
mit Verbrauch. Die Kopie verwendet den manifestabgeleiteten SHA-Pfad, prüft
|
||||
Nicht-Reparse, Elternhandles, File-ID, Länge, Hash und die SYS/Admin-Cachegrenze.
|
||||
Neue Cacheeinträge werden ohne Ersetzen bestehender Dateien veröffentlicht.
|
||||
Cache/Staging müssen vorher eingerichtet sein; der Runtimecode repariert weder
|
||||
ACLs noch Verzeichnisse. Der Provider hält eigene Archiv-/Prozesshandles.
|
||||
|
||||
Ein originales monotones Laufzeitbudget umfasst SYSTEM-Cacheaufbereitung,
|
||||
MSI-Metadaten, unabhängige Bestandsprüfung, Noopentscheidung und Installerlauf.
|
||||
Die festen Argumente und MSI-Tabellenprüfungen bleiben erhalten. Erfolg benötigt
|
||||
unabhängige Product-/Family-/PackageCode-/Payload-Nachbedingungen; `3010` bleibt
|
||||
als Rebootbedarf sichtbar, `1641` unklar, `1618` ein fehlgeschlagener eigener
|
||||
Start. Noop hat keinen Installerexitcode. Weder automatischer Reboot noch
|
||||
allgemeines `msiexec`-Kill oder automatischer Wiederholungsstart sind enthalten.
|
||||
|
||||
Die vorhandene Intentzeile besitzt zusätzlich eine dauerhafte, ausschließlich
|
||||
verweigernde Abbruchmarkierung. Sie ist nur von 0 nach 1 änderbar; Originalbytes,
|
||||
Grant und `may_have_dispatched` werden dabei nicht zurückgesetzt. Eine eng
|
||||
geprüfte additive Migration akzeptiert nur die bisherige genaue Tabellen- und
|
||||
Triggerdefinition. Der Helper liest die vollständige Originalbindung über eine
|
||||
jeweils frische gewöhnliche Read-only-Verbindung vor Noop/Start und während der
|
||||
Beobachtung. Fehlende, fehlerhafte oder gesperrte Beobachtung verweigert. Dies ist
|
||||
keine zusätzliche Ausführungsautorität. Zwischen letzter Prüfung und OS-Start
|
||||
bleibt das übliche kleine Rennen; es gibt kein behauptetes Rückgängigmachen.
|
||||
|
||||
Nach unklarem Timeout oder Beobachtungsfehler hält der Helper den eigenen Child,
|
||||
Archivhandles und Originalgrant-/Requestbindung in einem ungeklärten Slot.
|
||||
Weitere MSI-Starts werden bis zur Beobachtung desselben Prozessendes verweigert.
|
||||
Ein späterer Exit ändert das bereits persistierte `unknown` nicht. Nach einem
|
||||
Helperabsturz bleibt die ursprüngliche Ledger-Sperre bestehen. Intent, Abandon,
|
||||
RawMirror und signierter Core-Sync behalten ihre strengen Originalbindungen;
|
||||
keine Missing-row-Regel wurde gelockert.
|
||||
|
||||
## Tatsächlich lokale Prüfung
|
||||
|
||||
Der private Fall `qualified-ee6681c7-8d9d-4af9-8947-5325e1ea2e0f` unter
|
||||
`devstate/windows-msi-runtime/` bindet 82 Compiler-/Manifestquellen vor und nach
|
||||
allen qualifizierten Prüfungen identisch. Qualification-SHA-256:
|
||||
`17f3eb2258773a22be26afd9681d271f69136cfb52dbda31aac2a0ef577b3816`.
|
||||
|
||||
- Linux-Container: 10 Bibliothekstests ausgeführt, 10 bestanden, 0 ignoriert.
|
||||
- Windows-GNU: Default- und SYSTEM-Feature-Alltargets-Clippy mit `-D warnings`
|
||||
bestanden.
|
||||
- Windows-GNU: Lib-/Agent-Bin-Unittests gelinkt, nicht ausgeführt.
|
||||
- Windows-GNU: beide Releasebinaries gelinkt; AMD64-PE geprüft. Originale und
|
||||
mit `--strip-all` bearbeitete Auslieferungsdateien sind getrennt erhalten.
|
||||
- `git diff --check` bestanden. Keine Domain-/Core-/Server-/Web- oder
|
||||
Root-Cargo-/Lockänderung.
|
||||
|
||||
Release-Auslieferung Agent:
|
||||
`7d9b1221ccb3587437d0866296472330947a16445c4e40069981fc4197242d83`.
|
||||
Release-Auslieferung Helper:
|
||||
`96589d53d366a0ccbd60c301fd3d1f03cd4d9f93d85bdcb3ce9b7f4647afc273`.
|
||||
Die Zwischenbelege vor der ergänzten laufenden Abbruchbeobachtung bleiben
|
||||
historisch erhalten und sind nicht die finale Qualification.
|
||||
|
||||
## Noch offen
|
||||
|
||||
Die Windows-Unitbinaries sind inzwischen nativ35+7 bestanden; der ursprüngliche
|
||||
Harnessfehler und der neue Cloud-Linux10→Windows42-Beleg stehen in
|
||||
[windows-msi-runtime-units.md](windows-msi-runtime-units.md).
|
||||
Cache-/Staging-ACLs und gehaltene Handles, tatsächliche
|
||||
PERSIST-Migration mit konkurrierender Deny-Lesung, Installer 1.0, MajorUpgrade
|
||||
1.1, beide Noops und die Abbruch-/Unklarheitsfälle müssen auf der Windows-VM
|
||||
nachgewiesen werden. Installerjobs benötigen jeweils die reale WebUI-Grenze.
|
||||
Capabilityliste bleibt passiv, Clock-Gate unqualifiziert, Job-/Effektdefaults
|
||||
bleiben geschlossen. Diese Implementierung behauptet weder native MSI-Abnahme
|
||||
noch Windows-MVP-Abschluss. EXE, WinGet, allgemeine Installerargumente oder eine
|
||||
neue Rebootstrecke gehören nicht zu diesem Schnitt.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Eigene MSI-Fixture1.1: Quellenstand
|
||||
|
||||
Stand2026-11-14: drei unexportierte Quellen im isolierten Branch
|
||||
`codex/windows-msi-provider` erweitert und unabhängig geprüft. Keine Änderung
|
||||
an produktiven Cargo-/Action-/Helper-/Serverpfaden und keine Capability oder
|
||||
Paketfreigabe. MSI1.1 wurde noch nicht gebaut, registriert oder installiert.
|
||||
Der tatsächliche alte MSI1.0-Artefaktbeleg bleibt unverändert erhalten.
|
||||
|
||||
Neues festes Rezept `rmm-windows-msi-fixture-upgrade-1.1`, ProductCode
|
||||
`{D42BD387-079B-4BBF-A134-0DA7B7A97011}`, gleicher UpgradeCode wie1.0.
|
||||
Das vollständige Rezept bindet zusätzlich den konkreten neuen PackageCode und
|
||||
genau den bekannten1.0-Vorgänger samt Version/33-Byte-Nutzdateihash. Alte1.0-
|
||||
Rezeptbytes bleiben durch am Ende angefügte, bei None ausgelassene Felder gleich.
|
||||
Kein Fresh1.1, Repair, Downgrade oder beliebiger Vorgänger.
|
||||
|
||||
Provider und Builder verlangen feste Upgrade-Tabelle, LaunchCondition und
|
||||
Ausführungssequenz, keine CustomActions. Vorheriger Machine-Produktzustand,
|
||||
Familie und Nutzdatei müssen passen. Nachher1.1 exakt installiert und1.0 entfernt;
|
||||
ein eigener Noop verlangt denselben konkreten1.1-PackageCode. Ein anderes neu
|
||||
gebautes1.1-MSI erhält keine implizite Neuinstallationserlaubnis.
|
||||
|
||||
Zwei Quellenfehler wurden korrigiert: spät beobachteter Installerexit oder
|
||||
Nachzustand wird nicht rückwirkend erfolgreich; zusätzlich beginnt das eine
|
||||
Verifikations-/Installationsbudget vor allen synchronen Prüfungen und umfasst
|
||||
auch Noop samt frischem Fence und erneuter Abbruchprüfung. Timeout bleibt
|
||||
Unknown, kein globales Installerkillen oder Retry. `Run::Noop` kann dadurch
|
||||
auch eine Unknown-Observation enthalten; spätere Aufrufer müssen deren State
|
||||
auswerten und dürfen die Enumvariante nicht pauschal als Erfolg behandeln.
|
||||
|
||||
Tatsächlich lokal bestanden: fünf gezielte Harness-Tests ohne Skips,
|
||||
Linux-/WindowsGNU-Harness-Clippy mit Warnungen als Fehler und PowerShell-AST.
|
||||
Der Harness bindet explizit diesen Worktree und exportiert keine Produktmodule.
|
||||
Originaler Quellenbeleg `devstate/windows-package-msi11/local-source-qualification.json`
|
||||
(`0b562dc2…`) bleibt historisch; enger Folgebeleg
|
||||
`noop-deadline-qualification.json` (`23ed1175…`) bindet den korrigierten Stand.
|
||||
Finale Packagequelle `617b2a73…`, Domain `070a8dfa…`, Builder `6365ac16…`.
|
||||
Im Builder wurde anschließend nur ein überflüssiges Leerzeichen entfernt:
|
||||
PowerShell-Parse erfolgreich und vollständige Tokenliste vorher/nachher
|
||||
identisch; vorheriger Builderquellenbeleg `2d63eaba…` bleibt historisch.
|
||||
|
||||
Offen sind Linux-first-Vertragsintegration, Tenantkatalog, geschützter
|
||||
Artefakttransport/Cache, typisierte SYSTEM-Paketerlaubnis und tatsächliche
|
||||
WebUI-genehmigte Installation/Upgrade/Noops auf der Windows-VM. Lokale Tests
|
||||
und Crossbuilds sind keine native Installerabnahme.
|
||||
@@ -1,10 +1,11 @@
|
||||
# Windows PowerShell5.1: feste prozessbezogene RemoteSigned-Option
|
||||
|
||||
Stand2026-11-14, Spezifikation1.18. **Userentscheidung dokumentiert,
|
||||
Implementierungsentwurf noch nicht umgesetzt und nicht nativ abgenommen.**
|
||||
Diese Arbeit liest Produktquellen und ändert ausschließlich Dokumentation.
|
||||
Laufende Rust-/Artefaktbindungen bleiben unverändert. Keine VM-/Server-/Gitaktion
|
||||
oder Capability-/Clock-/Jobkonfigurationsänderung gehört zu diesem Schritt.
|
||||
Stand2026-11-14, Spezifikation1.18. **Userentscheidung als Sourcekandidat im
|
||||
isolierten Profilbranch umgesetzt und nativ Linux-first vertraglich geprüft.**
|
||||
Die23 Domain-/Coreverträge bestanden auf der Cloud-Linux-VM; Windows22 und die
|
||||
tatsächliche genehmigte PowerShellwirkung bleiben offen. Keine Capability-,
|
||||
Clock- oder Jobkonfiguration aktiviert, kein Deployment. Hauptcheckout und
|
||||
laufende Windowsartefakte bleiben unverändert. [Tatsächlicher Nachweis](windows-profile-acceptance.md).
|
||||
|
||||
## Autorisierter Umfang
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
# Native Prüfung des optionalen Windows-Prozessprofils
|
||||
|
||||
Stand2026-11-14: implementierter und unabhängig geprüfter Profilvertrag im
|
||||
isolierten Branch `codex/windows-powershell-profile`. Domain-/Server-/Original-
|
||||
Grantprüfungen, isolierter PostgreSQL-Fall, beide Windows-Cross-Clippy-Profile,
|
||||
35Webtests, Typecheck und Webbuild lokal bestanden. Zwei UI-Aliasbefunde und
|
||||
die zunächst akzeptierte Null-/Objekt-Profilform sind eng korrigiert.
|
||||
|
||||
Anschließend bestanden auf der tatsächlichen Cloud-Linux-VM alle23 Vertrags-
|
||||
prüfungen ohne Skips, Fall `f463acc9-ab77-4b70-bcfb-a016f40c9410`.
|
||||
Gemeinsamer Build `005b26fd-8269-40dd-8a35-798fabb024a5`, Manifest-SHA256
|
||||
`26247a3a9c187e8ce315250ab3bb3a8b5c1fe681028b15143fb9f193e4af9c80`,
|
||||
Linuxproof-SHA256 `7ecabd9a3ca8fac20aaa7a185b6e128735ea77f143988f058829ae642ad32d25`.
|
||||
Danach bestanden alle22 Windows-Vertragstests ohne Skips, Fall
|
||||
`9abd3e0d-d40f-4d6f-adc8-8fdbbefb98e8`, Windowsproof-SHA256
|
||||
`47cee8c9c449a45699641d53c0fca48b89a53a90dd22cfd03a2ab7675c0a348d`.
|
||||
Der Windowsbeleg bindet denselben Build und den vorangegangenen Linuxproof.
|
||||
Kein Deployment oder tatsächlicher PowerShell-Job; neue Profilcapability nicht
|
||||
veröffentlicht. Der Hauptcheckout und seine zuvor qualifizierten Artefakte
|
||||
bleiben für die ausstehende Komponentenwartung unverändert.
|
||||
|
||||
`deploy/windows_profile_acceptance.py` ist ein eigener Bootstrap-Nachweisrunner,
|
||||
kein RMM-Executor. Er verwendet ausschließlich zwei feste Unitprogramme:
|
||||
Domain-Lib16 und Core-Contracts7 auf der Cloud-Linux-VM, danach Domain-Lib16 und
|
||||
Core-Contracts6 auf der Windows-VM. Nur der Unix-OpenSSL-Paritätstest entfällt
|
||||
unter Windows. Es werden keine Dienste, Produktjournale, PKI, Policies,
|
||||
Capabilities oder RMM-Jobs verändert. SQLite-Fixturen entstehen ausschließlich
|
||||
im eigenen temporären Testverzeichnis. Die Windows-Tests laufen als
|
||||
Bootstrapadministrator; sie beweisen keinen LocalService- oder SYSTEM-Job.
|
||||
|
||||
Der lokale Build erhält Original-Linkdateien neben den gestrippten Lieferkopien,
|
||||
prüft beide Clippy-Ziele und führt die tatsächlich lieferbaren Linuxbytes lokal
|
||||
mit `--list` und ungefiltert aus. Alle Workspace-Cargomanifeste, Lock/Toolchain,
|
||||
Domain/Core/Protocol/Proto sowie Runner und Bootstraptransport werden vorher und
|
||||
nachher gehasht. Windows-Testnamen sind bis zur nativen Ausgabe nur erwartet.
|
||||
Der lokale Linuxlauf ersetzt keinen Linux-VM-Nachweis.
|
||||
|
||||
**Aufrufschema; obige Fälle tatsächlich ausgeführt:**
|
||||
|
||||
```sh
|
||||
python3 deploy/windows_profile_acceptance.py build-local
|
||||
python3 deploy/windows_profile_acceptance.py linux --manifest devstate/windows-profile/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
python3 deploy/windows_profile_acceptance.py windows --manifest devstate/windows-profile/build-UUID/manifest.json --access-root /ABSOLUTER/PFAD/ZUM/HAUPTREPO --execute-native-tests
|
||||
```
|
||||
|
||||
`--access-root` dient ausschließlich dem streng geparsten bestehenden
|
||||
SSH-Zugang: Cloud-Linux `116.203.20.85` bzw. der unveränderten gepinnten
|
||||
Windows-Reverse-SSH-Kette über Cloud-Loopback22240. Keine Credentialkopien,
|
||||
Symlinks oder Hostkeyänderung. Alle Artefakte und lokalen Belege bleiben im
|
||||
isolierten Profilworktree. Linux läuft mit geleerter Umgebung und eigener
|
||||
Netzwerknamespace. Beide nativen Phasen prüfen vor dem ersten Teststart sämtliche
|
||||
Testnamen beider Programme. Windows bindet den bereits verifizierten tatsächlichen
|
||||
Linux-Beleg desselben Manifests über dessen SHA256.
|
||||
|
||||
Jeder Fall hat eigene Create-once-Intents und Startbelege. Eine verlorene Antwort
|
||||
erlaubt ausschließlich beispielsweise `readback-linux --manifest … --case UUID
|
||||
--access-root …` bzw. `readback-windows`. Dieser Pfad lädt nichts hoch und startet
|
||||
keinen Prozess erneut. Er kann `remote_case_absent`, `prepared_without_start` oder
|
||||
`started_without_result` als unvollständigen Stand berichten. Ein neuer Fall ist
|
||||
keine automatische Fehlerwiederholung. Originale Readbacks bleiben an das feste
|
||||
Manifest, Intents und Runner-/Remotescripthashes gebunden; spätere Änderungen an
|
||||
Produktquellen erzwingen keine neue native Ausführung und verhindern ihren
|
||||
Readback nicht. Neue Starts benötigen weiterhin die exakt qualifizierten
|
||||
aktuellen Quellen. Vollständige Ausgaben/Transportfehler bleiben privat,
|
||||
Standardausgabe enthält nur Status, Fallkennung und Nachweishashes.
|
||||
@@ -0,0 +1,27 @@
|
||||
-- Additive immutable tenant catalog; existing APT recipes/artifact semantics stay.
|
||||
ALTER TABLE artifacts ADD CONSTRAINT artifacts_tenant_identity_digest
|
||||
UNIQUE (tenant_id,artifact_id,sha256,size_bytes);
|
||||
CREATE TABLE windows_msi_recipes (
|
||||
tenant_id uuid NOT NULL REFERENCES tenants,
|
||||
catalog_id uuid NOT NULL,
|
||||
recipe_id text NOT NULL CHECK(recipe_id IN ('rmm-windows-msi-fixture-install-1.0','rmm-windows-msi-fixture-upgrade-1.1')),
|
||||
recipe_version text NOT NULL CHECK(recipe_version='1'),
|
||||
recipe_sha256 text NOT NULL CHECK(recipe_sha256 ~ '^[0-9a-f]{64}$'),
|
||||
artifact_id uuid NOT NULL,
|
||||
artifact_sha256 text NOT NULL CHECK(artifact_sha256 ~ '^[0-9a-f]{64}$'),
|
||||
artifact_bytes bigint NOT NULL CHECK(artifact_bytes BETWEEN 1 AND 262144),
|
||||
payload bytea NOT NULL CHECK(octet_length(payload) BETWEEN 1 AND 65536),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY(tenant_id,catalog_id),
|
||||
UNIQUE(tenant_id,recipe_id,recipe_version), UNIQUE(tenant_id,recipe_sha256),
|
||||
FOREIGN KEY(tenant_id,artifact_id,artifact_sha256,artifact_bytes)
|
||||
REFERENCES artifacts(tenant_id,artifact_id,sha256,size_bytes)
|
||||
);
|
||||
ALTER TABLE windows_msi_recipes ENABLE ROW LEVEL SECURITY;
|
||||
ALTER TABLE windows_msi_recipes FORCE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_scope ON windows_msi_recipes
|
||||
USING (tenant_id::text=current_setting('app.tenant_id',true))
|
||||
WITH CHECK (tenant_id::text=current_setting('app.tenant_id',true));
|
||||
GRANT SELECT, INSERT ON windows_msi_recipes TO rmm_app;
|
||||
CREATE TRIGGER immutable_content BEFORE UPDATE OR DELETE ON windows_msi_recipes
|
||||
FOR EACH ROW EXECUTE FUNCTION immutable_plan();
|
||||
@@ -65,6 +65,24 @@ describe('JSON contract boundary', () => {
|
||||
expect(() => validateInput({ ...input, parameters: { ...input.parameters, execution_identity: 'root' } })).toThrow('agent_service');
|
||||
validateInput({ ...input, parameters: { ...input.parameters, variants: [{ ...windows, script_utf8: "\ufeffWrite-Output 'é'\r\n" }] } });
|
||||
});
|
||||
it('bounds the fixed Event Log source and exact 24h interval without rewriting Linux queries', () => {
|
||||
const base: PlanInput = { tenant_id: 't', action: 'query_logs', targets: { asset_ids: ['a'] }, parameters: { execution_identity: 'agent_service', unit: 'windows.eventlog.application.rustdiscovery-mvp-test', since: '2026-11-14T00:00:00Z', until: '2026-11-15T00:00:00Z', max_lines: 1000, timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now()+60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed fixture logs' };
|
||||
const before = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(before);
|
||||
for (const change of [{ execution_identity: 'root' }, { execution_identity: 'system' }, { unit: 'windows.eventlog.security.other' }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { max_lines: 1001 }, { until: '2026-11-15T00:00:00.000000001Z' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, ...change } })).toThrow();
|
||||
const linux = { ...base, parameters: { ...base.parameters, unit: 'rmm-test.service', execution_identity: 'root', timeout_seconds: 1, max_output_bytes: 512 } }; const original=JSON.stringify(linux); validateInput(linux); expect(JSON.stringify(linux)).toBe(original);
|
||||
expect(() => validateInput({ ...linux, parameters: { ...linux.parameters, until: '2026-11-15T00:59:00Z' } })).toThrow('24Stunden');
|
||||
});
|
||||
it('accepts only the fixed Windows process profile without changing inherited variants', () => {
|
||||
const windows = { os_family: 'windows', interpreter: 'powershell', encoding: 'utf-8', script_utf8: "Write-Output 'fixed'\r\n" };
|
||||
const base: PlanInput = { tenant_id: 't', action: 'run_script', targets: { asset_ids: ['a'] }, parameters: { variants: [windows], execution_identity: 'agent_service', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed profile fixture' };
|
||||
const original = JSON.stringify(base); validateInput(base); expect(JSON.stringify(base)).toBe(original);
|
||||
const profiled = { ...windows, windows_execution_profile: 'powershell_51_remote_signed' };
|
||||
validateInput({ ...base, parameters: { ...base.parameters, variants: [profiled] } });
|
||||
expect(() => validateInput({ ...base, parameters: { ...base.parameters, windows_execution_profile: 'powershell_51_remote_signed' } })).toThrow('Skriptvariante');
|
||||
for (const windows_execution_profile of ['Bypass', 'Unrestricted', 'RemoteSigned', 'inherited', null, {}]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [{ ...windows, windows_execution_profile }] } })).toThrow('Windows-Ausführungsprofil');
|
||||
for (const variant of [{ ...profiled, os_family: 'linux' }, { ...profiled, interpreter: 'bash' }, { ...profiled, interpreter: 'pwsh' }]) expect(() => validateInput({ ...base, parameters: { ...base.parameters, variants: [variant] } })).toThrow();
|
||||
for (const execution_identity of ['root', 'system']) expect(() => validateInput({ ...base, parameters: { ...base.parameters, execution_identity, variants: [profiled] } })).toThrow('agent_service');
|
||||
});
|
||||
it('allows SYSTEM only for exact bounded fixture SCM parameters without changing Linux restart', () => {
|
||||
const input: PlanInput = { tenant_id: 't', action: 'set_service_state', targets: { asset_ids: ['asset'] }, parameters: { execution_identity: 'system', unit: 'RmmDiscoveryFixtureService', state: 'running', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed SCM plan' };
|
||||
const before = JSON.stringify(input); validateInput(input); expect(JSON.stringify(input)).toBe(before);
|
||||
|
||||
+104
-4
@@ -59,7 +59,96 @@ export const pretty = (v: unknown) => JSON.stringify(v, null, 2);
|
||||
|
||||
export const actions = ['run_script', 'refresh_inventory', 'query_logs', 'set_service_state', 'ensure_package', 'apply_updates', 'reboot', 'apt_native_acceptance'] as const;
|
||||
export type Action = typeof actions[number];
|
||||
export const windowsPowerShellRemoteSignedProfile = 'powershell_51_remote_signed' as const;
|
||||
/** A missing field is inherited policy; a present field is never silently coerced. */
|
||||
export function windowsScriptProfile(value: RecordValue): 'inherited' | typeof windowsPowerShellRemoteSignedProfile {
|
||||
if (!Object.prototype.hasOwnProperty.call(value, 'windows_execution_profile')) return 'inherited';
|
||||
if (value.windows_execution_profile !== windowsPowerShellRemoteSignedProfile || value.interpreter !== 'powershell'
|
||||
|| (value.os_family !== undefined && value.os_family !== 'windows')) throw new Error('Windows-Ausführungsprofil nur powershell_51_remote_signed für Windows PowerShell5.1');
|
||||
return windowsPowerShellRemoteSignedProfile;
|
||||
}
|
||||
export const windowsEventLogFixtureSource = 'windows.eventlog.application.rustdiscovery-mvp-test';
|
||||
export const windowsEventLogFixtureChannel = 'Application';
|
||||
export const windowsEventLogFixtureProvider = 'RustDiscovery-MVP-Test';
|
||||
/** Preserve sub-millisecond bounds; Date.parse alone would admit 24h + 1ns. */
|
||||
export function logWindow(since: unknown, until: unknown): void {
|
||||
const instant = (value: unknown): bigint => {
|
||||
if (typeof value !== 'string') throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
const match = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d)(?:\.(\d{1,9}))?(Z|[+-]\d\d:\d\d)$/.exec(value);
|
||||
if (!match) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
const seconds = Date.parse(match[1]! + match[3]!);
|
||||
if (!Number.isFinite(seconds)) throw new Error('Exaktes UTC-Log-Zeitfenster erforderlich');
|
||||
return BigInt(seconds) * 1000000n + BigInt((match[2] ?? '').padEnd(9, '0'));
|
||||
};
|
||||
const start = instant(since), end = instant(until);
|
||||
if (end <= start || end - start > 86400000000000n) throw new Error('Exaktes Log-Zeitfenster höchstens24Stunden erforderlich');
|
||||
}
|
||||
export function validateWindowsLogLimits(identity: unknown, runtime: unknown, output: unknown, since: unknown): void {
|
||||
if (identity !== 'agent_service' || typeof runtime !== 'number' || !Number.isSafeInteger(runtime) || runtime < 10 || runtime > 120
|
||||
|| typeof output !== 'number' || !Number.isSafeInteger(output) || output < 1024 || output > 65536
|
||||
|| typeof since !== 'string' || Date.parse(since) < 0) throw new Error('Windows-Fixture-Eventlog nur agent_service,10–120s und1024–65536Bytes');
|
||||
}
|
||||
export interface PlanInput { tenant_id: string; action: Action; targets: { asset_ids: string[] }; parameters: RecordValue; artifact_ids?: string[]; schedule: { not_before: string; start_before: string; offline_policy: 'wait_until_deadline' }; rollout: { max_parallel: number; halt_after_failures: number }; reason: string }
|
||||
export const windowsMsi = {
|
||||
package: 'rmm-windows-msi-fixture', installRecipe: 'rmm-windows-msi-fixture-install-1.0', upgradeRecipe: 'rmm-windows-msi-fixture-upgrade-1.1',
|
||||
product: '{3F070B4B-9C08-4D65-BD41-13D81B884AEC}', upgradedProduct: '{D42BD387-079B-4BBF-A134-0DA7B7A97011}', family: '{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}',
|
||||
payload: 'C:\\Program Files\\RustDiscoveryFixtures\\msi-payload.txt', payload10: '0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0', payload11: 'ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49',
|
||||
} as const;
|
||||
export interface MsiPostcondition { product_code: string; product_version: string; payload_path: string; payload_sha256: string; payload_bytes: number }
|
||||
export interface WindowsMsiRecipe {
|
||||
schema_version: 1; recipe_id: string; recipe_version: '1'; platform: 'windows'; upgrade_code: string; architecture: 'x64'; context: 'machine'; command_profile: 'fixture_quiet_no_reboot_v1';
|
||||
artifact: { artifact_id: string; sha256: string; bytes: number }; postcondition: MsiPostcondition; no_reboot: true; package_code?: string; predecessor?: MsiPostcondition;
|
||||
}
|
||||
export interface WindowsMsiManifest { recipe: WindowsMsiRecipe; recipe_sha256: string }
|
||||
function exactMsiFields(value: RecordValue, fields: string[]): void {
|
||||
if (Object.keys(value).some(key => !fields.includes(key)) || fields.some(key => !Object.prototype.hasOwnProperty.call(value, key))) throw new Error('MSI-Schemafelder fehlen oder sind unbekannt');
|
||||
}
|
||||
export function msiDigest(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value)) throw new Error('Exakter MSI-SHA256 erforderlich'); return value; }
|
||||
export function msiUuid(value: unknown): string { if (typeof value !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value) || value === '00000000-0000-0000-0000-000000000000') throw new Error('Exakte MSI-UUID erforderlich'); return value; }
|
||||
function msiInteger(value: unknown, min: number, max: number): number { if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) throw new Error('MSI-Limit außerhalb des festen Budgets'); return value; }
|
||||
/** Reconstruct every nested object in Rust declaration order before hashing.
|
||||
* No unknown properties, null options, enum objects or caller-supplied argv.
|
||||
*/
|
||||
export function windowsMsiManifest(value: unknown): WindowsMsiManifest {
|
||||
const m = record(value, 'windows_msi_manifest'); exactMsiFields(m, ['recipe', 'recipe_sha256']);
|
||||
const r = record(m.recipe, 'MSI-Rezept'), upgrade = r.recipe_id === windowsMsi.upgradeRecipe;
|
||||
exactMsiFields(r, ['schema_version', 'recipe_id', 'recipe_version', 'platform', 'upgrade_code', 'architecture', 'context', 'command_profile', 'artifact', 'postcondition', 'no_reboot', ...(upgrade ? ['package_code', 'predecessor'] : [])]);
|
||||
if (r.schema_version !== 1 || (!upgrade && r.recipe_id !== windowsMsi.installRecipe) || r.recipe_version !== '1' || r.platform !== 'windows' || r.upgrade_code !== windowsMsi.family || r.architecture !== 'x64' || r.context !== 'machine' || r.command_profile !== 'fixture_quiet_no_reboot_v1' || r.no_reboot !== true) throw new Error('Nur feste Windows-Machine/x64-MSI-Rezepte mit No-Reboot-Vertrag');
|
||||
const a = record(r.artifact); exactMsiFields(a, ['artifact_id', 'sha256', 'bytes']);
|
||||
const post = (value: unknown): MsiPostcondition => { const p = record(value); exactMsiFields(p, ['product_code', 'product_version', 'payload_path', 'payload_sha256', 'payload_bytes']);
|
||||
if (p.payload_path !== windowsMsi.payload) throw new Error('Exakter MSI-Nutzdateipfad erforderlich');
|
||||
return { product_code: text(p.product_code, 'ProductCode'), product_version: text(p.product_version, 'Produktversion'), payload_path: p.payload_path, payload_sha256: msiDigest(p.payload_sha256), payload_bytes: msiInteger(p.payload_bytes, 1, 65536) };
|
||||
};
|
||||
const p = post(r.postcondition);
|
||||
if (p.product_code !== (upgrade ? windowsMsi.upgradedProduct : windowsMsi.product) || p.product_version !== (upgrade ? '1.1.0' : '1.0.0')) throw new Error('MSI-Produkt/Version widerspricht festem Rezept');
|
||||
const recipe: WindowsMsiRecipe = { schema_version: 1, recipe_id: r.recipe_id as string, recipe_version: '1', platform: 'windows', upgrade_code: windowsMsi.family, architecture: 'x64', context: 'machine', command_profile: 'fixture_quiet_no_reboot_v1',
|
||||
artifact: { artifact_id: msiUuid(a.artifact_id), sha256: msiDigest(a.sha256), bytes: msiInteger(a.bytes, 1, 262144) }, postcondition: p, no_reboot: true };
|
||||
if (upgrade) {
|
||||
const code = text(r.package_code, 'PackageCode');
|
||||
if (!/^\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$/.test(code) || code === '{00000000-0000-0000-0000-000000000000}' || [windowsMsi.product, windowsMsi.upgradedProduct, windowsMsi.family].some(x => x === code)) throw new Error('Exakter eigener MSI-PackageCode erforderlich');
|
||||
const old = post(r.predecessor);
|
||||
if (p.payload_sha256 !== windowsMsi.payload11 || p.payload_bytes !== 33 || old.product_code !== windowsMsi.product || old.product_version !== '1.0.0' || old.payload_sha256 !== windowsMsi.payload10 || old.payload_bytes !== 33) throw new Error('MSI1.1 benötigt exakt den bekannten1.0-Vorgänger und die feste1.1-Nutzdatei');
|
||||
recipe.package_code = code; recipe.predecessor = old;
|
||||
}
|
||||
return { recipe, recipe_sha256: msiDigest(m.recipe_sha256) };
|
||||
}
|
||||
export function validateWindowsMsiLimits(runtime: unknown, output: unknown): void { msiInteger(runtime, 10, 120); msiInteger(output, 1024, 65536); }
|
||||
/** Stored Action bytes omit apt_manifest=None; WebParameters may accept null. */
|
||||
export function windowsMsiAction(value: RecordValue): RecordValue {
|
||||
exactMsiFields(value, ['action', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest']);
|
||||
const m = windowsMsiManifest(value.windows_msi_manifest);
|
||||
if (value.action !== 'ensure_package' || value.provider !== 'msi' || value.package !== windowsMsi.package || value.version !== m.recipe.postcondition.product_version || value.architecture !== 'x64' || value.recipe_version !== m.recipe.recipe_version || value.installation_context !== 'machine' || value.recipe_id !== m.recipe.recipe_id) throw new Error('Äußere MSI-Felder widersprechen Manifest');
|
||||
return { action: 'ensure_package', provider: 'msi', package: windowsMsi.package, version: value.version, architecture: 'x64', recipe_version: m.recipe.recipe_version, installation_context: 'machine', recipe_id: m.recipe.recipe_id, windows_msi_manifest: m };
|
||||
}
|
||||
export function validateWindowsMsiInput(input: PlanInput): WindowsMsiManifest {
|
||||
const p = input.parameters;
|
||||
exactMsiFields(p, ['execution_identity', 'timeout_seconds', 'max_output_bytes', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'recipe_id', 'windows_msi_manifest', ...(Object.prototype.hasOwnProperty.call(p, 'apt_manifest') ? ['apt_manifest'] : [])]);
|
||||
if (input.action !== 'ensure_package' || p.execution_identity !== 'system' || (input.artifact_ids?.length ?? 0) !== 0) throw new Error('MSI ausschließlich als SYSTEM-ensure_package mit automatisch genau einem Artefakt');
|
||||
validateWindowsMsiLimits(p.timeout_seconds, p.max_output_bytes);
|
||||
if (p.apt_manifest !== undefined && p.apt_manifest !== null) throw new Error('APT-Manifest bei MSI nicht zulässig');
|
||||
windowsMsiAction({ action: input.action, provider: p.provider, package: p.package, version: p.version, architecture: p.architecture, recipe_version: p.recipe_version, installation_context: p.installation_context, recipe_id: p.recipe_id, windows_msi_manifest: p.windows_msi_manifest });
|
||||
return windowsMsiManifest(p.windows_msi_manifest);
|
||||
}
|
||||
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
|
||||
export function expectedStdout(value: string, format: string): string | null {
|
||||
if (value === '') return null;
|
||||
@@ -68,6 +157,7 @@ export function expectedStdout(value: string, format: string): string | null {
|
||||
return output;
|
||||
}
|
||||
export function validateInput(input: PlanInput): void {
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss an der festen Windows-Skriptvariante stehen');
|
||||
if (!input.targets.asset_ids.length || new Set(input.targets.asset_ids).size !== input.targets.asset_ids.length) throw new Error('Feste eindeutige Ziele erforderlich');
|
||||
if (!input.reason.trim()) throw new Error('Begründung erforderlich');
|
||||
const start = Date.parse(input.schedule.not_before), end = Date.parse(input.schedule.start_before);
|
||||
@@ -77,6 +167,7 @@ export function validateInput(input: PlanInput): void {
|
||||
const variants = input.parameters.variants;
|
||||
if (!Array.isArray(variants) || !variants.length || variants.length > 2 || !variants.every(v => {
|
||||
const variant = record(v), script = typeof variant.script_utf8 === 'string' ? variant.script_utf8 : '';
|
||||
windowsScriptProfile(variant);
|
||||
const bytes = new TextEncoder().encode(script).length;
|
||||
const platform = variant.os_family === 'linux' && ['posix_sh', 'bash'].includes(String(variant.interpreter))
|
||||
|| variant.os_family === 'windows' && variant.interpreter === 'powershell';
|
||||
@@ -87,13 +178,22 @@ export function validateInput(input: PlanInput): void {
|
||||
}
|
||||
if (!['agent_service', 'root', 'system'].includes(String(input.parameters.execution_identity))) throw new Error('Explizite Ausführungsidentität erforderlich');
|
||||
if (input.parameters.execution_identity === 'system') {
|
||||
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste; keine SYSTEM-Shell');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter');
|
||||
if (input.action === 'ensure_package') validateWindowsMsiInput(input);
|
||||
else {
|
||||
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte eigene Windows-Fixturedienste oder feste MSI-Rezepte; keine SYSTEM-Shell');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
if (Object.keys(input.parameters).some(k => !['execution_identity', 'unit', 'state', 'timeout_seconds', 'max_output_bytes'].includes(k))) throw new Error('SYSTEM-Dienstauftrag enthält fremde Parameter');
|
||||
}
|
||||
}
|
||||
if (input.parameters.provider === 'msi' || Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest')) validateWindowsMsiInput(input);
|
||||
const required = (key: string) => text(input.parameters[key], `parameters.${key}`);
|
||||
if (input.action === 'refresh_inventory') required('scope');
|
||||
if (input.action === 'query_logs') { required('unit'); const since = Date.parse(required('since')), until = Date.parse(required('until')); if (!Number.isFinite(since) || !Number.isFinite(until) || until <= since) throw new Error('Exaktes Log-Zeitfenster erforderlich'); if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein'); }
|
||||
if (input.action === 'query_logs') {
|
||||
const unit = required('unit'); logWindow(required('since'), required('until'));
|
||||
if (unit.startsWith('windows.eventlog.') && unit !== windowsEventLogFixtureSource) throw new Error('Nur die feste Windows-Fixture-Eventlogquelle ist konfiguriert');
|
||||
if (unit === windowsEventLogFixtureSource) validateWindowsLogLimits(input.parameters.execution_identity, input.parameters.timeout_seconds, input.parameters.max_output_bytes, input.parameters.since);
|
||||
if (typeof input.parameters.max_lines !== 'number' || !Number.isSafeInteger(input.parameters.max_lines) || input.parameters.max_lines < 1 || input.parameters.max_lines > 1000) throw new Error('Loglimit muss 1–1000 sein');
|
||||
}
|
||||
if (input.action === 'set_service_state') { required('unit'); if (!['running', 'stopped', 'restarted'].includes(required('state'))) throw new Error('Ungültiger Dienstzustand'); }
|
||||
if (input.action === 'ensure_package') { for (const key of ['provider', 'recipe_version', 'package', 'version', 'architecture', 'installation_context']) required(key); }
|
||||
if (input.action === 'apply_updates') { required('provider'); if (!Array.isArray(input.parameters.packages) || !input.parameters.packages.length || !input.parameters.packages.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Feste Updatepakete erforderlich'); if (input.parameters.reboot_policy !== 'never') throw new Error('Kein impliziter Reboot; eigenen festen Plan erstellen'); }
|
||||
|
||||
@@ -1,9 +1,39 @@
|
||||
import { expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { sha256, verifyPlanIntegrity } from './safety';
|
||||
|
||||
// Import the actual renderer without mounting the application's network effects.
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
it('shows fixed Event Log source, half-open UTC window and both runtime bounds before approval', async () => {
|
||||
const fetch=vi.fn();vi.stubGlobal('fetch',fetch);vi.stubGlobal('document',{getElementById:()=>({})});
|
||||
try{
|
||||
const {QueryLogsPlanNotice}=await import('./main');
|
||||
const payload={jobs:[{payload:{asset_id:'win-fixture',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-14T01:00:00Z',max_lines:1000}}}]};
|
||||
const raw=new TextEncoder().encode(JSON.stringify(payload)),plan={plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),plan_payload:payload};
|
||||
expect(renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>)).toContain('role="alert"');await verifyPlanIntegrity(plan);
|
||||
const html=renderToStaticMarkup(<QueryLogsPlanNotice plan={plan}/>);for(const expected of ['Application','RustDiscovery-MVP-Test','1000','4096','30s','5000ms','kooperativ','2026-11-14T01:00:00Z)','Keine Bookmark'])expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/);expect(fetch).not.toHaveBeenCalled();
|
||||
}finally{vi.unstubAllGlobals();}
|
||||
});
|
||||
|
||||
it('shows the verified PowerShell process profile before approval without issuing requests', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { PowerShellPlanNotice } = await import('./main');
|
||||
const payload = { jobs: [{ payload: { asset_id: 'fixed-windows', execution_identity: 'agent_service', action: { action: 'run_script', interpreter: 'powershell', script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', windows_execution_profile: 'powershell_51_remote_signed' } } }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(payload)), plan = { plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), plan_payload: payload };
|
||||
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan);
|
||||
const html = renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>);
|
||||
for (const expected of ['fixed-windows', 'Windows PowerShell5.1', 'RemoteSigned', 'nur Jobprozess', 'angeforderte Option']) expect(html).toContain(expected);
|
||||
expect(html).not.toMatch(/<(button|input|form)\b/);
|
||||
plan.plan_payload_bytes[0] = 0;
|
||||
expect(renderToStaticMarkup(<PowerShellPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
|
||||
it('renders hostile log content only as text, without executable nodes, approval controls or requests', async () => {
|
||||
const fetch = vi.fn();
|
||||
vi.stubGlobal('fetch', fetch);
|
||||
@@ -30,13 +60,17 @@ it('shows fixed SYSTEM identity and service state from stored plan bytes without
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { SystemPlanNotice } = await import('./main');
|
||||
const payload = { jobs: [{ payload: { execution_identity: 'system', asset_id: 'fixed-asset', action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'stopped' } } }] };
|
||||
const plan = { plan_payload_bytes: Array.from(new TextEncoder().encode(JSON.stringify(payload))), jobs: [{ payload: { execution_identity: 'root', action: { unit: 'untrusted-view' } } }] };
|
||||
const payload = { jobs: [{ payload: { execution_identity: 'system', asset_id: 'fixed-asset', max_runtime_seconds: 30, max_output_bytes: 4096, action: { action: 'set_service_state', unit: 'RmmDiscoveryFixtureService', state: 'stopped' } } }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(payload));
|
||||
const plan = { plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: [{ payload: { execution_identity: 'root', action: { unit: 'untrusted-view' } } }] };
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan);
|
||||
const html = renderToStaticMarkup(<SystemPlanNotice plan={plan}/>);
|
||||
expect(html).toContain('SYSTEM'); expect(html).toContain('system:execute'); expect(html).toContain('Identität: system');
|
||||
for (const expected of ['fixed-asset', 'RmmDiscoveryFixtureService', 'Zielzustand: stopped', 'Keine SYSTEM-Shell']) expect(html).toContain(expected);
|
||||
expect(html).not.toContain('untrusted-view'); expect(html).not.toMatch(/<(button|input|form|pre)\b/);
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={{ plan_payload_bytes: Array.from(new TextEncoder().encode('{"jobs":[]}')) }}/>)).toBe('');
|
||||
const emptyRaw = new TextEncoder().encode('{"jobs":[]}'), empty = { plan_payload_bytes: Array.from(emptyRaw), plan_hash: await sha256(emptyRaw) }; await verifyPlanIntegrity(empty);
|
||||
expect(renderToStaticMarkup(<SystemPlanNotice plan={empty}/>)).toBe('');
|
||||
for (const plan_payload_bytes of [[255], [123], 'invalid']) {
|
||||
const invalid = renderToStaticMarkup(<SystemPlanNotice plan={{ plan_payload_bytes }}/>);
|
||||
expect(invalid).toContain('role="alert"'); expect(invalid).toContain('nicht lesbar');
|
||||
|
||||
+67
-12
@@ -1,20 +1,48 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput } from './api';
|
||||
import { actions, Action, ApiError, authConfig, approvalBlockers, expectedStdout, objectId, page, Page, PlanInput, pretty, record, RecordValue, request, session, Session, stringField, tenant, tenantPath, validateInput, windowsPowerShellRemoteSignedProfile } from './api';
|
||||
import './style.css';
|
||||
import { AdminControl, Catalog, TenantControls } from './management';
|
||||
import { allowed, availableActions, parseStrictJson, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity } from './safety';
|
||||
import { allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, rootWarning, systemWarning, systemPlanJobs, validateSensitiveInput, verifyPlanIntegrity, queryLogsApprovalBlockers, queryLogsPlanJobs, windowsMsiApprovalBlockers, windowsMsiPlanJobs, verifyWindowsMsiManifest } from './safety';
|
||||
import { Login } from './login';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
export function JsonView({ value, label = 'Vollständige Daten' }: { value: unknown; label?: string }) { return <details open><summary>{label}</summary><pre>{pretty(value)}</pre></details>; }
|
||||
export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
let jobs: RecordValue[];
|
||||
try { jobs = systemPlanJobs(plan); }
|
||||
try { jobs = systemPlanJobs(plan).filter(p => record(p.action).action === 'set_service_state'); }
|
||||
catch { return <aside role="alert" className="error">Gespeicherte Planbytes sind nicht lesbar. Keine verlässliche SYSTEM-Plananzeige; Genehmigungsverifikation muss erfolgreich sein.</aside>; }
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste SYSTEM-Dienstaktionen"><p>{systemWarning}</p><ul>{jobs.map((payload, i) => { const action = record(payload.action); return <li key={i}>Identität: system · Asset: {String(payload.asset_id)} · Dienst: {String(action.unit)} · Zielzustand: {String(action.state)}</li>; })}</ul><p>Diese Definitionen stammen aus den gespeicherten Planbytes; die vollständigen Zielpayloads und Hashes stehen darunter.</p></aside>;
|
||||
}
|
||||
export function WindowsMsiPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = windowsMsiPlanJobs(plan); if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste SYSTEM-MSI-Paketaktionen"><p>{systemWarning}</p><p>Windows · SYSTEM · Machine · x64 · feste MSI-Profile, keine freie Installer-URL/Argumente. Diese Definition stammt ausschließlich aus hashgeprüften gespeicherten Planbytes.</p><ul>{jobs.map((job, i) => <li key={i}>
|
||||
Asset: {job.assetId} · Rezept: {job.recipeId} · Rezept-SHA256: {job.recipeHash}<br/>
|
||||
Artefakt: {job.artifactId} · SHA256: {job.artifactHash} · {job.artifactBytes} Bytes<br/>
|
||||
ProductCode: {job.productCode} · UpgradeCode: {job.upgradeCode} · Version: {job.version} · PackageCode: {job.packageCode ?? 'im historischen1.0-Rezept nicht separat gebunden; vollständiger Artefakthash bleibt fest'}<br/>
|
||||
Nutzdatei: {job.payloadPath} · SHA256: {job.payloadHash} · {job.payloadBytes} Bytes<br/>
|
||||
Vorgänger: {job.predecessor ? `${job.predecessor.product_code} · ${job.predecessor.product_version} · ${job.predecessor.payload_path} · SHA256 ${job.predecessor.payload_sha256} · ${job.predecessor.payload_bytes} Bytes` : 'keine Upgrade-Reparatur; erste1.0-Installation oder separat belegter Noop'}<br/>
|
||||
Fester Aufruf: %SystemRoot%\System32\msiexec.exe {job.arguments.map(arg => JSON.stringify(arg)).join(' ')}<br/>
|
||||
No-Reboot: true · ursprüngliches Gesamtbudget: {job.runtimeSeconds}s · Ausgabelimit: {job.outputBytes} Bytes
|
||||
</li>)}</ul><p>Upgrade1.1 setzt den exakten1.0-Vorgänger voraus und entfernt ihn. Erfolg/Noop benötigen unabhängige rechtzeitige Nachbedingungen.3010 meldet Neustartbedarf ohne Neustart;1641/unklare Wirkung bleiben unknown,1618 Konflikt ohne Retry. Planung und Anzeige behaupten keine native Installer-/Clock-/Helperbereitschaft.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">MSI-Plan ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne unveränderte gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
export function PowerShellPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = powerShellPlanJobs(plan);
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste PowerShell-Prozessprofile"><p>Diese Ausführungsoptionen sind an die hashgeprüften gespeicherten Planbytes gebunden.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Windows PowerShell5.1 · agent_service · {job.profile === windowsPowerShellRemoteSignedProfile ? 'RemoteSigned · nur Jobprozess' : 'Geerbte Richtlinie · kein ExecutionPolicy-Prozessparameter'}</li>)}</ul><p>Keine Maschinen-/CurrentUser-/GPO-Änderung durch den Executor. GPO-Vorgaben bleiben wirksam; die angeforderte Option ist kein Nachweis der effektiven Policy.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">PowerShell-Planprofil ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
export function QueryLogsPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
try {
|
||||
const jobs = queryLogsPlanJobs(plan);
|
||||
if (!jobs.length) return null;
|
||||
return <aside className="warning" aria-label="Feste Live-Logfenster"><p>UI-genehmigte Liveabfrage aus hashgeprüften gespeicherten Planbytes; kein passives Inventar, keine automatische Erhebung.</p><ul>{jobs.map((job, i) => <li key={i}>Asset: {job.assetId} · Quelle: {job.source}{job.windows ? <> · Kanal: {job.channel} · Provider: {job.provider} · agent_service</> : ' · Linux-Journal'} · UTC-Fenster: [{job.since}, {job.until}) · maximal {job.maxLines} {job.windows ? 'Events' : 'Zeilen'} · {job.outputBytes} Bytes · äußere Joblaufzeit {job.runtimeSeconds}s{job.windows && ' · inneres Abfragebudget höchstens5000ms, zwischen Win32-Aufrufen kooperativ geprüft'}</li>)}</ul><p>Grenzen, Abbruch, fehlende Rechte und Teilabdeckung bleiben sichtbar. Keine Bookmarkfortschreibung durch diesen Auftrag; die Abfrage behauptet keine vollständige Sammlung aller Systemlogs.</p></aside>;
|
||||
} catch { return <aside role="alert" className="error">Logfenster ist nicht verifiziert oder wurde verändert. Keine Genehmigung ohne gültige gespeicherte Planbytes.</aside>; }
|
||||
}
|
||||
function ErrorBox({ error }: { error: string | null }) { return error ? <div role="alert" className="error">{error}</div> : null; }
|
||||
function useResource<T>(load: (signal: AbortSignal) => Promise<T>, deps: React.DependencyList, poll = false) {
|
||||
const [data, setData] = useState<T | null>(null), [error, setError] = useState<string | null>(null), [revision, setRevision] = useState(0);
|
||||
@@ -50,39 +78,66 @@ function Planner({ tenantId, auth, selected, showPlan }: { tenantId: string; aut
|
||||
return <section><h2>Neuen unveränderlichen Plan vorbereiten</h2><p>Nur fest ausgewählte Asset-IDs. Keine Ausführung durch Planung oder Antrag; jede Aktion einschließlich Live-Inventar benötigt Genehmigung.</p>
|
||||
<form onSubmit={async e => { e.preventDefault(); setBusy(true); setError(null); const f = new FormData(e.currentTarget); try {
|
||||
const common = { execution_identity: String(f.get('identity')), timeout_seconds: Number(f.get('timeout')), max_output_bytes: Number(f.get('output')) };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const params = action === 'run_script' ? { ...common, variants: scriptPlatform === 'mixed' ? parseStrictJson(mixedVariants) : [{ os_family: scriptPlatform, interpreter: String(f.get('interpreter')), encoding: 'utf-8', script_utf8: String(f.get('script')), ...(scriptPlatform === 'windows' ? { windows_execution_profile: windowsPowerShellRemoteSignedProfile } : {}) }], arguments: [], expected_stdout: expectedStdout(String(f.get('expected')), String(f.get('expected_format'))) } : { ...record(parseStrictJson(parameters)), ...common };
|
||||
const input: PlanInput = { tenant_id: tenantId, action, targets: { asset_ids: [...selected] }, parameters: params, schedule: { not_before: new Date(String(f.get('not_before'))).toISOString(), start_before: new Date(String(f.get('expires'))).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: Number(f.get('parallel')), halt_after_failures: Number(f.get('failures')) }, reason: String(f.get('reason')) };
|
||||
const ids = String(f.get('artifact_ids') ?? '').split(/[\s,]+/).filter(Boolean); if (ids.length) { if (ids.length > 16 || new Set(ids).size !== ids.length || ids.some(id => !/^[0-9a-f-]{36}$/i.test(id))) throw new Error('Maximal 16 eindeutige feste Artefakt-UUIDs'); input.artifact_ids = ids; }
|
||||
validateInput(input); await validateSensitiveInput(input, auth); const plan = record(await request(tenantPath(tenantId, '/operation-plans'), { body: input, csrf: auth.csrf_token })); showPlan(objectId(plan, 'plan'));
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>
|
||||
<label>Aktion<select aria-label="Aktion" value={action} onChange={e => { const next = availableActions(auth, actions).find(a => a === e.target.value); if (next) { setAction(next); setParameters(pretty(initialParameters[next])); } }}>{availableActions(auth, actions).map(a => <option key={a} value={a}>{a}</option>)}</select></label>
|
||||
{action === 'query_logs' && <p>Windows-MVP nur Quelle windows.eventlog.application.rustdiscovery-mvp-test, Kanal Application, Provider RustDiscovery-MVP-Test, agent_service. Festes UTC-Fenster höchstens24h,1–1000Events,1024–65536Bytes,äußere Joblaufzeit10–120s; inneres kooperatives Abfragebudget höchstens5000ms. Keine freie Kanal-/XPathauswahl und keine Bookmarkfortschreibung. Linux behält seine feste Journalunit.</p>}
|
||||
{action === 'apt_native_acceptance' && <p className="warning">NUR SIMULIERTE DEV/TEST-NATIVABNAHME. In Vorbereitung; Backend/Helper/Scope müssen diese eigene Aktion unterstützen. Nur rmm-apt-fixture-install-1.0 oder rmm-apt-fixture-update-1.1, Rezeptversion 1, vollständiges Schema-2-Manifest. null/Platzhalter sind nicht konfiguriert, keine Produktionsaktion, keine automatische Ausführung.</p>}
|
||||
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive; keine ExecutionPolicy-Umgehung. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
|
||||
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={action !== 'set_service_state' || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
|
||||
{action === 'run_script' ? <><label>Skriptplattform<select aria-label="Skriptplattform" value={scriptPlatform} onChange={e => setScriptPlatform(e.target.value)}><option value="linux">Linux</option><option value="windows">Windows</option><option value="mixed">Linux und Windows · feste Varianten</option></select></label>{scriptPlatform === 'mixed' ? <label>Exakte Plattformvarianten (JSON)<textarea aria-label="Skriptvarianten" value={mixedVariants} onChange={e => setMixedVariants(e.target.value)} rows={9} spellCheck={false}/></label> : <><label>Interpreter<select name="interpreter" key={scriptPlatform}>{scriptPlatform === 'windows' ? <option value="powershell">powershell · Windows PowerShell 5.1</option> : <><option value="posix_sh">posix_sh · /bin/sh</option><option value="bash">bash · nur mit gemeldeter Capability</option></>}</select></label><label>Exakte UTF-8 Skriptbytes (keine automatische Ergänzung)<textarea name="script" required rows={7} spellCheck={false}/></label></>}<label>Format der stdout-Nachbedingung<select name="expected_format" aria-label="Format der stdout-Nachbedingung"><option value="text">Text · Linux-Default</option><option value="json">JSON-String · explizite CRLF mit \r\n</option></select></label><label>Erwartete stdout-Ausgabe (exakte Rohbytes als UTF-8, optional)<textarea name="expected" rows={2} spellCheck={false}/></label>{scriptPlatform !== 'linux' && <p>PowerShell5.1: -NoLogo -NoProfile -NonInteractive. Einzelne neue Windowspläne binden fest RemoteSigned nur für den Jobprozess. Bei gemischten Varianten ist powershell_51_remote_signed ausdrücklich an der Windowsvariante zu setzen; fehlendes Profil bleibt geerbt. Jede tatsächliche Prozessoption steht vor Genehmigung je Ziel im festen Plan. Nicht-ASCII benötigt ein ausdrücklich enthaltenes UTF-8-BOM vor Hashbildung. Skriptbytes und Ausgabe werden nicht normalisiert. Fehlende Plattform-/Interpreter-/Sync-Capability sperrt den ganzen Plan; kein stiller Zielausschluss.</p>}</> : <label>Typisierte Aktionsparameter (JSON; leere Pflichtwerte ergänzen)<textarea aria-label="Aktionsparameter" value={parameters} onChange={e => setParameters(e.target.value)} rows={9} spellCheck={false}/></label>}
|
||||
<div className="grid"><label>Ausführungsidentität<select aria-label="Ausführungsidentität" name="identity" value={identity} onChange={e => setIdentity(e.target.value)}><option value="agent_service">agent_service</option><option value="root" disabled={!allowed(auth, 'root:execute')}>root · root:execute und unabhängiger Helper erforderlich</option><option value="system" disabled={!['set_service_state', 'ensure_package'].includes(action) || !allowed(auth, 'system:execute')}>system · system:execute und Windows-SYSTEM-Helper erforderlich</option></select></label><label>Laufzeitlimit (s)<input name="timeout" type="number" min="1" max="86400" defaultValue="60" required/></label><label>Ausgabelimit (Bytes)<input name="output" type="number" min="1" max="524288" defaultValue="65536" required/></label><label>Frühester Start (lokale Zeit)<input name="not_before" type="datetime-local" defaultValue={localDate(new Date())} required/></label><label>Startfrist / Ablauf (lokale Zeit)<input name="expires" type="datetime-local" defaultValue={localDate(new Date(Date.now() + 86400000))} required/></label><label>Maximal parallel<input name="parallel" type="number" min="1" defaultValue="1" required/></label><label>Stopp nach Fehlern<input name="failures" type="number" min="1" defaultValue="1" required/></label></div>
|
||||
{identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && <p className="warning">{systemWarning}</p>}
|
||||
{identity === 'system' && action === 'ensure_package' && <p>MSI: provider=msi, package=rmm-windows-msi-fixture, architecture=x64, installation_context=machine, recipe_version=1 und vollständiges windows_msi_manifest aus dem getrennten MSI-Katalog. Genau zwei eigene Rezepte1.0/1.0→1.1;10–120s,1024–65536Bytes. APT-Manifest fehlt/null. Rezept-/Artefakthash und feste Nachbedingungen werden geprüft. Kein zusätzlicher Artefaktvektor.</p>}
|
||||
{['ensure_package', 'apply_updates', 'apt_native_acceptance'].includes(action) && <details open><summary>Unveränderte Parameter-/Manifestpreview: gesamte Closure, alte/neue Versionen, Origins, Archivbytes/Hashes und Bindungen</summary><pre>{parameters}</pre><p>Struktur, exakte Transaktionsbytes und Hash werden vor Planung geprüft. Diese Vorschau behauptet keine native Akzeptanz oder Bereitschaft; keine automatische Ergänzung/Reduzierung der Closure.</p></details>}
|
||||
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" placeholder="UUIDs durch Komma getrennt; keine URL"/></label>
|
||||
<label>Feste importierte Artefakt-IDs (optional, maximal 16)<input name="artifact_ids" disabled={identity === 'system' && action === 'ensure_package'} placeholder="MSI leitet genau eine Referenz aus dem Rezept ab; sonst UUIDs, keine URL"/></label>
|
||||
<label>Begründung<input name="reason" required maxLength={1024}/></label><p>Feste Ziele ({selected.length}): {selected.join(', ') || 'keine ausgewählt'}</p>{action === 'reboot' || action === 'apply_updates' || action === 'ensure_package' ? <p className="warning">Zieländerung: Testumfang separat abstimmen. Keine implizite Reboot-/Updateerlaubnis. Neue Versuche und Folgejobs benötigen neue feste Pläne.</p> : null}<button disabled={busy || !selected.length}>Plan erstellen · noch keine Ausführung</button><ErrorBox error={error}/>
|
||||
</form></section>;
|
||||
}
|
||||
function localDate(date: Date) { return new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 16); }
|
||||
|
||||
function WindowsMsiCatalog({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [source, setSource] = useState('{}'), [cursor, setCursor] = useState<string | null>(null), [revision, setRevision] = useState(0), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [receipt, setReceipt] = useState<unknown>(null);
|
||||
const list = useResource(async signal => {
|
||||
const result = page(await request(tenantPath(tenantId, `/windows-msi-recipes${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`), { signal }));
|
||||
const items: RecordValue[] = [];
|
||||
for (const item of result.items) { const manifest = await verifyWindowsMsiManifest(item.manifest); if (item.sha256 !== manifest.recipe_sha256 || item.recipe_id !== manifest.recipe.recipe_id) throw new Error('MSI-Katalogansicht widerspricht Rezeptbytes'); items.push({ catalog_id: item.catalog_id, recipe_id: manifest.recipe.recipe_id, sha256: manifest.recipe_sha256, manifest }); }
|
||||
return { ...result, items };
|
||||
}, [tenantId, cursor, revision]);
|
||||
return <section><h2>Getrennter unveränderlicher Windows-MSI-Katalog</h2><p>Nur die zwei festen eigenen Machine/x64-Rezepte. Import ist Metadatenpflege mit catalog:write, keine Genehmigung, Installation oder Capabilityfreigabe. Öffentliche MSI-Artefakte werden über den bestehenden Artefaktimport gebunden. Vollständiges geprüftes Manifest für den Parametereditor kopieren.</p><ErrorBox error={list.error}/>
|
||||
{list.data && <><PageStatus data={list.data}/><JsonView value={list.data.items} label="Hashgeprüfte feste MSI-Manifeste"/><button disabled={!cursor} onClick={() => setCursor(null)}>Erste MSI-Rezeptseite</button><button disabled={!list.data.next_cursor} onClick={() => setCursor(list.data?.next_cursor ?? null)}>Nächste MSI-Rezeptseite</button></>}
|
||||
<details><summary>Neues festes MSI-Manifest importieren</summary><form onSubmit={async event => { event.preventDefault(); setBusy(true); setError(null); setReceipt(null); try {
|
||||
if (!allowed(auth, 'catalog:write')) throw new Error('catalog:write unbekannt/nicht erteilt');
|
||||
const manifest = await verifyWindowsMsiManifest(parseStrictJson(source));
|
||||
const result = record(await request(tenantPath(tenantId, '/windows-msi-recipes'), { body: manifest, csrf: auth.csrf_token }));
|
||||
const stored = await verifyWindowsMsiManifest(result.manifest);
|
||||
if (result.sha256 !== manifest.recipe_sha256 || result.recipe_id !== manifest.recipe.recipe_id || JSON.stringify(stored) !== JSON.stringify(manifest)) throw new Error('MSI-Importbeleg widerspricht unveränderlichen Rezeptbytes');
|
||||
setReceipt({ catalog_id: result.catalog_id, manifest: stored }); setRevision(n => n + 1);
|
||||
} catch (error) { setError(errorText(error)); } finally { setBusy(false); } }}><label>Vollständiges MSI-Manifest JSON<textarea rows={10} value={source} onChange={e => setSource(e.target.value)} spellCheck={false}/></label><button disabled={busy || !allowed(auth, 'catalog:write')}>Festes MSI-Manifest importieren · keine Ausführung</button><ErrorBox error={error}/>{receipt !== null && <JsonView value={receipt} label="Verifizierter MSI-Importbeleg"/>}</form></details>
|
||||
</section>;
|
||||
}
|
||||
|
||||
function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id: string; auth: Session; onOperation: (id: string) => void }) {
|
||||
const plan = useResource(async signal => { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}`), { signal })); await verifyPlanIntegrity(result); return result; }, [tenantId, id]);
|
||||
const [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false), [confirmed, setConfirmed] = useState(false), [submitted, setSubmitted] = useState(false), [pending, setPending] = useState(false);
|
||||
const [idempotency] = useState(() => crypto.randomUUID());
|
||||
const blockers = plan.data ? approvalBlockers(plan.data) : ['Plan noch nicht geladen'];
|
||||
const blockers = plan.data ? [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data)] : ['Plan noch nicht geladen'];
|
||||
const recheck = async () => { if (!plan.data) throw new Error('Plan fehlt'); await verifyPlanIntegrity(plan.data); const errors = [...approvalBlockers(plan.data), ...powerShellApprovalBlockers(plan.data), ...queryLogsApprovalBlockers(plan.data), ...windowsMsiApprovalBlockers(plan.data)]; if (errors.length) throw new Error(errors.join('; ')); };
|
||||
return <section><h2>Unveränderlicher Plan / Genehmigungsdetail</h2><ErrorBox error={plan.error}/><ErrorBox error={error}/>{plan.data && <>
|
||||
<p>Plan-ID: {id}</p><p>Exakter gespeicherter Planhash: <code>{stringField(plan.data, 'plan_hash')}</code></p><p>Feste Ziele: {Array.isArray(plan.data.resolved_targets) ? plan.data.resolved_targets.length : 'unknown'}. Die folgenden Zielpreviews sind unveränderliche Plandefinitionen, keine ausführbaren Jobs oder angelegten Versuche. Diese entstehen erst nach Genehmigung.</p>
|
||||
<SystemPlanNotice plan={plan.data}/>
|
||||
<WindowsMsiPlanNotice plan={plan.data}/>
|
||||
<PowerShellPlanNotice plan={plan.data}/>
|
||||
<QueryLogsPlanNotice plan={plan.data}/>
|
||||
<JsonView value={plan.data} label="Alle festen Zielpreviews, exakte Skriptinhalte/Hashes, Parameter, Rechte, Fristen, Rollout und Nachbedingungen"/>
|
||||
<p className="warning">Genehmigung bindet ausschließlich diesen unveränderlichen Plan. Kein pauschaler Retry, keine Wildcard, kein impliziter Reboot. Unbekannte Wirkung wird nicht automatisch wiederholt. Ein Exitcode allein beweist keine fachliche Wirkung.</p>
|
||||
{blockers.length > 0 && <div role="alert" className="error">Nicht genehmigungsfähig: {blockers.join('; ')}</div>}
|
||||
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews und Auswirkungen dieses Plans geprüft.</label>
|
||||
<button disabled={busy || !!plan.error || blockers.length > 0 || submitted} onClick={async () => { setBusy(true); setError(null); try { await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/submit`), { csrf: auth.csrf_token, body: { idempotency_key: idempotency } })); setSubmitted(true); setPending((result.approval_state ?? result.state) === 'pending_approval'); onOperation(objectId(result, 'operation')); } catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>Antrag absenden · pending_approval</button>
|
||||
<label className="check"><input type="checkbox" checked={confirmed} onChange={e => setConfirmed(e.target.checked)}/>Ich habe sämtliche festen Ziele, Aktionen, Bytes/Hashes, Zielpreviews, Ausführungsprofile/Prozessumfänge und Auswirkungen dieses Plans geprüft.</label>
|
||||
<button className="danger" disabled={!confirmed || busy || !!plan.error || blockers.length > 0 || !(pending || plan.data.approval_state === 'pending_approval')} onClick={async () => { setBusy(true); setError(null); try {
|
||||
const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
|
||||
await recheck(); const result = record(await request(tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/authorizations`), { csrf: auth.csrf_token, body: { plan_hash: plan.data?.plan_hash } })); setConfirmed(false); setPending(false); onOperation(objectId(result, 'operation')); plan.reload();
|
||||
} catch (e) { setError(errorText(e)); } finally { setBusy(false); } }}>{auth.principal.simulated ? 'SIMULIERT: Diesen festen Plan ausdrücklich genehmigen' : 'Diesen festen Plan ausdrücklich genehmigen'}</button>
|
||||
<p>Nur für einen bestehenden Antrag pending_approval; Server prüft interaktive Sitzung, Rechte, Tenant, Policy und Frist erneut. Keine automatische Genehmigung.</p>
|
||||
<AdminControl auth={auth} path={tenantPath(tenantId, `/operation-plans/${encodeURIComponent(id)}/revocation`)} permission="plans:revoke" title="Planberechtigung widerrufen" warning="Sperrt neue Starts dieses Plans; laufende Wirkungen folgen sicheren Abbruchregeln, kein Rollback. Ein widerrufener Antrag wird nicht reaktiviert." done={plan.reload}/>
|
||||
@@ -119,7 +174,7 @@ function Workspace({ auth, logout }: { auth: Session; logout: () => void }) {
|
||||
}
|
||||
function TenantWorkspace({ tenantId, auth }: { tenantId: string; auth: Session }) {
|
||||
const [selected, setSelected] = useState<string[]>([]), [planId, setPlan] = useState<string | null>(null), [operationId, setOperation] = useState<string | null>(null);
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
return <><Devices tenantId={tenantId} auth={auth} selected={selected} setSelected={setSelected}/><Planner tenantId={tenantId} auth={auth} selected={selected} showPlan={setPlan}/><Catalog tenantId={tenantId} auth={auth}/><WindowsMsiCatalog tenantId={tenantId} auth={auth}/><TenantControls tenantId={tenantId} auth={auth}/><Operations tenantId={tenantId} open={setOperation}/>{operationId && <OperationDetail key={operationId} tenantId={tenantId} id={operationId} auth={auth} openPlan={setPlan}/ >}{planId && <PlanDetail key={planId} tenantId={tenantId} id={planId} auth={auth} onOperation={setOperation}/>}</>;
|
||||
}
|
||||
function App() {
|
||||
const [auth, setAuth] = useState<Session | null>(null), [loading, setLoading] = useState(true), [error, setError] = useState<string | null>(null);
|
||||
|
||||
+158
-2
@@ -1,10 +1,64 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { actions, PlanInput, Session, request, session } from './api';
|
||||
import { adminIntent, allowed, availableActions, parseStrictJson, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { actions, PlanInput, Session, request, session, windowsMsi, windowsMsiManifest, validateInput } from './api';
|
||||
import { adminIntent, allowed, availableActions, windowsMsiPlanJobs, windowsMsiApprovalBlockers, verifyWindowsMsiManifest, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, queryLogsApprovalBlockers, queryLogsPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
vi.mock('react-dom/client', () => ({ createRoot: () => ({ render: vi.fn() }) }));
|
||||
|
||||
const auth: Session = { principal: { id: 'test', display_name: 'SIMULIERT', simulated: true }, csrf_token: 'csrf', tenants: [], permissions: ['root:execute', 'devices:revoke'] };
|
||||
describe('immutable PowerShell process profile', () => {
|
||||
async function plan(profile: unknown = 'powershell_51_remote_signed', identity = 'agent_service', interpreter = 'powershell') {
|
||||
const action = { action: 'run_script', interpreter, script_utf8: 'Write-Output 1\r\n', arguments: [], expected_stdout: '1\r\n', ...(profile === undefined ? {} : { windows_execution_profile: profile }) };
|
||||
const payload = { asset_id: 'fixed-windows', execution_identity: identity, action }, jobs = [{ asset_id: 'fixed-windows', job_payload_hash: 'a'.repeat(64), payload }];
|
||||
const plan_payload = { jobs }, raw = new TextEncoder().encode(JSON.stringify(plan_payload));
|
||||
return { plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs };
|
||||
}
|
||||
it('requires verified bytes, rejects all profile/view mutations and preserves inherited plans', async () => {
|
||||
const value = await plan(); expect(() => powerShellPlanJobs(value)).toThrow('nicht aus hashgeprüften');
|
||||
await verifyPlanIntegrity(value); expect(powerShellPlanJobs(value)).toEqual([{ assetId: 'fixed-windows', profile: 'powershell_51_remote_signed' }]);
|
||||
expect(powerShellApprovalBlockers(value)).toEqual([]);
|
||||
const changed = structuredClone(value); changed.jobs[0]!.payload.action.windows_execution_profile = 'Bypass';
|
||||
await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
|
||||
const viewOnly = { ...value, jobs: [{ ...value.jobs[0]!, payload: { ...value.jobs[0]!.payload, action: { ...value.jobs[0]!.payload.action, windows_execution_profile: 'Bypass' } } }] };
|
||||
await expect(verifyPlanIntegrity(viewOnly)).rejects.toThrow('widerspricht');
|
||||
const extraAlias = { ...value, resolved_targets: value.jobs, jobs: viewOnly.jobs };
|
||||
await expect(verifyPlanIntegrity(extraAlias)).rejects.toThrow('widerspricht');
|
||||
await expect(verifyPlanIntegrity({ ...value, payloads: viewOnly.jobs })).rejects.toThrow('widerspricht');
|
||||
await expect(verifyPlanIntegrity({ ...value, payload: { jobs: viewOnly.jobs } })).rejects.toThrow('widerspricht');
|
||||
const idsOnly = { ...value, resolved_targets: ['fixed-windows'] }; await verifyPlanIntegrity(idsOnly);
|
||||
for (const alias of ['plan_payload', 'payload']) {
|
||||
const later: Record<string, unknown> = { ...value, [alias]: value.plan_payload };
|
||||
await verifyPlanIntegrity(later); later[alias] = { jobs: viewOnly.jobs };
|
||||
expect(powerShellApprovalBlockers(later).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(later)).toThrow('widerspricht');
|
||||
}
|
||||
await expect(verifyPlanIntegrity({ ...value, plan_payload_bytes: undefined })).rejects.toThrow('gespeicherte Planbytes');
|
||||
for (const profile of ['Bypass', null, {}, 'powershell_7_remote_signed']) await expect(verifyPlanIntegrity(await plan(profile))).rejects.toThrow('Windows-Ausführungsprofil');
|
||||
for (const identity of ['root', 'system']) await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', identity))).rejects.toThrow('agent_service');
|
||||
await expect(verifyPlanIntegrity(await plan('powershell_51_remote_signed', 'agent_service', 'bash'))).rejects.toThrow();
|
||||
const inherited = await plan(undefined); delete inherited.plan_payload.jobs[0]!.payload.action.windows_execution_profile;
|
||||
const raw = new TextEncoder().encode(JSON.stringify(inherited.plan_payload)); inherited.plan_payload_bytes = Array.from(raw); inherited.plan_hash = await sha256(raw);
|
||||
await verifyPlanIntegrity(inherited); expect(powerShellPlanJobs(inherited)[0]?.profile).toBe('inherited');
|
||||
value.plan_payload_bytes[0] = 0; expect(powerShellApprovalBlockers(value).length).toBeGreaterThan(0); expect(() => powerShellPlanJobs(value)).toThrow('verändert');
|
||||
});
|
||||
});
|
||||
describe('immutable live log window', () => {
|
||||
it('binds source/window/limits and every supplied view to stored bytes, preserving Linux and SYSTEM plans', async () => {
|
||||
const payload={asset_id:'windows-a',execution_identity:'agent_service',max_runtime_seconds:30,max_output_bytes:4096,action:{action:'query_logs',unit:'windows.eventlog.application.rustdiscovery-mvp-test',since:'2026-11-14T00:00:00Z',until:'2026-11-15T00:00:00Z',max_lines:1000}};
|
||||
const plan_payload={jobs:[{payload}]},raw=new TextEncoder().encode(JSON.stringify(plan_payload));
|
||||
const plan={plan_payload,plan_payload_bytes:Array.from(raw),plan_hash:await sha256(raw),jobs:plan_payload.jobs,resolved_targets:['windows-a']};
|
||||
expect(()=>queryLogsPlanJobs(plan)).toThrow();await verifyPlanIntegrity(plan);
|
||||
expect(queryLogsApprovalBlockers(plan)).toEqual([]);expect(queryLogsPlanJobs(plan)[0]).toMatchObject({source:payload.action.unit,channel:'Application',provider:'RustDiscovery-MVP-Test',maxLines:1000,outputBytes:4096,runtimeSeconds:30});
|
||||
await expect(verifyPlanIntegrity({...plan,plan_payload_bytes:undefined})).rejects.toThrow('gespeicherte');
|
||||
for(const action of [{...payload.action,max_lines:999},{...payload.action,until:'2026-11-14T23:59:59Z'}]){
|
||||
const bad={...plan,payloads:[{payload:{...payload,action}}]};await expect(verifyPlanIntegrity(bad)).rejects.toThrow('widerspricht');
|
||||
}
|
||||
const changed={...plan,jobs:[{payload:{...payload,max_output_bytes:2048}}]};await expect(verifyPlanIntegrity(changed)).rejects.toThrow('widerspricht');
|
||||
const cached={...plan};await verifyPlanIntegrity(cached);cached.jobs=[{payload:{...payload,max_runtime_seconds:31}}];expect(queryLogsApprovalBlockers(cached).length).toBeGreaterThan(0);
|
||||
for(const execution_identity of ['root','system']){const p={jobs:[{payload:{...payload,execution_identity}}]};const b=new TextEncoder().encode(JSON.stringify(p));await expect(verifyPlanIntegrity({plan_payload_bytes:Array.from(b),plan_hash:await sha256(b)})).rejects.toThrow('agent_service');}
|
||||
const linux={jobs:[{payload:{...payload,execution_identity:'root',action:{...payload.action,unit:'rmm-test.service'}}}]};const linuxBytes=new TextEncoder().encode(JSON.stringify(linux));const linuxPlan={plan_payload_bytes:Array.from(linuxBytes),plan_hash:await sha256(linuxBytes)};await verifyPlanIntegrity(linuxPlan);expect(queryLogsPlanJobs(linuxPlan)[0]?.windows).toBe(false);
|
||||
const system={jobs:[{payload:{...payload,execution_identity:'system',action:{action:'set_service_state',unit:'RmmDiscoveryFixtureService',state:'running'}}}]};const systemBytes=new TextEncoder().encode(JSON.stringify(system));const systemPlan={plan_payload_bytes:Array.from(systemBytes),plan_hash:await sha256(systemBytes)};await verifyPlanIntegrity(systemPlan);expect(queryLogsPlanJobs(systemPlan)).toEqual([]);
|
||||
});
|
||||
});
|
||||
async function manifest(acceptance = true) {
|
||||
const transaction = { schema_version: 1, recipe_id: 'rmm-apt-fixture-install-1.0', 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: '74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867', size: 20672, archive_path: '/var/lib/rmm-apt-transaction/archives/74036ae81223deab3aae994fd2a2a695af408741777e1ce17dcb4e32f1235867.deb' }] };
|
||||
const raw = new TextEncoder().encode(JSON.stringify(transaction));
|
||||
@@ -142,3 +196,105 @@ describe('interactive administrative boundary', () => {
|
||||
expect(fetch).toHaveBeenCalledWith('/api/v1/tenants/t/execution-stop', expect.objectContaining({ credentials: 'same-origin', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': 'csrf' }, body: '{"reason":"test only","stopped":true}' })); vi.unstubAllGlobals();
|
||||
});
|
||||
});
|
||||
|
||||
// Actual rmm_domain::jobs::encode(PlanPayload) output from the private synthetic
|
||||
// offline harness (no signer, real device, database or native execution).
|
||||
const msiDomainGoldens = [
|
||||
"{\"schema_version\":1,\"plan_id\":\"00000000-0000-4000-8000-000000000006\",\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"principal\":\"simulated-unit-only\",\"reason\":\"MSI UI contract, no execution\",\"jobs\":[{\"payload\":{\"schema_version\":1,\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"asset_id\":\"00000000-0000-4000-8000-000000000002\",\"agent_id\":\"00000000-0000-4000-8000-000000000003\",\"enrollment_generation\":1,\"assignment_version\":1,\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"action\":{\"action\":\"ensure_package\",\"provider\":\"msi\",\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.0.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"installation_context\":\"machine\",\"recipe_id\":\"rmm-windows-msi-fixture-install-1.0\",\"windows_msi_manifest\":{\"recipe\":{\"schema_version\":1,\"recipe_id\":\"rmm-windows-msi-fixture-install-1.0\",\"recipe_version\":\"1\",\"platform\":\"windows\",\"upgrade_code\":\"{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}\",\"architecture\":\"x64\",\"context\":\"machine\",\"command_profile\":\"fixture_quiet_no_reboot_v1\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"bytes\":32768},\"postcondition\":{\"product_code\":\"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\",\"product_version\":\"1.0.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0\",\"payload_bytes\":33},\"no_reboot\":true},\"recipe_sha256\":\"47e4a478f0e3b2976ededa6afa6058d6e56ceec4e0e36cc5950701c1e65190f5\"}},\"execution_identity\":\"system\",\"not_before\":\"2027-01-01T00:00:00Z\",\"start_before\":\"2027-01-01T01:00:00Z\",\"max_runtime_seconds\":30,\"max_output_bytes\":4096},\"job_payload_hash\":\"5df5828c52c2be0b005f31551319e5892a6daa80a4d30c76f95153e24eeec9b1\",\"script_sha256\":null}],\"max_parallel\":1,\"halt_after_failures\":1,\"recipe_references\":[{\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.0.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"sha256\":\"47e4a478f0e3b2976ededa6afa6058d6e56ceec4e0e36cc5950701c1e65190f5\"}],\"artifact_references\":[{\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"size_bytes\":32768}}]}",
|
||||
"{\"schema_version\":1,\"plan_id\":\"00000000-0000-4000-8000-000000000006\",\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"principal\":\"simulated-unit-only\",\"reason\":\"MSI UI contract, no execution\",\"jobs\":[{\"payload\":{\"schema_version\":1,\"tenant_id\":\"00000000-0000-4000-8000-000000000001\",\"asset_id\":\"00000000-0000-4000-8000-000000000002\",\"agent_id\":\"00000000-0000-4000-8000-000000000003\",\"enrollment_generation\":1,\"assignment_version\":1,\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"action\":{\"action\":\"ensure_package\",\"provider\":\"msi\",\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.1.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"installation_context\":\"machine\",\"recipe_id\":\"rmm-windows-msi-fixture-upgrade-1.1\",\"windows_msi_manifest\":{\"recipe\":{\"schema_version\":1,\"recipe_id\":\"rmm-windows-msi-fixture-upgrade-1.1\",\"recipe_version\":\"1\",\"platform\":\"windows\",\"upgrade_code\":\"{C9BF1FB8-E31D-4BD7-BA0D-AB46539BBBAA}\",\"architecture\":\"x64\",\"context\":\"machine\",\"command_profile\":\"fixture_quiet_no_reboot_v1\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"bytes\":32768},\"postcondition\":{\"product_code\":\"{D42BD387-079B-4BBF-A134-0DA7B7A97011}\",\"product_version\":\"1.1.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"ba0c83deff9eed014009bcd45369b2a356ae909ebf0c1434dc836b0e6d759c49\",\"payload_bytes\":33},\"no_reboot\":true,\"package_code\":\"{AF1C9887-391A-4BFF-B909-BC898300CF90}\",\"predecessor\":{\"product_code\":\"{3F070B4B-9C08-4D65-BD41-13D81B884AEC}\",\"product_version\":\"1.0.0\",\"payload_path\":\"C:\\\\Program Files\\\\RustDiscoveryFixtures\\\\msi-payload.txt\",\"payload_sha256\":\"0c90c4fc7233017cc88c0e925095d6662ac57abdb303c7527ef59d02b454fca0\",\"payload_bytes\":33}},\"recipe_sha256\":\"376d4a05fa43565a302cd1f90514e355e3f89a634d43abb9c31978e740bf7e9c\"}},\"execution_identity\":\"system\",\"not_before\":\"2027-01-01T00:00:00Z\",\"start_before\":\"2027-01-01T01:00:00Z\",\"max_runtime_seconds\":30,\"max_output_bytes\":4096},\"job_payload_hash\":\"33184fcde0395a48dccb5e0cbb4d48f92f59664c8c964db7489d6686a0002546\",\"script_sha256\":null}],\"max_parallel\":1,\"halt_after_failures\":1,\"recipe_references\":[{\"package\":\"rmm-windows-msi-fixture\",\"version\":\"1.1.0\",\"architecture\":\"x64\",\"recipe_version\":\"1\",\"sha256\":\"376d4a05fa43565a302cd1f90514e355e3f89a634d43abb9c31978e740bf7e9c\"}],\"artifact_references\":[{\"job_id\":\"00000000-0000-4000-8000-000000000004\",\"attempt_id\":\"00000000-0000-4000-8000-000000000005\",\"artifact\":{\"artifact_id\":\"00000000-0000-4000-8000-000000000010\",\"sha256\":\"abababababababababababababababababababababababababababababababab\",\"size_bytes\":32768}}]}"
|
||||
] as const;
|
||||
|
||||
// Mirrors the Rust Recipe/Action/Job declaration order, not a preview alias.
|
||||
async function msiFixture(upgrade = false) {
|
||||
const id = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
|
||||
const old = { product_code: windowsMsi.product, product_version: '1.0.0', payload_path: windowsMsi.payload, payload_sha256: windowsMsi.payload10, payload_bytes: 33 };
|
||||
const recipe = { schema_version: 1, recipe_id: upgrade ? windowsMsi.upgradeRecipe : windowsMsi.installRecipe, recipe_version: '1', platform: 'windows', upgrade_code: windowsMsi.family, architecture: 'x64', context: 'machine', command_profile: 'fixture_quiet_no_reboot_v1', artifact: { artifact_id: id(10), sha256: 'ab'.repeat(32), bytes: 32768 }, postcondition: upgrade ? { ...old, product_code: windowsMsi.upgradedProduct, product_version: '1.1.0', payload_sha256: windowsMsi.payload11 } : old, no_reboot: true, ...(upgrade ? { package_code: '{AF1C9887-391A-4BFF-B909-BC898300CF90}', predecessor: old } : {}) };
|
||||
const manifest = { recipe, recipe_sha256: await sha256(new TextEncoder().encode(JSON.stringify(recipe))) };
|
||||
const action = { action: 'ensure_package', provider: 'msi', package: windowsMsi.package, version: recipe.postcondition.product_version, architecture: 'x64', recipe_version: '1', installation_context: 'machine', recipe_id: recipe.recipe_id, windows_msi_manifest: manifest };
|
||||
const payload = { schema_version: 1, tenant_id: id(1), asset_id: id(2), agent_id: id(3), enrollment_generation: 1, assignment_version: 1, job_id: id(4), attempt_id: id(5), action, execution_identity: 'system', not_before: '2027-01-01T00:00:00Z', start_before: '2027-01-01T01:00:00Z', max_runtime_seconds: 30, max_output_bytes: 4096 };
|
||||
const job = { payload, job_payload_hash: await sha256(new TextEncoder().encode(JSON.stringify(payload))), script_sha256: null };
|
||||
const constructed = { schema_version: 1, plan_id: id(6), tenant_id: id(1), principal: 'simulated-unit-only', reason: 'MSI UI contract, no execution', jobs: [job], max_parallel: 1, halt_after_failures: 1, recipe_references: [{ package: windowsMsi.package, version: action.version, architecture: 'x64', recipe_version: '1', sha256: manifest.recipe_sha256 }], artifact_references: [{ job_id: payload.job_id, attempt_id: payload.attempt_id, artifact: { artifact_id: recipe.artifact.artifact_id, sha256: recipe.artifact.sha256, size_bytes: recipe.artifact.bytes } }] };
|
||||
const golden = msiDomainGoldens[upgrade ? 1 : 0];
|
||||
expect(JSON.stringify(constructed)).toBe(golden); // Independent Rust codec oracle.
|
||||
const plan_payload = parseStrictJson(golden) as typeof constructed;
|
||||
const actualJob = plan_payload.jobs[0]!;
|
||||
const raw = new TextEncoder().encode(golden);
|
||||
const preview = { ...actualJob, job_id: actualJob.payload.job_id, attempt_id: actualJob.payload.attempt_id, asset_id: actualJob.payload.asset_id, agent_id: actualJob.payload.agent_id };
|
||||
const plan = structuredClone({ plan_id: plan_payload.plan_id, plan_payload, payload: plan_payload, plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw), jobs: [preview], payloads: [preview], resolved_targets: [{ asset_id: payload.asset_id, agent_id: payload.agent_id }], expires_at: payload.start_before });
|
||||
return { manifest: actualJob.payload.action.windows_msi_manifest, action: actualJob.payload.action, payload: actualJob.payload, plan_payload, plan };
|
||||
}
|
||||
|
||||
describe('fixed SYSTEM MSI UI contract', () => {
|
||||
it('renders only the verified fixed package definition and never issues an approval or download', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch); vi.stubGlobal('document', { getElementById: () => ({}) });
|
||||
try {
|
||||
const { WindowsMsiPlanNotice } = await import('./main');
|
||||
for (const upgrade of [false, true]) {
|
||||
const { plan } = await msiFixture(upgrade);
|
||||
expect(renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>)).toContain('role="alert"');
|
||||
await verifyPlanIntegrity(plan); const html = renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>);
|
||||
for (const value of ['SYSTEM', 'Machine', 'x64', upgrade ? windowsMsi.upgradeRecipe : windowsMsi.installRecipe, windowsMsi.product, windowsMsi.family, 'Rezept-SHA256', 'Artefakt', 'Vorgänger', 'No-Reboot: true', '30s', '4096', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1', '3010', '1641', '1618']) expect(html).toContain(value);
|
||||
if (upgrade) { expect(html).toContain(windowsMsi.upgradedProduct); expect(html).toContain('AF1C9887'); }
|
||||
else expect(html).toContain('historischen1.0-Rezept nicht separat gebunden');
|
||||
expect(html).not.toMatch(/<(button|input|form|script)\b/); expect(fetch).not.toHaveBeenCalled();
|
||||
plan.jobs[0]!.payload.action.provider = 'foreign-installer';
|
||||
const invalid = renderToStaticMarkup(<WindowsMsiPlanNotice plan={plan}/>); expect(invalid).toContain('role="alert"'); expect(invalid).not.toContain('foreign-installer');
|
||||
}
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
it('checks canonical nested recipe bytes, strict typed inputs and independent SYSTEM rights', async () => {
|
||||
const { manifest, action } = await msiFixture(true);
|
||||
const { action: _action, ...fields } = action;
|
||||
const input: PlanInput = { tenant_id: 't', action: 'ensure_package', targets: { asset_ids: ['a'] }, parameters: { ...fields, execution_identity: 'system', timeout_seconds: 30, max_output_bytes: 4096 }, schedule: { not_before: new Date().toISOString(), start_before: new Date(Date.now() + 60000).toISOString(), offline_policy: 'wait_until_deadline' }, rollout: { max_parallel: 1, halt_after_failures: 1 }, reason: 'fixed MSI' };
|
||||
const original = JSON.stringify(input); validateInput(input); await validateSensitiveInput(input, { ...auth, permissions: ['system:execute'] }); expect(JSON.stringify(input)).toBe(original);
|
||||
const formNull = { ...input, parameters: { ...input.parameters, apt_manifest: null } }; validateInput(formNull); await validateSensitiveInput(formNull, { ...auth, permissions: ['system:execute'] });
|
||||
const reversed = { ...manifest, recipe: Object.fromEntries(Object.entries(manifest.recipe).reverse()) };
|
||||
expect(await verifyWindowsMsiManifest(reversed)).toEqual(windowsMsiManifest(manifest));
|
||||
await expect(verifyWindowsMsiManifest({ ...manifest, recipe_sha256: 'cd'.repeat(32) })).rejects.toThrow('Rezepthash');
|
||||
for (const permissions of [undefined, [], ['root:execute']]) await expect(validateSensitiveInput(input, { ...auth, permissions })).rejects.toThrow('system:execute');
|
||||
for (const change of [{ execution_identity: 'root' }, { provider: 'apt' }, { architecture: 'amd64' }, { installation_context: 'system' }, { version: '2.0' }, { arguments: ['/quiet'] }, { apt_manifest: {} }, { timeout_seconds: 9 }, { timeout_seconds: 121 }, { max_output_bytes: 1023 }, { max_output_bytes: 65537 }, { windows_msi_manifest: null }]) expect(() => validateInput({ ...input, parameters: { ...input.parameters, ...change } })).toThrow();
|
||||
expect(() => validateInput({ ...input, artifact_ids: [manifest.recipe.artifact.artifact_id] })).toThrow('automatisch');
|
||||
for (const change of [{ architecture: { x64: null } }, { context: 'user' }, { command_profile: { fixture_quiet_no_reboot_v1: null } }, { no_reboot: false }, { installer_url: 'https://example.invalid/a.msi' }, { package_code: null }, { predecessor: { ...manifest.recipe.predecessor, product_version: '0.9' } }]) expect(() => windowsMsiManifest({ ...manifest, recipe: { ...manifest.recipe, ...change } })).toThrow();
|
||||
});
|
||||
it('requires the complete per-job recipe/artifact set and immutable full job hash', async () => {
|
||||
for (const upgrade of [false, true]) {
|
||||
const { plan } = await msiFixture(upgrade);
|
||||
expect(() => windowsMsiPlanJobs(plan)).toThrow('nicht aus hashgeprüften');
|
||||
await verifyPlanIntegrity(plan); const job = windowsMsiPlanJobs(plan)[0]!;
|
||||
expect(job.version).toBe(upgrade ? '1.1.0' : '1.0.0'); expect(job.packageCode !== null).toBe(upgrade); expect(job.arguments).toEqual(['/i', `C:\\ProgramData\\RustDiscoverySystem\\cache\\${'ab'.repeat(32)}.msi`, '/qn', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1']);
|
||||
expect(windowsMsiApprovalBlockers(plan)).toEqual([]);
|
||||
for (const mutate of [
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references = []; },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references.push(structuredClone(p.artifact_references[0]!)); },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references[0]!.artifact.size_bytes++; },
|
||||
(p: typeof plan.plan_payload) => { p.artifact_references[0]!.attempt_id = '00000000-0000-4000-8000-000000000099'; },
|
||||
(p: typeof plan.plan_payload) => { p.recipe_references.push(structuredClone(p.recipe_references[0]!)); },
|
||||
(p: typeof plan.plan_payload) => { p.recipe_references = []; },
|
||||
(p: typeof plan.plan_payload) => { p.jobs[0]!.payload.max_output_bytes++; },
|
||||
(p: typeof plan.plan_payload) => { Object.assign(p.jobs[0]!.payload.action, { apt_manifest: null }); },
|
||||
(p: typeof plan.plan_payload) => { Object.assign(p.jobs[0]!.payload.action, { apt_manifest: {} }); },
|
||||
]) {
|
||||
const changed = structuredClone(plan.plan_payload); mutate(changed); const raw = new TextEncoder().encode(JSON.stringify(changed));
|
||||
await expect(verifyPlanIntegrity({ plan_payload_bytes: Array.from(raw), plan_hash: await sha256(raw) })).rejects.toThrow();
|
||||
}
|
||||
}
|
||||
});
|
||||
it('blocks every alias and late mutation without blessing changed bytes or issuing a request', async () => {
|
||||
const fetch = vi.fn(); vi.stubGlobal('fetch', fetch);
|
||||
try {
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets', 'payload', 'plan_payload']) {
|
||||
const { plan } = await msiFixture(true); await verifyPlanIntegrity(plan);
|
||||
const object = plan as Record<string, unknown>;
|
||||
if (alias === 'resolved_targets') plan.resolved_targets[0]!.agent_id = '00000000-0000-4000-8000-000000000099';
|
||||
else if (alias === 'jobs' || alias === 'payloads') { const view = structuredClone(plan.jobs); view[0]!.payload.max_runtime_seconds++; object[alias] = view; }
|
||||
else { const view = structuredClone(plan.plan_payload); view.jobs[0]!.payload.action.windows_msi_manifest.recipe.artifact.bytes++; object[alias] = view; }
|
||||
expect(windowsMsiApprovalBlockers(plan).length).toBeGreaterThan(0); await expect(verifyPlanIntegrity(plan)).rejects.toThrow();
|
||||
}
|
||||
const { plan } = await msiFixture(); await verifyPlanIntegrity(plan);
|
||||
const copy = windowsMsiPlanJobs(plan)[0]!; (copy.arguments as string[]).push('FORGED=1'); expect(windowsMsiPlanJobs(plan)[0]!.arguments).not.toContain('FORGED=1');
|
||||
const changed = structuredClone(plan.plan_payload); changed.reason = 'later'; const raw = new TextEncoder().encode(JSON.stringify(changed)); plan.plan_payload_bytes = Array.from(raw); plan.plan_hash = await sha256(raw);
|
||||
await expect(verifyPlanIntegrity(plan)).rejects.toThrow('verändert');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
} finally { vi.unstubAllGlobals(); }
|
||||
});
|
||||
});
|
||||
|
||||
+257
-10
@@ -1,8 +1,8 @@
|
||||
import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid } from './api';
|
||||
|
||||
export const hashPattern = /^[0-9a-f]{64}$/;
|
||||
export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.';
|
||||
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst und running/stopped. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
|
||||
export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst (running/stopped) oder eigenes festes MSI-Rezept. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.';
|
||||
export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; }
|
||||
export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; }
|
||||
export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); }
|
||||
@@ -75,8 +75,13 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) {
|
||||
if (input.parameters.execution_identity === 'root' && !allowed(auth, 'root:execute')) throw new Error('root:execute unbekannt oder nicht erteilt; keine Rechteerhöhung');
|
||||
if (input.parameters.execution_identity === 'system') {
|
||||
if (!allowed(auth, 'system:execute')) throw new Error('system:execute unbekannt oder nicht erteilt; root:execute enthält dieses Recht nicht');
|
||||
if (input.action !== 'set_service_state') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen');
|
||||
validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
if (input.action !== 'set_service_state' && input.action !== 'ensure_package') throw new Error('SYSTEM ausschließlich für typisierte Dienstaktionen oder feste MSI-Rezepte');
|
||||
if (input.action === 'set_service_state') validateSystemService(input.parameters.unit, input.parameters.state, input.parameters.timeout_seconds, input.parameters.max_output_bytes);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(input.parameters, 'windows_msi_manifest') || (input.action === 'ensure_package' && input.parameters.execution_identity === 'system')) {
|
||||
const original = canonical(input), m = validateWindowsMsiInput(input); await verifyWindowsMsiManifest(m);
|
||||
if (canonical(input) !== original) throw new Error('MSI-Antrag wurde während der Hashprüfung verändert');
|
||||
return;
|
||||
}
|
||||
if (input.action === 'apt_native_acceptance') {
|
||||
if (!auth.principal.simulated || input.parameters.execution_identity !== 'root') throw new Error('APT-Abnahme ausschließlich explizit simuliert und root');
|
||||
@@ -96,12 +101,231 @@ export async function validateSensitiveInput(input: PlanInput, auth: Session) {
|
||||
}
|
||||
/** Display only definitions decoded from the exact hashed plan bytes. */
|
||||
export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
if (plan.plan_payload_bytes === undefined) return [];
|
||||
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(bytes(plan.plan_payload_bytes))));
|
||||
if (!Array.isArray(parsed.jobs)) return [];
|
||||
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
|
||||
powerShellPlanJobs(plan);
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.systemJobs);
|
||||
}
|
||||
export interface PowerShellPlanJob { readonly assetId: string; readonly profile: 'inherited' | 'powershell_51_remote_signed' }
|
||||
// Only successful verification writes this cache. Projection is copied from the
|
||||
// verified bytes; later mutations of API views cannot change the displayed plan.
|
||||
interface VerifiedPowerShellPlan { readonly jobs: readonly PowerShellPlanJob[]; readonly logJobs: readonly QueryLogsPlanJob[]; readonly msiJobs: readonly WindowsMsiPlanJob[]; readonly systemJobs: RecordValue[]; readonly planHash: unknown; readonly planBytes: readonly number[] }
|
||||
const verifiedPowerShellPlans = new WeakMap<RecordValue, VerifiedPowerShellPlan>();
|
||||
export function powerShellPlanJobs(plan: RecordValue): readonly PowerShellPlanJob[] {
|
||||
const verified = verifiedPowerShellPlans.get(plan);
|
||||
if (!verified) throw new Error('PowerShell-Plan wurde nicht aus hashgeprüften gespeicherten Bytes verifiziert');
|
||||
if (verified.planBytes.length) {
|
||||
const current = bytes(plan.plan_payload_bytes);
|
||||
if (plan.plan_hash !== verified.planHash || current.length !== verified.planBytes.length || verified.planBytes.some((value, i) => current[i] !== value)) throw new Error('PowerShell-Planbytes wurden nach Verifikation verändert');
|
||||
const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(current)));
|
||||
validatePlanAliases(plan, parsed);
|
||||
validatePowerShellViews(plan, parsed.jobs);
|
||||
validateQueryLogsViews(plan, parsed.jobs);
|
||||
validateMsiViews(plan, parsed.jobs);
|
||||
} else if (scriptPayloads(planTargetPreviews(plan)).some(hasPowerShellProfile)) {
|
||||
throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
}
|
||||
return verified.jobs.map(job => ({ ...job }));
|
||||
}
|
||||
export function powerShellApprovalBlockers(plan: RecordValue): string[] {
|
||||
try { powerShellPlanJobs(plan); return []; }
|
||||
catch (error) { return [error instanceof Error ? error.message : 'PowerShell-Profil ist nicht verifiziert']; }
|
||||
}
|
||||
function scriptPayloads(jobs: unknown): RecordValue[] {
|
||||
if (!Array.isArray(jobs)) return [];
|
||||
return jobs.flatMap(job => {
|
||||
if (!job || typeof job !== 'object') return [];
|
||||
const payload = record(job).payload;
|
||||
return payload && typeof payload === 'object' ? [record(payload)] : [];
|
||||
});
|
||||
}
|
||||
function hasPowerShellProfile(payload: RecordValue): boolean {
|
||||
if (Object.prototype.hasOwnProperty.call(payload, 'windows_execution_profile')) throw new Error('Windows-Ausführungsprofil muss Teil der festen Skriptaktion sein');
|
||||
const action = payload.action;
|
||||
return action !== null && typeof action === 'object' && (record(action).interpreter === 'powershell'
|
||||
|| Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile'));
|
||||
}
|
||||
function projectPowerShellJobs(jobs: unknown): PowerShellPlanJob[] {
|
||||
return scriptPayloads(jobs).filter(hasPowerShellProfile).map(payload => {
|
||||
const action = record(payload.action);
|
||||
if (action.action !== 'run_script' || action.interpreter !== 'powershell' || payload.execution_identity !== 'agent_service') throw new Error('PowerShell-Profil benötigt Windows PowerShell5.1 als agent_service');
|
||||
exact(action, ['action', 'interpreter', 'script_utf8', 'arguments', 'expected_stdout', ...(Object.prototype.hasOwnProperty.call(action, 'windows_execution_profile') ? ['windows_execution_profile'] : [])]);
|
||||
if (typeof action.script_utf8 !== 'string' || !action.script_utf8 || new TextEncoder().encode(action.script_utf8).length > 32768 || action.script_utf8.includes('\0')
|
||||
|| (!/^[\x00-\x7f]*$/.test(action.script_utf8) && !action.script_utf8.startsWith('\ufeff'))
|
||||
|| !Array.isArray(action.arguments) || action.arguments.length > 32 || action.arguments.some(arg => typeof arg !== 'string' || new TextEncoder().encode(arg).length > 4096 || arg.includes('\0'))
|
||||
|| !(action.expected_stdout === null || (typeof action.expected_stdout === 'string' && new TextEncoder().encode(action.expected_stdout).length <= 65536))) throw new Error('Vollständige unveränderte PowerShell-Skriptaktion erforderlich');
|
||||
return { assetId: text(payload.asset_id, 'PowerShell-Zielasset'), profile: windowsScriptProfile(action) };
|
||||
});
|
||||
}
|
||||
function validatePlanAliases(plan: RecordValue, parsed: unknown): void {
|
||||
for (const alias of ['plan_payload', 'payload']) if (plan[alias] !== undefined && canonical(parsed) !== canonical(plan[alias])) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
const p = record(parsed);
|
||||
if (scriptPayloads(p.jobs).some(isMsi) && ((plan.plan_id !== undefined && plan.plan_id !== p.plan_id) || (plan.expires_at !== undefined && plan.expires_at !== scriptPayloads(p.jobs)[0]?.start_before))) throw new Error('MSI-Plan-ID/Fristansicht widerspricht gespeicherten Bytes');
|
||||
}
|
||||
function validateFixedViews(plan: RecordValue, rawJobs: unknown, selected: (payload: RecordValue) => boolean, label: string, fields = ['action', 'execution_identity']): void {
|
||||
const rawPayloads = scriptPayloads(rawJobs), views = [planTargetPreviews(plan)];
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
if (plan[alias] !== undefined && !Array.isArray(plan[alias])) throw new Error(`${label}-Zielpreview ist keine vollständige Liste`);
|
||||
if (Array.isArray(plan[alias])) views.push(plan[alias]);
|
||||
}
|
||||
for (const collection of new Set(views)) if (collection !== null) {
|
||||
if (!collection.some(value => value !== null && typeof value === 'object' && !Array.isArray(value) && 'payload' in value)) continue;
|
||||
const viewPayloads = scriptPayloads(collection);
|
||||
for (const fixed of rawPayloads.filter(selected)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error(`${label}-Zielpreview fehlt im festen Plan`);
|
||||
for (const view of viewPayloads) {
|
||||
const raw = rawPayloads.find(payload => payload.asset_id === view.asset_id);
|
||||
if ((selected(view) || (raw && selected(raw))) && (!raw || fields.some(field => canonical(raw[field]) !== canonical(view[field])))) throw new Error(`${label}-Zielpreview widerspricht gespeicherten Planbytes`);
|
||||
}
|
||||
}
|
||||
}
|
||||
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
validateFixedViews(plan, rawJobs, hasPowerShellProfile, 'PowerShell');
|
||||
}
|
||||
function isQueryLogs(payload: RecordValue): boolean {
|
||||
return payload.action !== null && typeof payload.action === 'object' && record(payload.action).action === 'query_logs';
|
||||
}
|
||||
function validateQueryLogsViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
validateFixedViews(plan, rawJobs, isQueryLogs, 'Log', ['action', 'execution_identity', 'max_runtime_seconds', 'max_output_bytes']);
|
||||
}
|
||||
export interface QueryLogsPlanJob {
|
||||
readonly assetId: string; readonly source: string; readonly since: string; readonly until: string;
|
||||
readonly maxLines: number; readonly runtimeSeconds: number; readonly outputBytes: number; readonly windows: boolean;
|
||||
readonly channel: string | null; readonly provider: string | null;
|
||||
}
|
||||
function projectQueryLogsJobs(jobs: unknown): QueryLogsPlanJob[] {
|
||||
return scriptPayloads(jobs).filter(isQueryLogs).map(payload => {
|
||||
const action = record(payload.action);
|
||||
exact(action, ['action', 'unit', 'since', 'until', 'max_lines']);
|
||||
const source = text(action.unit, 'Logquelle'), since = text(action.since, 'since'), until = text(action.until, 'until');
|
||||
logWindow(since, until);
|
||||
if (typeof action.max_lines !== 'number' || !Number.isSafeInteger(action.max_lines) || action.max_lines < 1 || action.max_lines > 1000
|
||||
|| typeof payload.max_runtime_seconds !== 'number' || !Number.isSafeInteger(payload.max_runtime_seconds) || payload.max_runtime_seconds < 1 || payload.max_runtime_seconds > 3600
|
||||
|| typeof payload.max_output_bytes !== 'number' || !Number.isSafeInteger(payload.max_output_bytes) || payload.max_output_bytes < 1 || payload.max_output_bytes > 262144) throw new Error('Vollständige feste Loglimits erforderlich');
|
||||
const windows = source === windowsEventLogFixtureSource;
|
||||
if (source.startsWith('windows.eventlog.') && !windows) throw new Error('Unbekannte Windows-Eventlogquelle');
|
||||
if (windows) validateWindowsLogLimits(payload.execution_identity, payload.max_runtime_seconds, payload.max_output_bytes, since);
|
||||
else if (!['agent_service', 'root'].includes(String(payload.execution_identity))) throw new Error('Unbekannte Log-Ausführungsidentität');
|
||||
return { assetId: text(payload.asset_id, 'Log-Zielasset'), source, since, until, maxLines: action.max_lines,
|
||||
runtimeSeconds: payload.max_runtime_seconds, outputBytes: payload.max_output_bytes, windows,
|
||||
channel: windows ? windowsEventLogFixtureChannel : null, provider: windows ? windowsEventLogFixtureProvider : null };
|
||||
});
|
||||
}
|
||||
export function queryLogsPlanJobs(plan: RecordValue): readonly QueryLogsPlanJob[] {
|
||||
// Reuse the same verified-object/immutable-byte gate as the PowerShell view.
|
||||
powerShellPlanJobs(plan);
|
||||
const verified = verifiedPowerShellPlans.get(plan)!;
|
||||
if (!verified.planBytes.length && ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
|
||||
return verified.logJobs.map(job => ({ ...job }));
|
||||
}
|
||||
export function queryLogsApprovalBlockers(plan: RecordValue): string[] {
|
||||
try { queryLogsPlanJobs(plan); return []; }
|
||||
catch (error) { return [error instanceof Error ? error.message : 'Logplan ist nicht verifiziert']; }
|
||||
}
|
||||
|
||||
export async function verifyWindowsMsiManifest(value: unknown): Promise<WindowsMsiManifest> {
|
||||
const m = windowsMsiManifest(value);
|
||||
if (await sha256(new TextEncoder().encode(JSON.stringify(m.recipe))) !== m.recipe_sha256) throw new Error('MSI-Rezepthash widerspricht kanonischen Rust-Rezeptbytes');
|
||||
return m;
|
||||
}
|
||||
function isMsi(payload: RecordValue): boolean {
|
||||
const action = payload.action;
|
||||
return action !== null && typeof action === 'object' && (record(action).provider === 'msi' || Object.prototype.hasOwnProperty.call(action, 'windows_msi_manifest'));
|
||||
}
|
||||
function hasMsiView(plan: RecordValue): boolean {
|
||||
return ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isMsi))
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isMsi) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isMsi);
|
||||
}
|
||||
/** MSI views bind the entire payload, preview identity and hash, not just argv. */
|
||||
function validateMsiViews(plan: RecordValue, rawJobs: unknown): void {
|
||||
const originals = Array.isArray(rawJobs) ? rawJobs.map(job => record(job)) : [];
|
||||
const raw = scriptPayloads(rawJobs);
|
||||
for (const alias of ['jobs', 'payloads', 'resolved_targets']) {
|
||||
const values = plan[alias]; if (values === undefined) continue;
|
||||
if (!Array.isArray(values)) { if (raw.some(isMsi)) throw new Error('MSI-Zielansicht ist keine vollständige Liste'); continue; }
|
||||
if (!raw.some(isMsi) && !scriptPayloads(values).some(isMsi)) continue;
|
||||
if (values.length !== raw.length) throw new Error('MSI-Zielansicht ist unvollständig oder enthält zusätzliche Ziele');
|
||||
const seen = new Set<string>();
|
||||
for (const value of values) {
|
||||
const v = typeof value === 'string' ? { asset_id: value } : record(value);
|
||||
const payload = v.payload === undefined ? null : record(v.payload);
|
||||
const asset = text(v.asset_id ?? payload?.asset_id, 'MSI-Zielasset'), index = raw.findIndex(item => item.asset_id === asset);
|
||||
if (index < 0 || seen.has(asset)) throw new Error('MSI-Zielansicht enthält fremde/doppelte Ziele'); seen.add(asset);
|
||||
const fixed = raw[index]!, original = originals[index]!;
|
||||
if (!isMsi(fixed)) throw new Error('MSI-Ansicht widerspricht gespeichertem Aktionstyp');
|
||||
if (payload) {
|
||||
const allowed = ['payload', 'job_payload_hash', 'script_sha256', 'asset_id', 'agent_id', 'job_id', 'attempt_id'];
|
||||
if (Object.keys(v).some(key => !allowed.includes(key)) || canonical(payload) !== canonical(fixed) || v.job_payload_hash !== original.job_payload_hash || (v.script_sha256 !== undefined && v.script_sha256 !== original.script_sha256)
|
||||
|| ['agent_id', 'job_id', 'attempt_id'].some(key => v[key] !== undefined && v[key] !== fixed[key])) throw new Error('MSI-Zielpreview widerspricht gespeicherten Planbytes');
|
||||
} else if (alias !== 'resolved_targets' || (typeof value !== 'string' && (Object.keys(v).some(key => !['asset_id', 'agent_id'].includes(key)) || v.agent_id !== fixed.agent_id))) throw new Error('Vollständiger MSI-Zielpayload fehlt');
|
||||
}
|
||||
}
|
||||
}
|
||||
export interface WindowsMsiPlanJob {
|
||||
readonly assetId: string; readonly recipeId: string; readonly recipeHash: string;
|
||||
readonly artifactId: string; readonly artifactHash: string; readonly artifactBytes: number;
|
||||
readonly productCode: string; readonly upgradeCode: string; readonly packageCode: string | null; readonly version: string;
|
||||
readonly payloadPath: string; readonly payloadHash: string; readonly payloadBytes: number;
|
||||
readonly predecessor: Readonly<MsiPostcondition> | null; readonly runtimeSeconds: number; readonly outputBytes: number; readonly arguments: readonly string[];
|
||||
}
|
||||
function msiArguments(sha: string): string[] { return ['/i', `C:\\ProgramData\\RustDiscoverySystem\\cache\\${sha}.msi`, '/qn', '/norestart', 'REBOOT=ReallySuppress', 'ALLUSERS=1']; }
|
||||
async function projectMsiJobs(parsed: RecordValue): Promise<WindowsMsiPlanJob[]> {
|
||||
const payloads = scriptPayloads(parsed.jobs); if (!payloads.some(isMsi)) return [];
|
||||
exact(parsed, ['schema_version', 'plan_id', 'tenant_id', 'principal', 'reason', 'jobs', 'max_parallel', 'halt_after_failures', 'recipe_references', 'artifact_references']);
|
||||
if (parsed.schema_version !== 1 || !Array.isArray(parsed.jobs) || !parsed.jobs.length || parsed.jobs.length > 100 || payloads.length !== parsed.jobs.length || payloads.some(p => !isMsi(p)) || !Array.isArray(parsed.recipe_references) || !Array.isArray(parsed.artifact_references)) throw new Error('Vollständiger fester MSI-Plan erforderlich');
|
||||
msiUuid(parsed.plan_id); msiUuid(parsed.tenant_id); text(parsed.principal, 'MSI-Antragsteller'); text(parsed.reason, 'MSI-Grund');
|
||||
if (!Number.isSafeInteger(parsed.max_parallel) || Number(parsed.max_parallel) < 1 || Number(parsed.max_parallel) > 10 || !Number.isSafeInteger(parsed.halt_after_failures) || Number(parsed.halt_after_failures) < 1) throw new Error('MSI-Rolloutlimits fehlen');
|
||||
const projections: WindowsMsiPlanJob[] = [], recipes = new Map<string, RecordValue>(), jobs = new Set<string>(), assets = new Set<string>();
|
||||
for (const value of parsed.jobs) {
|
||||
const j = record(value); exact(j, ['payload', 'job_payload_hash', 'script_sha256']);
|
||||
const p = record(j.payload); exact(p, ['schema_version', 'tenant_id', 'asset_id', 'agent_id', 'enrollment_generation', 'assignment_version', 'job_id', 'attempt_id', 'action', 'execution_identity', 'not_before', 'start_before', 'max_runtime_seconds', 'max_output_bytes']);
|
||||
const asset = msiUuid(p.asset_id), tuple = `${msiUuid(p.job_id)}/${msiUuid(p.attempt_id)}`; msiUuid(p.agent_id);
|
||||
if (p.schema_version !== 1 || p.tenant_id !== parsed.tenant_id || p.execution_identity !== 'system' || j.script_sha256 !== null || jobs.has(tuple) || assets.has(asset)
|
||||
|| !Number.isSafeInteger(p.enrollment_generation) || Number(p.enrollment_generation) < 1 || !Number.isSafeInteger(p.assignment_version) || Number(p.assignment_version) < 1
|
||||
|| typeof p.not_before !== 'string' || typeof p.start_before !== 'string' || !Number.isFinite(Date.parse(p.not_before)) || !Number.isFinite(Date.parse(p.start_before)) || Date.parse(p.not_before) >= Date.parse(p.start_before)) throw new Error('MSI-Jobidentität/Frist/Generation widerspricht festem Plan');
|
||||
jobs.add(tuple); assets.add(asset); validateWindowsMsiLimits(p.max_runtime_seconds, p.max_output_bytes);
|
||||
const action = windowsMsiAction(record(p.action)), m = await verifyWindowsMsiManifest(action.windows_msi_manifest), r = m.recipe;
|
||||
// JobPayload declaration order and nested Action/Recipe order are fixed.
|
||||
const ordered = { schema_version: p.schema_version, tenant_id: p.tenant_id, asset_id: p.asset_id, agent_id: p.agent_id, enrollment_generation: p.enrollment_generation, assignment_version: p.assignment_version, job_id: p.job_id, attempt_id: p.attempt_id, action, execution_identity: p.execution_identity, not_before: p.not_before, start_before: p.start_before, max_runtime_seconds: p.max_runtime_seconds, max_output_bytes: p.max_output_bytes };
|
||||
if (await sha256(new TextEncoder().encode(JSON.stringify(ordered))) !== j.job_payload_hash) throw new Error('MSI-Jobhash widerspricht festen Rust-Payloadbytes');
|
||||
const recipe = { package: windowsMsi.package, version: r.postcondition.product_version, architecture: 'x64', recipe_version: r.recipe_version, sha256: m.recipe_sha256 };
|
||||
recipes.set(JSON.stringify(recipe), recipe);
|
||||
const refs = parsed.artifact_references.map(value => record(value)).filter(ref => ref.job_id === p.job_id && ref.attempt_id === p.attempt_id);
|
||||
const expectedArtifact = { artifact_id: r.artifact.artifact_id, sha256: r.artifact.sha256, size_bytes: r.artifact.bytes };
|
||||
if (refs.length !== 1) throw new Error('MSI benötigt genau eine Artefaktreferenz pro Job/Versuch');
|
||||
exact(refs[0]!, ['job_id', 'attempt_id', 'artifact']); exact(record(refs[0]!.artifact), ['artifact_id', 'sha256', 'size_bytes']);
|
||||
if (canonical(refs[0]!.artifact) !== canonical(expectedArtifact)) throw new Error('MSI-Artefaktreferenz widerspricht signiertem Rezept');
|
||||
projections.push({ assetId: asset, recipeId: r.recipe_id, recipeHash: m.recipe_sha256, artifactId: r.artifact.artifact_id, artifactHash: r.artifact.sha256, artifactBytes: r.artifact.bytes, productCode: r.postcondition.product_code, upgradeCode: r.upgrade_code, packageCode: r.package_code ?? null, version: r.postcondition.product_version, payloadPath: r.postcondition.payload_path, payloadHash: r.postcondition.payload_sha256, payloadBytes: r.postcondition.payload_bytes, predecessor: r.predecessor ?? null, runtimeSeconds: Number(p.max_runtime_seconds), outputBytes: Number(p.max_output_bytes), arguments: msiArguments(r.artifact.sha256) });
|
||||
}
|
||||
const expectedRecipes = [...recipes.values()].sort((a, b) => { for (const key of ['package', 'version', 'architecture', 'recipe_version', 'sha256']) { if (String(a[key]) < String(b[key])) return -1; if (String(a[key]) > String(b[key])) return 1; } return 0; });
|
||||
for (const value of parsed.recipe_references) exact(record(value), ['package', 'version', 'architecture', 'recipe_version', 'sha256']);
|
||||
if (parsed.artifact_references.length !== payloads.length || canonical(parsed.recipe_references) !== canonical(expectedRecipes)) throw new Error('Vollständige exakte MSI-Rezept-/Artefaktmenge widerspricht gespeichertem Plan');
|
||||
return projections;
|
||||
}
|
||||
export function windowsMsiPlanJobs(plan: RecordValue): readonly WindowsMsiPlanJob[] {
|
||||
powerShellPlanJobs(plan);
|
||||
if (!verifiedPowerShellPlans.get(plan)!.planBytes.length && hasMsiView(plan)) throw new Error('MSI-Plan benötigt exakte gespeicherte Planbytes');
|
||||
return structuredClone(verifiedPowerShellPlans.get(plan)!.msiJobs);
|
||||
}
|
||||
export function windowsMsiApprovalBlockers(plan: RecordValue): string[] { try { windowsMsiPlanJobs(plan); return []; } catch (error) { return [error instanceof Error ? error.message : 'MSI-Plan ist nicht verifiziert']; } }
|
||||
|
||||
export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
// Rechecking a previously displayed object may not bless a replacement plan.
|
||||
if (verifiedPowerShellPlans.has(plan)) { powerShellPlanJobs(plan); windowsMsiPlanJobs(plan); }
|
||||
verifiedPowerShellPlans.delete(plan);
|
||||
const views = planTargetPreviews(plan), hasScriptView = scriptPayloads(views).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(plan.jobs).some(hasPowerShellProfile) || scriptPayloads(plan.payloads).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(plan.resolved_targets).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(hasPowerShellProfile)
|
||||
|| scriptPayloads(record(plan.payload ?? {}).jobs).some(hasPowerShellProfile);
|
||||
if (hasScriptView && plan.plan_payload_bytes === undefined) throw new Error('PowerShell-Plan benötigt exakte gespeicherte Planbytes');
|
||||
const hasLogView = ['jobs', 'payloads', 'resolved_targets'].some(alias => scriptPayloads(plan[alias]).some(isQueryLogs))
|
||||
|| scriptPayloads(record(plan.plan_payload ?? {}).jobs).some(isQueryLogs) || scriptPayloads(record(plan.payload ?? {}).jobs).some(isQueryLogs);
|
||||
if (hasLogView && plan.plan_payload_bytes === undefined) throw new Error('Logplan benötigt exakte gespeicherte Planbytes');
|
||||
if (hasMsiView(plan) && plan.plan_payload_bytes === undefined) throw new Error('MSI-Plan benötigt exakte gespeicherte Planbytes');
|
||||
let logJobs: QueryLogsPlanJob[] = [];
|
||||
let powerShellJobs: PowerShellPlanJob[] = [];
|
||||
let msiJobs: WindowsMsiPlanJob[] = [], systemJobs: RecordValue[] = [];
|
||||
let verifiedBytes: readonly number[] = [];
|
||||
let verifiedParsed: RecordValue | null = null;
|
||||
const verifiedHash = plan.plan_hash;
|
||||
if (plan.plan_payload_bytes === undefined && Array.isArray(plan.jobs) && plan.jobs.some(value => {
|
||||
const payload = record(value).payload;
|
||||
return payload !== null && typeof payload === 'object' && record(payload).execution_identity === 'system';
|
||||
@@ -109,11 +333,25 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
if (plan.plan_payload_bytes !== undefined) {
|
||||
const exactBytes = bytes(plan.plan_payload_bytes); hash(plan.plan_hash);
|
||||
if (await sha256(exactBytes) !== plan.plan_hash) throw new Error('Planhash stimmt nicht mit gespeicherten Bytes überein');
|
||||
verifiedBytes = Array.from(exactBytes);
|
||||
const parsed = parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(exactBytes));
|
||||
if (plan.plan_payload !== undefined && canonical(parsed) !== canonical(plan.plan_payload)) throw new Error('Planansicht widerspricht gespeicherten Bytes');
|
||||
validatePlanAliases(plan, parsed);
|
||||
const parsedPlan = record(parsed), rawJobs = parsedPlan.jobs;
|
||||
verifiedParsed = parsedPlan;
|
||||
powerShellJobs = projectPowerShellJobs(rawJobs);
|
||||
logJobs = projectQueryLogsJobs(rawJobs);
|
||||
if (hasLogView || logJobs.length) validateQueryLogsViews(plan, rawJobs);
|
||||
if (hasScriptView || powerShellJobs.length) {
|
||||
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
|
||||
validatePowerShellViews(plan, rawJobs);
|
||||
}
|
||||
msiJobs = await projectMsiJobs(parsedPlan);
|
||||
validateMsiViews(plan, rawJobs);
|
||||
systemJobs = scriptPayloads(rawJobs).filter(payload => payload.execution_identity === 'system');
|
||||
}
|
||||
for (const payload of systemPlanJobs(plan)) {
|
||||
for (const payload of systemJobs) {
|
||||
const action = record(payload.action);
|
||||
if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above.
|
||||
exact(action, ['action', 'unit', 'state']);
|
||||
if (action.action !== 'set_service_state') throw new Error('SYSTEM-Plan enthält keine typisierte Dienstaktion');
|
||||
validateSystemService(action.unit, action.state, payload.max_runtime_seconds, payload.max_output_bytes);
|
||||
@@ -122,6 +360,15 @@ export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
for (const value of jobs) { if (!value || typeof value !== 'object') continue; const p = record(value).payload; if (!p || typeof p !== 'object') continue; const action = record(p).action;
|
||||
if (action && typeof action === 'object' && record(action).apt_manifest !== undefined && record(action).apt_manifest !== null) await verifyAptManifest(record(action).apt_manifest, record(action).action === 'apt_native_acceptance');
|
||||
}
|
||||
// No await after this check: asynchronous hash verification cannot publish a
|
||||
// projection for bytes/views that changed while WebCrypto was running.
|
||||
if (verifiedParsed) {
|
||||
const current = bytes(plan.plan_payload_bytes);
|
||||
if (plan.plan_hash !== verifiedHash || current.length !== verifiedBytes.length || current.some((n, i) => n !== verifiedBytes[i])) throw new Error('Planbytes wurden während der Verifikation verändert');
|
||||
validatePlanAliases(plan, verifiedParsed); validateMsiViews(plan, verifiedParsed.jobs);
|
||||
validatePowerShellViews(plan, verifiedParsed.jobs); validateQueryLogsViews(plan, verifiedParsed.jobs);
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), logJobs: logJobs.map(job => Object.freeze({ ...job })), msiJobs: structuredClone(msiJobs), systemJobs: structuredClone(systemJobs), planHash: verifiedHash, planBytes: verifiedBytes });
|
||||
}
|
||||
export function recipeInput(value: unknown): RecordValue {
|
||||
const r = record(value); exact(r, ['schema_version', 'provider', 'package', 'version', 'architecture', 'recipe_version', 'installation_context', 'reboot_policy']);
|
||||
|
||||
Reference in New Issue
Block a user