Add fresh device trust, installer recovery and scoped patch runtime

This commit is contained in:
2026-11-17 16:08:53 +01:00
parent 60f8f21f54
commit 81fcd9c8f8
24 changed files with 543 additions and 45 deletions
+18 -4
View File
@@ -1430,6 +1430,13 @@ impl Server {
}
}
/// Blocking SDK call; run on the agent's bounded blocking worker, never heartbeat reactor.
pub fn execution_timeout(action: &rmm_domain::jobs::Action, seconds: u32) -> Result<Duration> {
ensure!(
(1..=action.windows_system_runtime_limit(120, Some(rmm_domain::jobs::WINDOWS_UPDATE_MAX_SECONDS))).contains(&seconds),
"SYSTEM_EXECUTION_TIMEOUT_BOUND"
);
Ok(Duration::from_secs(u64::from(seconds) + 5))
}
pub fn exchange(pin: &Pin, call: &Call, timeout: Duration) -> Result<Reply> {
exchange_fixed(pin, call, timeout, false)
}
@@ -1443,10 +1450,17 @@ fn exchange_fixed(pin: &Pin, call: &Call, timeout: Duration, time_only: bool) ->
);
pin.validate()?;
require_self(&pin.agent).context(Stage::ClientSelfRole)?;
ensure!(
(Duration::from_secs(1)..=Duration::from_secs(125)).contains(&timeout),
"HELPER_CALL_TIMEOUT_BOUND"
);
if timeout > Duration::from_secs(125) {
let Operation::Execute { request, .. } = &call.operation else {
anyhow::bail!("HELPER_CALL_TIMEOUT_BOUND");
};
let job = pin.binding.job(&request.job_bytes)?;
ensure!(job.execution_identity == "system" && job.action.is_windows_update_template()
&& execution_timeout(&job.action, job.max_runtime_seconds)? == timeout,
"HELPER_CALL_TIMEOUT_BOUND");
} else {
ensure!(timeout >= Duration::from_secs(1), "HELPER_CALL_TIMEOUT_BOUND");
}
let deadline = Instant::now() + timeout;
let pipe = owned(unsafe {
CreateFileW(
+10 -13
View File
@@ -563,7 +563,7 @@ impl Client {
let timeout = if matches!(job.action, Action::UpdateAgent { .. }) {
Duration::from_secs(60)
} else {
execution_timeout(job.max_runtime_seconds)?
ipc::execution_timeout(&job.action, job.max_runtime_seconds)?
};
let permit = self
.lane
@@ -898,13 +898,6 @@ fn system_shape(job: &JobPayload) -> bool {
&& (1..=65536).contains(&job.max_output_bytes)
&& matches!(&job.action,Action::SetServiceState{unit,state} if unit.starts_with("RmmDiscoveryFixture")&&unit.len()>"RmmDiscoveryFixture".len()&&unit.len()<=80&&unit.bytes().all(|b|b.is_ascii_alphanumeric()||b"_-".contains(&b))&&matches!(state.as_str(),"running"|"stopped"))
}
fn execution_timeout(seconds: u32) -> Result<Duration> {
ensure!(
(1..=120).contains(&seconds),
"SYSTEM_EXECUTION_TIMEOUT_BOUND"
);
Ok(Duration::from_secs(u64::from(seconds) + 5))
}
pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()> {
if let Action::UpdateAgent { update } = &job.action {
ensure!(
@@ -1023,11 +1016,15 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
}
return Ok(());
}
let windows_update = job.action.is_windows_update_template();
let reboot_report = if windows_update && !outcome.output_truncated && matches!(outcome.state.as_str(), "succeeded" | "failed") {
rmm_domain::jobs::windows_update_reboot_report(&outcome.stdout)
} else { None };
ensure!(
matches!(
outcome.state.as_str(),
"succeeded" | "failed" | "cancelled" | "expired" | "unknown"
) && (job.action.windows_msi().is_some() || !outcome.reboot_required)
) && (job.action.windows_msi().is_some() || outcome.reboot_required == reboot_report.unwrap_or(false))
&& outcome
.stdout
.len()
@@ -1092,7 +1089,7 @@ pub(super) fn checked_outcome(job: &JobPayload, outcome: &Outcome) -> Result<()>
system_shape(job)
&& outcome.exit_code == Some(0)
&& !outcome.output_truncated
&& !outcome.reboot_required
&& (!windows_update || (reboot_report.is_some() && e["windows_update_reboot_required"] == serde_json::json!(reboot_report)))
&& e["postconditions_passed"] == true
&& e["privileged_script_profile"] == "full_maintenance_v1"
&& e["execution_sid"] == "S-1-5-18"
@@ -1417,9 +1414,9 @@ mod tests {
state: "stopped".into(),
};
assert!(!system_shape(&job));
assert_eq!(execution_timeout(120).unwrap(), Duration::from_secs(125));
assert!(execution_timeout(0).is_err());
assert!(execution_timeout(121).is_err());
assert_eq!(ipc::execution_timeout(&job.action, 120).unwrap(), Duration::from_secs(125));
assert!(ipc::execution_timeout(&job.action, 0).is_err());
assert!(ipc::execution_timeout(&job.action, 121).is_err());
let mut outcome = Outcome::unknown("LOST_REPLY");
assert!(checked_outcome(&job, &outcome).is_ok());
outcome.reboot_required = true;
+19 -2
View File
@@ -83,6 +83,8 @@ pub struct Settings {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
pub allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub windows_update_max_runtime_seconds: Option<u32>,
}
fn strict_recipe_hashes<'de, D: serde::Deserializer<'de>>(
d: D,
@@ -113,7 +115,7 @@ impl Settings {
&& job
.action
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
&& job.max_runtime_seconds <= self.max_runtime_seconds
&& job.max_runtime_seconds <= job.action.windows_system_runtime_limit(self.max_runtime_seconds, self.windows_update_max_runtime_seconds)
&& self.allowed_script_profiles.as_deref()
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
}
@@ -144,6 +146,7 @@ impl Settings {
|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]
)
&& (self.schema_version == 4 || !self.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(self.windows_update_max_runtime_seconds, self.allowed_script_profiles.as_deref())
&& (1..=120).contains(&self.max_runtime_seconds)
&& self.allowed_services.len() <= 16,
"SYSTEM_POLICY_PROFILE"
@@ -1167,8 +1170,8 @@ impl SystemHelper {
&& ((job.max_runtime_seconds <= self.settings.max_runtime_seconds
&& (matches!(&job.action,Action::SetServiceState{unit,state} if matches!(state.as_str(),"running"|"stopped")&&self.settings.allowed_services.iter().any(|r|r.name==*unit))
|| self.settings.permits_msi(&job)
|| self.settings.permits_script(&job)
|| self.settings.permits_reboot(&job)))
|| self.settings.permits_script(&job)
|| crate::update_admission::permits_denial(
&self.settings.binding,
&job
@@ -1974,6 +1977,7 @@ mod tests {
allow_reboot: false,
allowed_msi_recipe_sha256: None,
allowed_script_profiles: None,
windows_update_max_runtime_seconds: None,
};
let legacy = serde_json::to_value(&settings).unwrap();
assert!(legacy.get("allowed_msi_recipe_sha256").is_none());
@@ -2013,6 +2017,19 @@ mod tests {
assert!(!settings.permits_script(&script));
settings.schema_version = 3;
assert!(settings.permits_script(&script));
let generic_script = script.action.clone();
script.max_runtime_seconds = 3600;
settings.windows_update_max_runtime_seconds = Some(3600);
assert!(!settings.permits_script(&script));
if let Action::RunScript { script_utf8, windows_execution_profile, .. } = &mut script.action {
*script_utf8 = rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into();
*windows_execution_profile = Some(rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned);
}
assert!(settings.permits_script(&script));
settings.windows_update_max_runtime_seconds = None;
assert!(!settings.permits_script(&script));
script.action = generic_script;
script.max_runtime_seconds = 30;
script.execution_identity = "root".into();
assert!(!settings.permits_script(&script));
let mut null = legacy;
@@ -89,6 +89,9 @@ pub fn qualified(
&& crate::actions::powershell().is_ok(),
"system script qualification policy"
);
if settings.windows_update_max_runtime_seconds.is_some() {
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.to_owned());
}
caps.extend(["system:run_script", "script.full_maintenance/1"].map(str::to_string));
}
"set_service_state" => {
@@ -60,6 +60,8 @@ struct Settings {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
allowed_script_profiles: Option<Vec<PrivilegedScriptProfile>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
windows_update_max_runtime_seconds: Option<u32>,
}
fn strict_hashes<'de, D: serde::Deserializer<'de>>(
d: D,
@@ -213,6 +215,7 @@ pub fn render(input: Inputs<'_>) -> Result<CodePairTransition> {
ensure!(
matches!(settings.schema_version, 1..=4)
&& (settings.schema_version == 4 || !settings.allow_reboot)
&& rmm_domain::jobs::valid_windows_update_limit(settings.windows_update_max_runtime_seconds, settings.allowed_script_profiles.as_deref())
&& (1..=120).contains(&settings.max_runtime_seconds)
&& settings.allowed_services.len() <= 16
&& (settings.schema_version >= 2 || settings.allowed_msi_recipe_sha256.is_none())
+68 -1
View File
@@ -54,6 +54,36 @@ pub enum PrivilegedScriptProfile {
#[serde(rename = "full_maintenance_v1")]
FullMaintenanceV1,
}
/// Bytes of the Windows Update Agent PowerShell template seeded by migration 0023.
pub const WINDOWS_UPDATE_SCRIPT_UTF8: &str = include_str!("windows_update.ps1");
pub const WINDOWS_UPDATE_SCRIPT_SHA256: &str =
"0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf";
pub const WINDOWS_UPDATE_MAX_SECONDS: u32 = 3600;
pub const WINDOWS_UPDATE_LONG_CAPABILITY: &str = "script.windows_update.long/1";
pub fn valid_windows_update_limit(
limit: Option<u32>,
profiles: Option<&[PrivilegedScriptProfile]>,
) -> bool {
limit.is_none_or(|seconds| {
(121..=WINDOWS_UPDATE_MAX_SECONDS).contains(&seconds)
&& profiles == Some(&[PrivilegedScriptProfile::FullMaintenanceV1][..])
})
}
/// Only the built-in template's final ASCII JSON object describes the host's
/// restart state. Earlier lines can include per-update results and native titles.
pub fn windows_update_reboot_report(stdout: &[u8]) -> Option<bool> {
let summary = stdout
.rsplit(|byte| *byte == b'\n')
.map(<[u8]>::trim_ascii)
.find(|line| !line.is_empty())?;
let json: serde_json::Value = serde_json::from_slice(summary).ok()?;
let obj = json.as_object()?;
let reboot = obj.get("reboot_required")?.as_bool()?;
(obj.len() == 2
&& (obj.get("found").is_some_and(|v| v.is_u64())
|| (reboot && obj.get("status").and_then(|v| v.as_str()) == Some("restart_pending"))))
.then_some(reboot)
}
pub const FULL_MAINTENANCE_CAPABILITY: &str = "script.full_maintenance/1";
pub fn deserialize_privileged_script_profile<'de, D>(
d: D,
@@ -387,6 +417,20 @@ impl Action {
}
)
}
pub fn is_windows_update_template(&self) -> bool {
matches!(self, Self::RunScript {
interpreter, script_utf8, arguments, expected_stdout: None,
windows_execution_profile: Some(WindowsExecutionProfile::PowerShell51RemoteSigned),
privileged_script_profile: Some(PrivilegedScriptProfile::FullMaintenanceV1),
} if interpreter == "powershell" && arguments.is_empty() && script_utf8 == WINDOWS_UPDATE_SCRIPT_UTF8)
}
pub fn windows_system_runtime_limit(&self, normal: u32, windows_update: Option<u32>) -> u32 {
if self.is_windows_update_template() {
windows_update.unwrap_or(normal)
} else {
normal
}
}
pub fn valid_execution_identity(&self, identity: &str) -> bool {
if let Self::UpdateAgent { update } = self {
return update.execution_identity() == Some(identity);
@@ -410,7 +454,7 @@ impl Action {
|| (output_bytes <= 65536
&& runtime_seconds
<= if self.script_platform() == Some("windows") {
120
self.windows_system_runtime_limit(120, Some(WINDOWS_UPDATE_MAX_SECONDS))
} else {
300
}))
@@ -779,6 +823,29 @@ impl JobState {
mod tests {
use super::*;
#[test]
fn windows_update_final_report_and_policy_are_exact() {
assert_eq!(
windows_update_reboot_report(
b"ignored \xff\r\n{\"found\":1,\"reboot_required\":true}\r\n"
),
Some(true)
);
assert_eq!(
windows_update_reboot_report(br#"{"reboot_required":false,"found":0}"#),
Some(false)
);
assert_eq!(
windows_update_reboot_report(br#"{"reboot_required":true,"status":"restart_pending"}"#),
Some(true)
);
assert_eq!(
windows_update_reboot_report(br#"{"id":"an update","reboot_required":true}"#),
None
);
assert_eq!(windows_update_reboot_report(b"partial"), None);
assert!(!valid_windows_update_limit(Some(3600), None));
}
#[test]
fn windows_system_scm_is_explicit_and_preserves_linux_service_bytes() {
let caps: Vec<String> = [
"windows.base/1",
+47
View File
@@ -0,0 +1,47 @@
# Install available software updates from the configured Windows Update source.
# See https://learn.microsoft.com/windows/win32/wua_sdk/windows-update-agent-object-model
$ErrorActionPreference = 'Stop'
$session = New-Object -ComObject Microsoft.Update.Session
$session.ClientApplicationID = 'Rust Discovery'
$searcher = $session.CreateUpdateSearcher()
$search = $searcher.Search("IsInstalled=0 and IsHidden=0 and Type='Software'")
if ($search.ResultCode -ne 2) { throw "Update search returned $($search.ResultCode)" }
$failed = $false
$systemInfo = New-Object -ComObject Microsoft.Update.SystemInfo
if ($systemInfo.RebootRequired) {
Write-Output '{"reboot_required":true,"status":"restart_pending"}'
exit 1
}
foreach ($update in $search.Updates) {
$result = [ordered]@{ id = $update.Identity.UpdateID; title = $update.Title; status = 'pending' }
try {
if ($update.InstallationBehavior.CanRequestUserInput -or !$update.EulaAccepted) {
$result.status = 'operator_input_required'
$failed = $true
} else {
$batch = New-Object -ComObject Microsoft.Update.UpdateColl
[void]$batch.Add($update)
if (!$update.IsDownloaded) {
$downloader = $session.CreateUpdateDownloader()
$downloader.Updates = $batch
$download = $downloader.Download().GetUpdateResult(0)
if ($download.ResultCode -ne 2) { throw "Download HRESULT $($download.HResult)" }
}
$installer = $session.CreateUpdateInstaller()
$installer.AllowSourcePrompts = $false
$installer.Updates = $batch
$install = $installer.Install().GetUpdateResult(0)
$result.status = [int]$install.ResultCode
$result.hresult = $install.HResult
$result.reboot_required = [bool]$install.RebootRequired
if ($install.ResultCode -ne 2) { $failed = $true }
}
} catch {
$result.status = 'failed'
$result.error = $_.Exception.Message
$failed = $true
}
Write-Output ($result | ConvertTo-Json -Compress)
}
Write-Output (@{ found = $search.Updates.Count; reboot_required = [bool]$systemInfo.RebootRequired } | ConvertTo-Json -Compress)
if ($failed) { exit 1 }
+1
View File
@@ -308,6 +308,7 @@ RMM_BOOTSTRAP_PYTHON
.route("/agent/v1/bootstrap/updater", get(bootstrap::updater))
.route("/agent/v1/releases/current", get(current))
.route("/agent/v1/releases/installed", get(installed))
.route("/agent/v1/releases/device-trust", get(bootstrap::device_trust))
.route(
"/agent/v1/releases/{release}/artifacts/{artifact}",
get(release_artifact),
+27 -6
View File
@@ -176,14 +176,16 @@ def installed():
def healthy(version, baseline, duration=90):
until = time.monotonic() + duration
started = time.time()
while time.monotonic() < until:
try:
record = installed()
contact = record.get('last_contact_at')
if contact:
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
if (time.time() - 65 < recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline):
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
and record['connection_generation'] > baseline
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
return True
except (subprocess.SubprocessError, ValueError, OSError):
pass
@@ -249,6 +251,18 @@ def enable():
service('enable', '--now', SERVICE, TIMER)
def enrollment_token(path):
token = Path(path).read_text().strip() if path else getpass.getpass('Einmalcode: ').strip()
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
return token
def save_token(base, token, gid):
path = base / 'first.token'
save(path, token.encode(), 0o440)
os.chown(path, 0, gid)
def install(base, token_file):
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
base = origin(base)
@@ -256,12 +270,20 @@ def install(base, token_file):
config = read(ROOT / 'config.json')
require(config['bootstrap'] == base and (ROOT / 'current/manifest.json').is_file(),
'existing installation differs')
if not (STATE / 'identity.json').is_file():
token = enrollment_token(token_file)
with tempfile.TemporaryDirectory() as work:
metadata = Path(work) / 'bootstrap.json'
remote((base, token), '/agent/v1/bootstrap/current?platform=' + PLATFORM, metadata)
require(read(metadata)['tenant_id'] == config['tenant'], 'different enrollment tenant')
save_token(ROOT, token, pwd.getpwnam('rmm-discovery').pw_gid)
enable()
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
(ROOT / 'first.token').unlink(missing_ok=True)
return
require(not STATE.exists() and not any((UNIT_DIR/name).exists() for name in units()),
'existing device installation requires migration')
token = Path(token_file).read_text().strip() if token_file else getpass.getpass('Einmalcode: ').strip()
require(re.fullmatch('[0-9a-f]{64}', token), 'invalid enrollment token')
token = enrollment_token(token_file)
try:
account = pwd.getpwnam('rmm-discovery')
except KeyError:
@@ -290,8 +312,7 @@ def install(base, token_file):
link(staging, manifest['release_id'])
save(staging / 'lifecycle.py', Path(__file__).read_bytes())
save(staging / 'release.lock', b'')
save(staging / 'first.token', token.encode(), 0o440)
os.chown(staging / 'first.token', 0, account.pw_gid)
save_token(staging, token, account.pw_gid)
staging.chmod(0o755)
releases.chmod(0o755)
os.rename(staging, ROOT)
+33 -1
View File
@@ -106,6 +106,37 @@ async fn token_tenant(s: &crate::State, h: &HeaderMap) -> Result<Uuid, Error> {
.await?;
t.ok_or_else(denied)
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct TimeTrust {
key_generation: u64,
server_instance: Uuid,
public_keys_hex: std::collections::BTreeMap<String, String>,
}
fn device_trust_data(s: &crate::State) -> Result<Value, Error> {
let job_public = hex::encode(s.job_signer.public_key()?);
let path = std::env::var_os("RMM_AGENT_BOOTSTRAP_WINDOWS_FILE")
.and_then(|slot| FsPath::new(&slot).parent().map(|p| p.join("windows-time-trust.json")));
let trust = match path {
Some(path) if path.try_exists().map_err(|_| fail("BOOTSTRAP_TIME_TRUST_INVALID"))? => {
let trust: TimeTrust = serde_json::from_slice(&protected_file(&path, 8192)?)?;
if trust.key_generation == 0 || trust.server_instance.is_nil()
|| !(1..=8).contains(&trust.public_keys_hex.len())
|| !trust.public_keys_hex.iter().all(|(id,key)| !id.is_empty() && id.len() <= 64
&& id.bytes().all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
&& rmm_domain::agent_update::digest(key) && key != &job_public) {
return Err(fail("BOOTSTRAP_TIME_TRUST_INVALID"));
}
Some(trust)
}
_ => None
};
Ok(json!({"job_signing_public_key_hex":job_public,"windows_time_trust":trust}))
}
pub(super) async fn device_trust(State(s): State<crate::State>, Extension(peer): Extension<crate::Peer>, headers: HeaderMap) -> Result<Response, Error> {
device(&s, peer, &headers).await?;
Ok(private_json(device_trust_data(&s)?))
}
pub(super) async fn current(
State(s): State<crate::State>,
headers: HeaderMap,
@@ -126,8 +157,9 @@ pub(super) async fn current(
.ca
.to_pem()
.map_err(|_| invalid())?;
let trust = device_trust_data(&s)?;
Ok(private_json(
json!({"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
json!({"job_signing_public_key_hex":trust["job_signing_public_key_hex"],"windows_time_trust":trust["windows_time_trust"],"schema_version":1,"tenant_id":t,"release_envelope":envelope,"manifest":manifest,
"gateway_origin":c.gateway_origin,"ca_pem":String::from_utf8(ca).map_err(|_| invalid())?,
"keyring":ring,"updater":{"sha256":c.updater_sha256,"bytes":c.updater_bytes}}),
))
+2
View File
@@ -723,6 +723,7 @@ pub(crate) async fn plan_resolved(
artifact_references,
script_revision,
};
crate::script_library::validate_plan_bindings(&payload)?;
crate::windows_msi_catalog::validate_plan_bindings(&payload)?;
crate::agent_updates::validate_plan_bindings(&payload)?;
let bytes = encode(&payload)?;
@@ -759,6 +760,7 @@ async fn load_plan(
Ok((serde_json::from_slice(&bytes)?, h, bytes))
}
async fn recheck(tx: &mut Transaction<'_, Postgres>, plan: &PlanPayload) -> Result<()> {
crate::script_library::validate_plan_bindings(plan)?;
crate::windows_msi_catalog::validate_plan_bindings(plan)?;
crate::agent_updates::validate_plan_bindings(plan)?;
policy(tx).await?;
+42 -1
View File
@@ -186,6 +186,27 @@ pub async fn plan(
jobs::plan_resolved(s, p, tenant, plan, None, Some(reference)).await
}
pub(crate) fn validate_plan_bindings(plan: &rmm_domain::jobs::PlanPayload) -> Result<(), Error> {
let Some(reference) = &plan.script_revision else {
if plan.jobs.iter().any(|job| {
job.payload.max_runtime_seconds > 120 && job.payload.action.is_windows_update_template()
}) {
return Err(Error(
StatusCode::CONFLICT,
"WINDOWS_UPDATE_REVISION_REQUIRED",
));
}
return Ok(());
};
if reference.revision_id.is_nil() || reference.version < 1 || reference.name.is_empty() || plan.jobs.is_empty()
|| plan.jobs.iter().any(|job| !matches!(&job.payload.action,
Action::RunScript { script_utf8, .. } if hash(script_utf8.as_bytes()) == reference.script_sha256
&& job.script_sha256.as_ref() == Some(&reference.script_sha256))) {
return Err(Error(StatusCode::CONFLICT, "SCRIPT_REVISION_BINDING_MISMATCH"));
}
Ok(())
}
pub fn routes(r: Router<crate::State>) -> Router<crate::State> {
r.route(
"/api/v1/tenants/{tenant}/script-revisions",
@@ -247,7 +268,13 @@ pub(crate) mod tests {
template["script_utf8"].as_str().unwrap().into(),
)
.unwrap();
assert!(native.full_maintenance());
assert!(native.is_windows_update_template());
assert_eq!(
template["script_sha256"],
rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256
);
assert!(native.valid_job_limits(3600, 65536));
assert!(!native.valid_job_limits(3601, 65536));
let v1 = Publish {
name: "Agentversion".into(),
@@ -335,6 +362,20 @@ pub(crate) mod tests {
.unwrap();
tx.commit().await.unwrap();
let bound: rmm_domain::jobs::PlanPayload = serde_json::from_slice(&bytes).unwrap();
let mut extended = bound.clone();
extended.jobs[0].payload.action = native;
extended.jobs[0].payload.max_runtime_seconds = 3600;
extended.jobs[0].script_sha256 =
Some(rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_SHA256.into());
assert_eq!(
validate_plan_bindings(&extended).unwrap_err().1,
"SCRIPT_REVISION_BINDING_MISMATCH"
);
extended.script_revision = None;
assert_eq!(
validate_plan_bindings(&extended).unwrap_err().1,
"WINDOWS_UPDATE_REVISION_REQUIRED"
);
let reference = bound.script_revision.unwrap();
assert_eq!(reference.revision_id, id);
assert_eq!(reference.version, 1);
+39 -1
View File
@@ -45,6 +45,8 @@ struct SystemScope {
deserialize_with = "rmm_domain::jobs::deserialize_script_profiles"
)]
allowed_script_profiles: Option<Vec<rmm_domain::jobs::PrivilegedScriptProfile>>,
#[serde(default)]
windows_update_max_runtime_seconds: Option<u32>,
#[serde(default, deserialize_with = "strict_optional_reboot")]
allow_reboot: Option<bool>,
}
@@ -122,6 +124,10 @@ impl SystemScope {
.allowed_script_profiles
.as_deref()
.is_none_or(|v| v == [rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1])
&& rmm_domain::jobs::valid_windows_update_limit(
self.windows_update_max_runtime_seconds,
self.allowed_script_profiles.as_deref(),
)
&& (1..=120).contains(&self.max_runtime_seconds)
}
fn permits(
@@ -154,7 +160,13 @@ impl SystemScope {
"helper.binary.sha256:{}",
self.helper_binary_sha256
))
&& (1..=self.max_runtime_seconds).contains(&job.max_runtime_seconds)
&& (1..=job.action.windows_system_runtime_limit(
self.max_runtime_seconds,
self.windows_update_max_runtime_seconds,
))
.contains(&job.max_runtime_seconds)
&& (job.max_runtime_seconds <= 120
|| has(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY))
&& (1..=65536).contains(&job.max_output_bytes)
&& match &job.action {
Action::Reboot { .. } => {
@@ -556,6 +568,32 @@ mod tests {
policy.schema_version = 3;
assert!(policy.permits("selected", &job, &caps, Utc::now()));
assert!(!policy.permits("foreign", &job, &caps, Utc::now()));
let general = job.action.clone();
job.action = Action::RunScript {
interpreter: "powershell".into(),
script_utf8: rmm_domain::jobs::WINDOWS_UPDATE_SCRIPT_UTF8.into(),
arguments: vec![],
expected_stdout: None,
windows_execution_profile: Some(
rmm_domain::jobs::WindowsExecutionProfile::PowerShell51RemoteSigned,
),
privileged_script_profile: Some(
rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
),
};
caps.push("script.powershell.process_remote_signed/1".into());
job.max_runtime_seconds = 3600;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
caps.push(rmm_domain::jobs::WINDOWS_UPDATE_LONG_CAPABILITY.into());
assert!(policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(1800);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
policy.scopes[0].windows_update_max_runtime_seconds = Some(3600);
job.action = general;
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
job.max_runtime_seconds = 30;
caps.retain(|c| c != rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY);
assert!(!policy.permits("selected", &job, &caps, Utc::now()));
}