Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
207b91f19a | ||
|
|
abea4eb4d9 |
@@ -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,36 @@ 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();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
@@ -47,6 +82,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 +92,7 @@ impl Script {
|
||||
let Action::RunScript {
|
||||
interpreter,
|
||||
script_utf8,
|
||||
arguments,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
@@ -95,18 +131,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 +147,7 @@ impl Script {
|
||||
let Action::RunScript {
|
||||
script_utf8,
|
||||
expected_stdout,
|
||||
windows_execution_profile,
|
||||
..
|
||||
} = &job.action
|
||||
else {
|
||||
@@ -124,6 +157,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 +197,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 +216,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 +245,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 fixed1.0 first install/noop and fixed1.0→1.1 major-upgrade/noop.
|
||||
//! No fresh1.1, downgrade, repair, arbitrary predecessor, or EXE mode.
|
||||
//! Only first install/exact noop of v1.0.0 is implemented. Upgrade and EXE are
|
||||
//! separate deliveries, not guessed modes of this MSI executor.
|
||||
//! 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,80 +15,33 @@
|
||||
//! https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
|
||||
#[cfg(windows)]
|
||||
use anyhow::{Result, ensure};
|
||||
#[cfg(any(windows, test))]
|
||||
use rmm_domain::windows_execution::{ResolvedWindowsMsi, valid_package_code};
|
||||
#[cfg(windows)]
|
||||
use rmm_domain::windows_execution::ResolvedWindowsMsi;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
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(any(windows, test))]
|
||||
#[cfg(windows)]
|
||||
fn desired(&self, r: &ResolvedWindowsMsi) -> bool {
|
||||
let p = &r.recipe.postcondition;
|
||||
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_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.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_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 {
|
||||
@@ -140,94 +93,6 @@ 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.
|
||||
@@ -243,7 +108,7 @@ fn validate(r: &ResolvedWindowsMsi, allowed_recipe_sha256: &str) -> Result<()> {
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use rmm_domain::windows_execution::*;
|
||||
use rmm_domain::windows_execution::{MSI_PAYLOAD, MSI_PRODUCT_CODE};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
@@ -487,106 +352,6 @@ 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!(
|
||||
@@ -644,7 +409,6 @@ 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('#')
|
||||
@@ -656,7 +420,7 @@ mod windows {
|
||||
"MSI_EMBEDDED_CABINET_REQUIRED"
|
||||
);
|
||||
for (field, value) in [
|
||||
("ProductCode", r.recipe.postcondition.product_code.as_str()),
|
||||
("ProductCode", MSI_PRODUCT_CODE),
|
||||
(
|
||||
"ProductVersion",
|
||||
r.recipe.postcondition.product_version.as_str(),
|
||||
@@ -703,41 +467,15 @@ 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(product: &str, name: &str) -> Result<Option<String>> {
|
||||
fn property(name: &str) -> Result<Option<String>> {
|
||||
let mut value = [0u16; 256];
|
||||
let mut len = 255;
|
||||
let code = unsafe {
|
||||
MsiGetProductInfoExW(
|
||||
wide(product).as_ptr(),
|
||||
wide(MSI_PRODUCT_CODE).as_ptr(),
|
||||
ptr::null(),
|
||||
MSIINSTALLCONTEXT_MACHINE,
|
||||
wide(name).as_ptr(),
|
||||
@@ -751,58 +489,13 @@ mod windows {
|
||||
ensure!(code == 0 && len < 256, "MSI_MACHINE_PRODUCT_QUERY");
|
||||
Ok(Some(String::from_utf16(&value[..len as usize])?))
|
||||
}
|
||||
fn snapshot_product(product: &str, predecessor: Option<&str>) -> Result<Snapshot> {
|
||||
let product_state = property(product, "State")?;
|
||||
pub fn snapshot() -> Result<Snapshot> {
|
||||
let product_state = property("State")?;
|
||||
let product_version = if product_state.as_deref() == Some("5") {
|
||||
property(product, "VersionString")?
|
||||
property("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)?;
|
||||
@@ -813,32 +506,12 @@ 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) };
|
||||
@@ -874,9 +547,9 @@ mod windows {
|
||||
inspect_archive(&mut archive, r)?;
|
||||
let system_root = system_root()?;
|
||||
let msiexec = Held::open(&system_root.join("System32").join("msiexec.exe"), true)?;
|
||||
let before = snapshot_for(r)?;
|
||||
let before = snapshot()?;
|
||||
ensure!(
|
||||
before.baseline_allowed(r),
|
||||
before.absent() || before.desired(r),
|
||||
"MSI_EXISTING_PRODUCT_OR_PAYLOAD_CONFLICT"
|
||||
);
|
||||
Ok(Self {
|
||||
@@ -888,25 +561,6 @@ 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(
|
||||
@@ -921,35 +575,10 @@ mod windows {
|
||||
&& !cancelled.load(Ordering::SeqCst),
|
||||
"MSI_START_LIMIT_OR_CANCELLED"
|
||||
);
|
||||
// One original budget includes all synchronous verification and
|
||||
// the eventual installer. A late Noop is not retroactive success.
|
||||
let began = Instant::now();
|
||||
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?;
|
||||
inspect_archive(&mut self.archive, &self.recipe)?;
|
||||
self.msiexec.check()?;
|
||||
let before = snapshot()?;
|
||||
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(),
|
||||
@@ -969,11 +598,14 @@ mod windows {
|
||||
automatic_retry: false,
|
||||
})));
|
||||
}
|
||||
ensure!(
|
||||
before.baseline_allowed(&self.recipe),
|
||||
"MSI_INSTALL_BASELINE_CONFLICT"
|
||||
);
|
||||
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"
|
||||
);
|
||||
let began = Instant::now();
|
||||
let child = Command::new(&self.msiexec.path)
|
||||
.args([
|
||||
std::ffi::OsStr::new("/i"),
|
||||
@@ -1025,21 +657,14 @@ mod windows {
|
||||
};
|
||||
if exit.is_none()
|
||||
&& !cancelled.load(Ordering::SeqCst)
|
||||
&& within_budget(self.began, self.timeout)
|
||||
&& self.began.elapsed() < self.timeout
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let mut after = None;
|
||||
let (state, error, reboot, initiated) = if let Some(code) = code {
|
||||
// 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) {
|
||||
after = snapshot().ok();
|
||||
if after.is_none() && matches!(code, 0 | 3010) {
|
||||
(
|
||||
"unknown",
|
||||
"MSI_POSTCONDITION_QUERY_FAILED",
|
||||
@@ -1047,12 +672,11 @@ mod windows {
|
||||
false,
|
||||
)
|
||||
} else {
|
||||
observed_classification(
|
||||
classification(
|
||||
code,
|
||||
after
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.desired(&self.prepared.recipe)),
|
||||
within_deadline,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
@@ -1092,124 +716,11 @@ mod windows {
|
||||
}
|
||||
}
|
||||
#[cfg(windows)]
|
||||
pub use windows::{Installer, Prepared, Run, snapshot, snapshot_for};
|
||||
pub use windows::{Installer, Prepared, Run, snapshot};
|
||||
#[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),
|
||||
@@ -1241,7 +752,6 @@ mod tests {
|
||||
product_version: None,
|
||||
payload_sha256: None,
|
||||
payload_bytes: None,
|
||||
..Snapshot::default()
|
||||
};
|
||||
assert!(!advertised.absent());
|
||||
}
|
||||
|
||||
@@ -684,6 +684,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+131
-4
@@ -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,33 @@ pub fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, serde_json::Error> {
|
||||
serde_json::to_vec(value)
|
||||
}
|
||||
|
||||
/// 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"],
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, schemars::JsonSchema)]
|
||||
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Action {
|
||||
@@ -21,6 +49,12 @@ 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"
|
||||
)]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
},
|
||||
RefreshInventory {
|
||||
scope: String,
|
||||
@@ -99,8 +133,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}'))
|
||||
@@ -219,15 +255,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")
|
||||
}
|
||||
@@ -496,6 +542,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 +552,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 +574,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 +650,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 +663,83 @@ mod tests {
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn windows_remote_signed_profile_is_optional_exact_and_capability_bound() {
|
||||
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 no_terminal_replay_or_unknown_restart() {
|
||||
assert!(!JobState::Succeeded.allows(JobState::Running));
|
||||
assert!(!JobState::Unknown.allows(JobState::Running));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Unexported 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.
|
||||
//! 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.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
@@ -10,17 +11,6 @@ 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";
|
||||
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, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Architecture {
|
||||
@@ -66,11 +56,6 @@ 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)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -85,16 +70,10 @@ 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
|
||||
@@ -102,32 +81,11 @@ 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)?)))
|
||||
@@ -169,55 +127,6 @@ mod tests {
|
||||
payload_bytes: 20,
|
||||
},
|
||||
no_reboot: true,
|
||||
package_code: None,
|
||||
predecessor: None,
|
||||
}
|
||||
}
|
||||
#[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 {
|
||||
|
||||
@@ -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,7 @@ pub async fn event(
|
||||
ensure!(r.stdout == expected.as_bytes(), "expected output mismatch");
|
||||
}
|
||||
}
|
||||
script_profile_evidence(&payload.action, &evidence)?;
|
||||
if matches!(payload.action, Action::Reboot { .. }) {
|
||||
crate::synchronization::verify_reboot_success(
|
||||
tx, tenant, agent, e, &payload, r, &evidence,
|
||||
@@ -224,6 +225,74 @@ pub async fn event(
|
||||
.await?;
|
||||
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 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,
|
||||
|
||||
+154
-1
@@ -151,6 +151,12 @@ 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"
|
||||
)]
|
||||
windows_execution_profile: Option<WindowsExecutionProfile>,
|
||||
}
|
||||
#[derive(Clone, Deserialize, Serialize, schemars::JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -213,6 +219,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 {
|
||||
@@ -310,6 +317,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 +344,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 +379,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<()> {
|
||||
@@ -1035,6 +1053,72 @@ mod windows_contract_tests {
|
||||
i.script_variants.remove(1);
|
||||
assert!(target_action(&i, &["windows.base/1".into()]).is_err());
|
||||
}
|
||||
#[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 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 +1259,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())
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -393,6 +393,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 {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#requires -Version 5.1
|
||||
<#
|
||||
Build-only, fixed MSI1.0.0 or1.1.0 major-upgrade fixture. Writes only a NEW private child directory.
|
||||
Build-only, fixed MSI 1.0.0 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.
|
||||
1.1 removes only the exact known1.0 predecessor; no EXE/repair mode.
|
||||
No upgrade/EXE package is authored by this version.
|
||||
|
||||
Primary API/format contracts:
|
||||
https://learn.microsoft.com/en-us/windows/win32/msi/installer-opendatabase
|
||||
@@ -17,8 +17,7 @@ https://learn.microsoft.com/en-us/windows/win32/msi/package-codes
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$OutputParent,
|
||||
[Guid]$CaseId=([Guid]::NewGuid()),
|
||||
[ValidateSet('1.0.0','1.1.0')][string]$FixtureVersion='1.0.0'
|
||||
[Guid]$CaseId=([Guid]::NewGuid())
|
||||
)
|
||||
Set-StrictMode -Version Latest
|
||||
$ErrorActionPreference='Stop'
|
||||
@@ -26,18 +25,14 @@ $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=$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}")'
|
||||
$version='1.0.0'
|
||||
# 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=$isUpgrade;
|
||||
reboot_requested=$false;trust_changed=$false;downloads=$false;upgrade_authored=$false;
|
||||
product_code=$product;upgrade_code=$upgrade;component_code=$component;package_code=$package;version=$version}
|
||||
|
||||
function Require([bool]$Value,[string]$Code) {if (!$Value) {throw $Code}}
|
||||
@@ -174,7 +169,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 $version`r`n")
|
||||
$payloadBytes=[Text.Encoding]::ASCII.GetBytes("RustDiscovery MSI fixture 1.0.0`r`n")
|
||||
Write-New $payload $payloadBytes
|
||||
$ddf=Join-Path $case 'fixture.ddf'
|
||||
$ddfText=@"
|
||||
@@ -195,7 +190,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-'+$version+'-x64.msi');Require (!(Test-Path -LiteralPath $msi)) 'MSI_OUTPUT_EXISTS'
|
||||
$msi=Join-Path $case 'RustDiscoveryFixture-1.0.0-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)
|
||||
@@ -210,11 +205,9 @@ 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'',''.'')'
|
||||
@@ -225,17 +218,8 @@ 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}
|
||||
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]))")}
|
||||
}
|
||||
foreach ($action in $sequence.Keys) {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}
|
||||
@@ -252,23 +236,7 @@ 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 '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'
|
||||
}
|
||||
Require ('CustomAction' -notin $names -and 'Upgrade' -notin $names -and 'Registry' -notin $names -and 'ServiceInstall' -notin $names) 'MSI_FORBIDDEN_TABLE'
|
||||
$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
|
||||
@@ -285,17 +253,12 @@ 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=$(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}
|
||||
}
|
||||
$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}
|
||||
$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 $version`r`n";installed_path=$recipe.postcondition.payload_path}
|
||||
$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.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'))}
|
||||
@@ -304,7 +267,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=$isUpgrade}|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=$false}|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,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
|
||||
@@ -53,18 +53,6 @@ Zugänge und private Rohbelege bleiben gitignoriert.
|
||||
|
||||
## Aktuelle Windowsfortsetzung
|
||||
|
||||
Separater Profilbranch `codex/windows-powershell-profile`, Commit `abea4eb`:
|
||||
RemoteSigned als optionales festes Aktions-/Variantenfeld implementiert, alte
|
||||
Bytes erhalten, UI-Planansichten streng gebunden. Lokal Rust-/Server-/35Web-
|
||||
Prüfungen bestanden; danach nativ Cloud-Linux23 ohne Skips, Fall `f463acc9…`,
|
||||
Manifest `26247a3a…`. Windows22 weiterhin nicht nativ ausgeführt, keine
|
||||
Profilcapability veröffentlicht und kein PowerShelljob gestartet. Der
|
||||
Hauptcheckout bleibt für die Komponentenwartung unverändert. Quellen/Nachweise:
|
||||
[Profilbranch](https://gitea.incoso.eu/kevin_janssen/rust-discovery/src/branch/codex/windows-powershell-profile).
|
||||
Ein separat tatsächlich bestätigter Schemars-Nullable-Metadatenunterschied
|
||||
betrifft keine Berechtigung; sein enger Attributfix wird im isolierten folgenden
|
||||
M3-Schnitt mitgeführt. Der ursprüngliche Nativebeleg wird nicht umgeschrieben.
|
||||
|
||||
Neue Userentscheidungen1.18: RemoteSigned nur für den einzelnen zuvor in der
|
||||
WebUI genehmigten PowerShell5.1-Jobprozess, vor Genehmigung sichtbar und fest
|
||||
gebunden; bestehendes W32Time gezielt starten ohne Startart-/NTP-/ACLänderung;
|
||||
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
# Entdeckungen und Aufgaben nach dem Linux-MVP
|
||||
|
||||
Stand 2026-11-14. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
||||
Stand 2026-11-13. Die begrenzten Linux-[M0–M5-Gates](mvp-gates.md) sind
|
||||
abgeschlossen. Windows wird auf eigenen Auftrag fortgesetzt; seine aktuellen
|
||||
Voraussetzungen stehen in [Windows-Gates](windows-gates.md) und
|
||||
[Jobgrenze](windows-job-boundary.md). Diese Liste erweitert den Auftrag nicht.
|
||||
@@ -10,7 +10,6 @@ Pfad bleiben dort sofort relevant.
|
||||
|
||||
| Entdeckung / späteres Thema | Tatsächlicher heutiger Stand | Spätere Aufgabe |
|
||||
| --- | --- | --- |
|
||||
| Dev-Reversetunnel ohne Zielbanner | Windows-RMM-Heartbeats liefen tatsächlich weiter, während Serverlistener/TCP-Verbindung auf127.0.0.1:22240 vorhanden waren, aber kein SSH-Banner durchkam. Der Bootstraploop überwacht nur das äußere ssh.exe und verbindet nach dessen Ende neu; der Task hat kein RestartOnFailure. Konkrete Ursache des blockierten SSH-Ziels unbewiesen. Keine SSH-/Hostkey-/Expirygrenze gelockert. | Nach dem MVP begrenzte Transport-/Workerdiagnose verbessern. Keine automatische Schlüsselverlängerung, öffentliche Windowsportfreigabe oder pauschalen sshd-/UID-Resets. Der aktuelle manuelle Konsolenneustart bleibt ausdrücklich zeitlich abzustimmen und ist kein RMM-Rebootnachweis. |
|
||||
| Legacy-Syncflag ohne signierten Sync | Bei Clients ohne `rmm.sync.v1` setzt der bisherige Hello-Kompatibilitätspfad `sync_ready=true`. Auf dem passiven Windowsclient nach Serverneustart tatsächlich beobachtet; weiterhin keine Jobcapabilities und kein signierter Syncnachweis. | In Status/API `sync_required`, Unterstützung und tatsächlichen signierten Checkpoint trennen. Das Legacyflag niemals als Windows-Jobabnahme verwenden. |
|
||||
| Nichtstart zwischen Grant und Helperdelegation | Beim Windows-SCM-Source-Review2026-11-14 wurde eine lokale Consumption ohne Helperzeile als strenger Sync-Fault erkannt. Die Linux-Root-Quelle besitzt strukturell denselben frühen Pfad; dieser konkrete Linuxfall wurde noch nicht nativ reproduziert. Aktuelle Rootscope bleibt geschlossen. | Vor Wiederöffnung für weitere Rootjobs den engen Vor-Delegation-Cancel-/Fencefall reproduzieren und analog gebunden lösen; keine Missing-Row-Guardlockerung oder Historienänderung. Der aktuelle Windowsfixvertrag steht in Spec1.17/[Abandonvertrag](windows-system-abandon.md). Historische Linux-Abnahmen werden dadurch nicht rückwirkend als dieser Nachweis ausgegeben. |
|
||||
| Rohoutput und kanonischer Sync-Outcome | Das vorhandene Sync-Outcome-Limit von 512 KiB betrifft JSON; Zahlenarrays können den erlaubten Rohoutput deutlich vergrößern. Kleine bisherige MVP-Fixturen sind davon nicht betroffen. | Vor breiter Freigabe großer Ausgaben effektive Adapterlimits, Codec-/Kontrollnachrichtenbudget und gegebenenfalls Artefaktreferenzen konsistent qualifizieren. Keinen erfolglosen Sync als übernommen ausgeben. |
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
# 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.
|
||||
@@ -65,6 +65,17 @@ 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('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);
|
||||
|
||||
@@ -59,6 +59,14 @@ 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 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 }
|
||||
/** Decode explicit escaped CRLF before planning; never alter approved output bytes. */
|
||||
export function expectedStdout(value: string, format: string): string | null {
|
||||
@@ -68,6 +76,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 +86,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';
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
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 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);
|
||||
|
||||
+14
-6
@@ -1,9 +1,9 @@
|
||||
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 } from './safety';
|
||||
import { Login } from './login';
|
||||
|
||||
const errorText = (error: unknown) => error instanceof Error ? error.message : 'Unbekannter Fehler';
|
||||
@@ -15,6 +15,13 @@ export function SystemPlanNotice({ plan }: { plan: RecordValue }) {
|
||||
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 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>; }
|
||||
}
|
||||
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,14 +57,14 @@ 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 === '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>}
|
||||
{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={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>
|
||||
{identity === 'root' && <p className="warning">{rootWarning}</p>}
|
||||
{identity === 'system' && <p className="warning">{systemWarning}</p>}
|
||||
@@ -72,15 +79,16 @@ function PlanDetail({ tenantId, id, auth, onOperation }: { tenantId: string; id:
|
||||
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)] : ['Plan noch nicht geladen'];
|
||||
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}/>
|
||||
<PowerShellPlanNotice 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>
|
||||
<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();
|
||||
} 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>
|
||||
|
||||
+36
-1
@@ -1,10 +1,45 @@
|
||||
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 { adminIntent, allowed, availableActions, parseStrictJson, powerShellApprovalBlockers, powerShellPlanJobs, recipeInput, rootWarning, sha256, validateAptManifest, validateSensitiveInput, verifyAptManifest, verifyPlanIntegrity } from './safety';
|
||||
import { AdminControl } from './management';
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
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));
|
||||
|
||||
+90
-2
@@ -1,4 +1,4 @@
|
||||
import { Action, PlanInput, RecordValue, Session, record, text, validateSystemService } from './api';
|
||||
import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, windowsScriptProfile } 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.';
|
||||
@@ -101,7 +101,87 @@ export function systemPlanJobs(plan: RecordValue): RecordValue[] {
|
||||
if (!Array.isArray(parsed.jobs)) return [];
|
||||
return parsed.jobs.map(value => record(record(value).payload)).filter(payload => payload.execution_identity === 'system');
|
||||
}
|
||||
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 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);
|
||||
} 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');
|
||||
}
|
||||
function validatePowerShellViews(plan: RecordValue, rawJobs: unknown): 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('PowerShell-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) {
|
||||
// IDs-only target lists remain metadata. Every supplied payload-bearing
|
||||
// alias, however, must describe the same complete fixed PowerShell jobs.
|
||||
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(hasPowerShellProfile)) if (!viewPayloads.some(view => view.asset_id === fixed.asset_id)) throw new Error('PowerShell-Zielpreview fehlt im festen Plan');
|
||||
for (const view of viewPayloads) {
|
||||
const raw = rawPayloads.find(payload => payload.asset_id === view.asset_id);
|
||||
if ((hasPowerShellProfile(view) || (raw && hasPowerShellProfile(raw))) && (!raw || canonical(raw.action) !== canonical(view.action)
|
||||
|| raw.execution_identity !== view.execution_identity)) throw new Error('PowerShell-Zielpreview widerspricht gespeicherten Planbytes');
|
||||
}
|
||||
}
|
||||
}
|
||||
export async function verifyPlanIntegrity(plan: RecordValue) {
|
||||
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');
|
||||
let powerShellJobs: PowerShellPlanJob[] = [];
|
||||
let verifiedBytes: readonly number[] = [];
|
||||
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,8 +189,15 @@ 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 rawJobs = record(parsed).jobs;
|
||||
powerShellJobs = projectPowerShellJobs(rawJobs);
|
||||
if (hasScriptView || powerShellJobs.length) {
|
||||
if (!Array.isArray(rawJobs)) throw new Error('Vollständige feste PowerShell-Zielpayloads fehlen');
|
||||
validatePowerShellViews(plan, rawJobs);
|
||||
}
|
||||
}
|
||||
for (const payload of systemPlanJobs(plan)) {
|
||||
const action = record(payload.action);
|
||||
@@ -122,6 +209,7 @@ 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');
|
||||
}
|
||||
verifiedPowerShellPlans.set(plan, { jobs: powerShellJobs.map(job => Object.freeze({ ...job })), planHash: plan.plan_hash, 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