Use script-only execution on Linux and preserve the enrolled helper through updates
This commit is contained in:
@@ -1,241 +1,8 @@
|
|||||||
//! Approved artifact prefetch before a grant; Full independently admits the handoff.
|
//! Passive signed-release observations and retained update evidence.
|
||||||
use anyhow::{Context, Result, ensure};
|
use anyhow::{Context, Result, ensure};
|
||||||
use rmm_domain::{
|
use rmm_domain::agent_update::Platform;
|
||||||
agent_update::{
|
use rmm_privileged_helper::Binding;
|
||||||
APPLY_CAPABILITY, ArtifactDescriptor, ArtifactRole, CHECK_CAPABILITY, Platform,
|
use std::path::Path;
|
||||||
},
|
|
||||||
jobs::{Action, JobPayload},
|
|
||||||
};
|
|
||||||
use rmm_privileged_helper::{Binding, Request, control, update_admission::Accepted};
|
|
||||||
use sha2::{Digest, Sha256};
|
|
||||||
use std::{
|
|
||||||
fs::{self, File, OpenOptions},
|
|
||||||
io::{Read, Write},
|
|
||||||
os::unix::fs::{MetadataExt, OpenOptionsExt},
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
time::{Duration, Instant},
|
|
||||||
};
|
|
||||||
const MAXIMUM: u64 = 256 * 1024 * 1024;
|
|
||||||
const CHUNK: u64 = 512 * 1024;
|
|
||||||
pub struct Prefetch(pub tokio::task::JoinHandle<Result<()>>);
|
|
||||||
impl Drop for Prefetch {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.0.abort();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn directory(path: &Path, create: bool) -> Result<()> {
|
|
||||||
if create && !path.try_exists()? {
|
|
||||||
std::fs::DirBuilder::new().mode(0o700).create(path)?;
|
|
||||||
}
|
|
||||||
let m = fs::symlink_metadata(path)?;
|
|
||||||
ensure!(
|
|
||||||
m.is_dir() && !m.file_type().is_symlink() && m.uid() == 993 && m.mode() & 0o777 == 0o700,
|
|
||||||
"UPDATE_PREFETCH_DIRECTORY"
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
use std::os::unix::fs::DirBuilderExt;
|
|
||||||
fn parent(job: &JobPayload) -> Result<PathBuf> {
|
|
||||||
ensure!(
|
|
||||||
unsafe { libc::geteuid() } == 993,
|
|
||||||
"UPDATE_PREFETCH_AGENT_UID"
|
|
||||||
);
|
|
||||||
let base = Path::new("/var/lib/rmm-agent-remote");
|
|
||||||
directory(base, false)?;
|
|
||||||
let base = base.join("update-downloads");
|
|
||||||
directory(&base, true)?;
|
|
||||||
let base = base.join(job.job_id.to_string());
|
|
||||||
directory(&base, true)?;
|
|
||||||
let base = base.join(job.attempt_id.to_string());
|
|
||||||
directory(&base, true)?;
|
|
||||||
Ok(base)
|
|
||||||
}
|
|
||||||
fn label(a: &ArtifactDescriptor) -> &'static str {
|
|
||||||
match a.role {
|
|
||||||
ArtifactRole::Agent => "agent.bin",
|
|
||||||
ArtifactRole::Helper => "helper.bin",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn checked(path: &Path, a: &ArtifactDescriptor) -> Result<()> {
|
|
||||||
let mut f = OpenOptions::new()
|
|
||||||
.read(true)
|
|
||||||
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
|
||||||
.open(path)?;
|
|
||||||
let m = f.metadata()?;
|
|
||||||
ensure!(
|
|
||||||
m.is_file()
|
|
||||||
&& m.uid() == 993
|
|
||||||
&& m.mode() & 0o777 == 0o600
|
|
||||||
&& m.nlink() == 1
|
|
||||||
&& m.len() == a.bytes,
|
|
||||||
"UPDATE_PREFETCH_FILE"
|
|
||||||
);
|
|
||||||
let mut h = Sha256::new();
|
|
||||||
let mut n = 0;
|
|
||||||
let mut buf = [0; 65536];
|
|
||||||
loop {
|
|
||||||
let size = f.read(&mut buf)?;
|
|
||||||
if size == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
n += size as u64;
|
|
||||||
ensure!(n <= a.bytes, "UPDATE_PREFETCH_LENGTH");
|
|
||||||
h.update(&buf[..size]);
|
|
||||||
}
|
|
||||||
ensure!(
|
|
||||||
n == a.bytes && format!("{:x}", h.finalize()) == a.sha256,
|
|
||||||
"UPDATE_PREFETCH_DIGEST"
|
|
||||||
);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
pub async fn prefetch(client: reqwest::Client, base: String, job: JobPayload) -> Result<()> {
|
|
||||||
let Action::UpdateAgent { update } = &job.action else {
|
|
||||||
anyhow::bail!("UPDATE_ACTION_REQUIRED")
|
|
||||||
};
|
|
||||||
let manifest = update.manifest().map_err(anyhow::Error::msg)?;
|
|
||||||
ensure!(
|
|
||||||
manifest.validate() && manifest.platform == Platform::LinuxX64,
|
|
||||||
"UPDATE_PREFETCH_MANIFEST"
|
|
||||||
);
|
|
||||||
let pjob = job.clone();
|
|
||||||
let folder = tokio::task::spawn_blocking(move || parent(&pjob)).await??;
|
|
||||||
let deadline = Instant::now() + Duration::from_secs(600);
|
|
||||||
for artifact in manifest.artifacts {
|
|
||||||
ensure!(
|
|
||||||
artifact.bytes > 0 && artifact.bytes <= MAXIMUM,
|
|
||||||
"UPDATE_PREFETCH_LIMIT"
|
|
||||||
);
|
|
||||||
let path = folder.join(label(&artifact));
|
|
||||||
let existing = path.clone();
|
|
||||||
let desc = artifact.clone();
|
|
||||||
if tokio::task::spawn_blocking(move || -> Result<bool> {
|
|
||||||
if existing.try_exists()? {
|
|
||||||
checked(&existing, &desc)?;
|
|
||||||
Ok(true)
|
|
||||||
} else {
|
|
||||||
Ok(false)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.await??
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let stage = folder.join(format!("{}.partial", label(&artifact)));
|
|
||||||
let stage_path = stage.clone();
|
|
||||||
let mut file = tokio::task::spawn_blocking(move || {
|
|
||||||
OpenOptions::new()
|
|
||||||
.write(true)
|
|
||||||
.create_new(true)
|
|
||||||
.mode(0o600)
|
|
||||||
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
|
|
||||||
.open(stage_path)
|
|
||||||
})
|
|
||||||
.await??;
|
|
||||||
let mut offset = 0;
|
|
||||||
let mut hash = Sha256::new();
|
|
||||||
while offset < artifact.bytes {
|
|
||||||
ensure!(
|
|
||||||
Instant::now() < deadline && chrono::Utc::now() < job.start_before,
|
|
||||||
"UPDATE_PREFETCH_EXPIRED"
|
|
||||||
);
|
|
||||||
let length = CHUNK.min(artifact.bytes - offset);
|
|
||||||
let url = format!(
|
|
||||||
"{base}/agent/v1/update-artifacts/{}?job_id={}&attempt_id={}&offset={offset}&length={length}",
|
|
||||||
artifact.artifact_id, job.job_id, job.attempt_id
|
|
||||||
);
|
|
||||||
let mut response = client.get(&url).send().await?;
|
|
||||||
let partial = offset != 0 || length != artifact.bytes;
|
|
||||||
ensure!(
|
|
||||||
response.url().as_str() == url
|
|
||||||
&& response.status()
|
|
||||||
== if partial {
|
|
||||||
reqwest::StatusCode::PARTIAL_CONTENT
|
|
||||||
} else {
|
|
||||||
reqwest::StatusCode::OK
|
|
||||||
},
|
|
||||||
"UPDATE_PREFETCH_HTTP"
|
|
||||||
);
|
|
||||||
let h = response.headers();
|
|
||||||
ensure!(
|
|
||||||
h.get("x-artifact-sha256").and_then(|v| v.to_str().ok())
|
|
||||||
== Some(artifact.sha256.as_str())
|
|
||||||
&& h.get("content-type").and_then(|v| v.to_str().ok())
|
|
||||||
== Some("application/octet-stream")
|
|
||||||
&& !h.contains_key("content-encoding")
|
|
||||||
&& response.content_length() == Some(length),
|
|
||||||
"UPDATE_PREFETCH_HEADERS"
|
|
||||||
);
|
|
||||||
if partial {
|
|
||||||
ensure!(
|
|
||||||
h.get("content-range").and_then(|v| v.to_str().ok())
|
|
||||||
== Some(
|
|
||||||
format!(
|
|
||||||
"bytes {}-{}/{}",
|
|
||||||
offset,
|
|
||||||
offset + length - 1,
|
|
||||||
artifact.bytes
|
|
||||||
)
|
|
||||||
.as_str()
|
|
||||||
),
|
|
||||||
"UPDATE_PREFETCH_RANGE"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ensure!(!h.contains_key("content-range"), "UPDATE_PREFETCH_RANGE");
|
|
||||||
}
|
|
||||||
let mut bytes = Vec::with_capacity(length as usize);
|
|
||||||
while let Some(chunk) = response.chunk().await? {
|
|
||||||
ensure!(
|
|
||||||
bytes.len() + chunk.len() <= length as usize,
|
|
||||||
"UPDATE_PREFETCH_BODY_LIMIT"
|
|
||||||
);
|
|
||||||
bytes.extend_from_slice(&chunk);
|
|
||||||
}
|
|
||||||
ensure!(
|
|
||||||
bytes.len() == length as usize && Instant::now() < deadline,
|
|
||||||
"UPDATE_PREFETCH_BODY_LENGTH"
|
|
||||||
);
|
|
||||||
hash.update(&bytes);
|
|
||||||
file = tokio::task::spawn_blocking(move || -> Result<File> {
|
|
||||||
file.write_all(&bytes)?;
|
|
||||||
Ok(file)
|
|
||||||
})
|
|
||||||
.await??;
|
|
||||||
offset += length;
|
|
||||||
}
|
|
||||||
ensure!(
|
|
||||||
format!("{:x}", hash.finalize()) == artifact.sha256,
|
|
||||||
"UPDATE_PREFETCH_DIGEST"
|
|
||||||
);
|
|
||||||
let dir = folder.clone();
|
|
||||||
tokio::task::spawn_blocking(move || -> Result<()> {
|
|
||||||
file.sync_all()?;
|
|
||||||
drop(file);
|
|
||||||
fs::hard_link(&stage, &path)?;
|
|
||||||
fs::remove_file(stage)?;
|
|
||||||
File::open(dir)?.sync_all()?;
|
|
||||||
checked(&path, &artifact)
|
|
||||||
})
|
|
||||||
.await??;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
/// No Outcome is invented on acceptance; loss after write stays ambiguous.
|
|
||||||
pub fn handoff(binding: &Binding, request: &Request, grant: uuid::Uuid) -> Result<Accepted> {
|
|
||||||
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
|
||||||
.context("UPDATE_FULL_SOCKET_REQUIRED")?;
|
|
||||||
let pin =
|
|
||||||
std::env::var_os("RMM_FULL_MAINTENANCE_POLICY_FILE").context("UPDATE_FULL_PIN_REQUIRED")?;
|
|
||||||
let pin = control::GeneralPin::read(Path::new(&pin), binding)?;
|
|
||||||
ensure!(
|
|
||||||
pin.profile == "full_maintenance_v1",
|
|
||||||
"UPDATE_FULL_PROFILE_REQUIRED"
|
|
||||||
);
|
|
||||||
control::general_probe(Path::new(&socket), binding, &pin)?;
|
|
||||||
let ack: Accepted =
|
|
||||||
control::exchange(Path::new(&socket), request, Duration::from_secs(50), 4096)?;
|
|
||||||
ack.matches(request, grant)?;
|
|
||||||
Ok(ack)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Opaque public metadata authenticated by the current protected Full peer,
|
/// Opaque public metadata authenticated by the current protected Full peer,
|
||||||
/// with complete guarded history verified there. No caller JSON constructor.
|
/// with complete guarded history verified there. No caller JSON constructor.
|
||||||
@@ -342,51 +109,4 @@ impl Observer {
|
|||||||
self.cached()?;
|
self.cached()?;
|
||||||
self.record.clone()
|
self.record.clone()
|
||||||
}
|
}
|
||||||
pub fn capabilities(&self) -> Vec<String> {
|
|
||||||
let Some(value) = self
|
|
||||||
.cached()
|
|
||||||
.filter(|v| v.quality == rmm_domain::agent_update::ObservationQuality::Valid)
|
|
||||||
else {
|
|
||||||
return vec![];
|
|
||||||
};
|
|
||||||
let (Some(updater), Some(predecessor)) = (&value.updater, &value.predecessor) else {
|
|
||||||
return vec![];
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
APPLY_CAPABILITY.into(),
|
|
||||||
CHECK_CAPABILITY.into(),
|
|
||||||
"update_agent".into(),
|
|
||||||
"root:update_agent".into(),
|
|
||||||
"helper.root.v1".into(),
|
|
||||||
format!("updater.binary.sha256:{}", updater.binary_sha256),
|
|
||||||
format!("updater.policy.sha256:{}", updater.policy_sha256),
|
|
||||||
format!("helper.binary.sha256:{}", predecessor.helper_sha256),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
|
|
||||||
(|| -> Result<bool> {
|
|
||||||
ensure!(
|
|
||||||
unsafe { libc::geteuid() } == 993 && job.execution_identity == "root",
|
|
||||||
"UPDATE_AGENT_PRINCIPAL"
|
|
||||||
);
|
|
||||||
let Action::UpdateAgent { update } = &job.action else {
|
|
||||||
return Ok(false);
|
|
||||||
};
|
|
||||||
let observation = rmm_privileged_helper::update_admission::observe(
|
|
||||||
Path::new("/run/rmm-helper-maintenance/control.sock"),
|
|
||||||
binding,
|
|
||||||
Some(update.release_envelope.clone()),
|
|
||||||
Some(update.updater.keyring_generation),
|
|
||||||
)?;
|
|
||||||
Ok(observation.validate()
|
|
||||||
&& observation.quality == rmm_domain::agent_update::ObservationQuality::Valid
|
|
||||||
&& observation.predecessor.as_ref() == Some(&update.predecessor)
|
|
||||||
&& observation.updater.as_ref() == Some(&update.updater)
|
|
||||||
&& observation.candidate_previews.iter().any(|c| {
|
|
||||||
c.manifest_sha256 == update.manifest_sha256
|
|
||||||
&& c.peer_pin_transition == update.peer_pin_transition
|
|
||||||
}))
|
|
||||||
})()
|
|
||||||
.unwrap_or(false)
|
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-357
@@ -1,118 +1,7 @@
|
|||||||
//! Dedicated APT route: no fallback to generic helper, shell or SSH. Readiness
|
//! Passive APT observations for installations with a configured planning source.
|
||||||
//! is nonce/root-peer/identity/profile/stack pinned before advertising or use.
|
use anyhow::{Context, Result};
|
||||||
use anyhow::{Context, Result, ensure};
|
use rmm_privileged_helper::{Binding, readiness};
|
||||||
use rmm_domain::jobs::JobPayload;
|
use std::path::Path;
|
||||||
use rmm_privileged_helper::{Binding, Outcome, Request, apt as provider, readiness};
|
|
||||||
use std::{
|
|
||||||
ffi::OsString,
|
|
||||||
path::{Path, PathBuf},
|
|
||||||
};
|
|
||||||
|
|
||||||
pub fn socket_for(
|
|
||||||
job: &JobPayload,
|
|
||||||
general: Option<OsString>,
|
|
||||||
apt: Option<OsString>,
|
|
||||||
) -> Result<PathBuf> {
|
|
||||||
if job.action.full_maintenance() {
|
|
||||||
return Ok(PathBuf::from(
|
|
||||||
std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
|
||||||
.context("FULL_MAINTENANCE_SOCKET_NOT_CONFIGURED")?,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
select_socket(provider::is_apt_action(job), general, apt)
|
|
||||||
}
|
|
||||||
fn select_socket(
|
|
||||||
is_apt: bool,
|
|
||||||
general: Option<OsString>,
|
|
||||||
apt: Option<OsString>,
|
|
||||||
) -> Result<PathBuf> {
|
|
||||||
if is_apt {
|
|
||||||
let socket = PathBuf::from(apt.context("APT_HELPER_SOCKET_NOT_CONFIGURED")?);
|
|
||||||
ensure!(
|
|
||||||
socket == Path::new(readiness::SOCKET),
|
|
||||||
"APT_HELPER_SOCKET_PROFILE"
|
|
||||||
);
|
|
||||||
Ok(socket)
|
|
||||||
} else {
|
|
||||||
Ok(PathBuf::from(
|
|
||||||
general.context("GENERAL_HELPER_SOCKET_NOT_CONFIGURED")?,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn status(binding: &Binding) -> Result<readiness::Response> {
|
|
||||||
let path =
|
|
||||||
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_HELPER_PIN_NOT_CONFIGURED")?;
|
|
||||||
let pin = readiness::Pin::read(Path::new(&path), binding)?;
|
|
||||||
let socket =
|
|
||||||
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_HELPER_SOCKET_NOT_CONFIGURED")?;
|
|
||||||
readiness::probe(Path::new(&socket), binding, &pin)
|
|
||||||
}
|
|
||||||
fn recovery_status(binding: &Binding) -> Result<readiness::Response> {
|
|
||||||
let path =
|
|
||||||
std::env::var_os("RMM_APT_HELPER_PROOF_FILE").context("APT_RECOVERY_PIN_REQUIRED")?;
|
|
||||||
let pin = readiness::Pin::read(Path::new(&path), binding)?;
|
|
||||||
let socket =
|
|
||||||
std::env::var_os("RMM_APT_HELPER_SOCKET").context("APT_RECOVERY_SOCKET_REQUIRED")?;
|
|
||||||
readiness::planning_for_recovery(Path::new(&socket), binding, &pin)
|
|
||||||
}
|
|
||||||
pub fn capabilities_from(response: &readiness::Response) -> Vec<String> {
|
|
||||||
if response.profile != "apt_only" {
|
|
||||||
return vec![];
|
|
||||||
}
|
|
||||||
let mut result = vec![];
|
|
||||||
if response.fixture_acceptance_ready && !response.bootstrap_recipes.is_empty() {
|
|
||||||
result.push("apt_native_acceptance".into());
|
|
||||||
}
|
|
||||||
if !response.accepted_recipes.is_empty() {
|
|
||||||
result.push("ensure_package".into());
|
|
||||||
}
|
|
||||||
if response
|
|
||||||
.accepted_recipes
|
|
||||||
.iter()
|
|
||||||
.any(|r| r == provider::UPDATE_RECIPE)
|
|
||||||
{
|
|
||||||
result.push("apply_updates".into());
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
pub fn capabilities(binding: &Binding) -> Vec<String> {
|
|
||||||
let normal = status(binding)
|
|
||||||
.map(|s| {
|
|
||||||
let mut caps = capabilities_from(&s);
|
|
||||||
if !caps.is_empty() {
|
|
||||||
let roots: Vec<String> = caps.iter().map(|c| format!("root:{c}")).collect();
|
|
||||||
caps.extend(roots);
|
|
||||||
caps.extend([
|
|
||||||
"helper.root.v1".into(),
|
|
||||||
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
|
|
||||||
"apt.manifest.v2".into(),
|
|
||||||
]);
|
|
||||||
if s.fixture_acceptance_ready && !s.bootstrap_recipes.is_empty() {
|
|
||||||
caps.push("apt.native-acceptance.v1".into());
|
|
||||||
}
|
|
||||||
if !s.accepted_recipes.is_empty() {
|
|
||||||
caps.push("apt.native-accepted.v1".into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
caps
|
|
||||||
})
|
|
||||||
.unwrap_or_default();
|
|
||||||
if !normal.is_empty() {
|
|
||||||
return normal;
|
|
||||||
}
|
|
||||||
recovery_status(binding)
|
|
||||||
.map(|s| {
|
|
||||||
vec![
|
|
||||||
"apt_native_acceptance".into(),
|
|
||||||
"root:apt_native_acceptance".into(),
|
|
||||||
"helper.root.v1".into(),
|
|
||||||
format!("helper.policy.sha256:{}", s.provider_stack_sha256),
|
|
||||||
"apt.manifest.v2".into(),
|
|
||||||
"apt.native-acceptance.v1".into(),
|
|
||||||
]
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Called only by the periodic blocking inventory worker, never heartbeat or a
|
/// Called only by the periodic blocking inventory worker, never heartbeat or a
|
||||||
/// caller-selected live query. Failure retains honest unknown/not_configured.
|
/// caller-selected live query. Failure retains honest unknown/not_configured.
|
||||||
@@ -142,103 +31,6 @@ pub fn planning_observation(binding: Option<&Binding>) -> serde_json::Value {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn recipe_ready(job: &JobPayload, response: &readiness::Response) -> Result<()> {
|
|
||||||
ensure!(
|
|
||||||
job.execution_identity == "root" && provider::is_apt_action(job),
|
|
||||||
"APT_TYPED_ROOT_ACTION_REQUIRED"
|
|
||||||
);
|
|
||||||
let action = serde_json::to_value(&job.action)?;
|
|
||||||
let manifest: provider::AptExecutionManifest = serde_json::from_value(
|
|
||||||
action
|
|
||||||
.get("apt_manifest")
|
|
||||||
.context("APT_MANIFEST_NOT_CONFIGURED")?
|
|
||||||
.clone(),
|
|
||||||
)?;
|
|
||||||
manifest.resolved_apt_transaction.validate_fixture()?;
|
|
||||||
let recipe = &manifest.resolved_apt_transaction.recipe_id;
|
|
||||||
if let Some(reference) = &manifest.native_recovery {
|
|
||||||
let planning = response
|
|
||||||
.planning
|
|
||||||
.as_ref()
|
|
||||||
.context("APT_RECOVERY_PLANNING_REQUIRED")?;
|
|
||||||
planning.validate(chrono::Utc::now())?;
|
|
||||||
ensure!(
|
|
||||||
job.action.name() == "apt_native_acceptance"
|
|
||||||
&& manifest.schema_version == 4
|
|
||||||
&& manifest.action == "apt-native-acceptance"
|
|
||||||
&& planning.native_recovery.as_ref() == Some(reference)
|
|
||||||
&& planning.baseline_sha256 == manifest.resolved_apt_transaction.baseline_sha256
|
|
||||||
&& planning.status_fingerprint
|
|
||||||
== manifest.resolved_apt_transaction.status_fingerprint
|
|
||||||
&& planning.runtime_sha256 == manifest.runtime_sha256
|
|
||||||
&& planning.provider_sha256 == manifest.provider_sha256
|
|
||||||
&& planning.hook_sha256 == manifest.hook_sha256
|
|
||||||
&& planning.apt_config_sha256 == manifest.apt_config_sha256,
|
|
||||||
"APT_RECOVERY_FRESH_PLAN_BINDING"
|
|
||||||
);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
if job.action.name() == "apt_native_acceptance" {
|
|
||||||
ensure!(
|
|
||||||
manifest.action == "apt-native-acceptance"
|
|
||||||
&& response.fixture_acceptance_ready
|
|
||||||
&& response.bootstrap_recipes.contains(recipe),
|
|
||||||
"APT_FIXTURE_READINESS_REQUIRED"
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
ensure!(
|
|
||||||
manifest.action == "apt-execute" && response.accepted_recipes.contains(recipe),
|
|
||||||
"APT_NATIVE_ACCEPTANCE_REQUIRED"
|
|
||||||
);
|
|
||||||
ensure!(
|
|
||||||
job.action.name() != "apply_updates" || recipe == provider::UPDATE_RECIPE,
|
|
||||||
"APT_UPDATE_RECIPE_SCOPE"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
pub fn supported(binding: &Binding, job: &JobPayload) -> bool {
|
|
||||||
job_status(binding, job)
|
|
||||||
.and_then(|s| recipe_ready(job, &s))
|
|
||||||
.is_ok()
|
|
||||||
}
|
|
||||||
fn job_status(binding: &Binding, job: &JobPayload) -> Result<readiness::Response> {
|
|
||||||
if matches!(&job.action,rmm_domain::jobs::Action::AptNativeAcceptance{apt_manifest,..}if apt_manifest.native_recovery.is_some())
|
|
||||||
{
|
|
||||||
recovery_status(binding)
|
|
||||||
} else {
|
|
||||||
status(binding)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub fn invoke(binding: &Binding, job: &JobPayload, request: &Request) -> Result<Outcome> {
|
|
||||||
let socket = socket_for(
|
|
||||||
job,
|
|
||||||
std::env::var_os("RMM_HELPER_SOCKET"),
|
|
||||||
std::env::var_os("RMM_APT_HELPER_SOCKET"),
|
|
||||||
)?;
|
|
||||||
if provider::is_apt_action(job) {
|
|
||||||
recipe_ready(job, &job_status(binding, job)?)?;
|
|
||||||
}
|
|
||||||
rmm_privileged_helper::invoke(&socket, request, job.max_runtime_seconds)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invoke_with_control(
|
|
||||||
binding: &Binding,
|
|
||||||
job: &JobPayload,
|
|
||||||
request: &Request,
|
|
||||||
observe: impl FnMut() -> Result<()>,
|
|
||||||
) -> Result<Outcome> {
|
|
||||||
if !job.action.full_maintenance() {
|
|
||||||
return invoke(binding, job, request);
|
|
||||||
}
|
|
||||||
ensure!(
|
|
||||||
crate::helper_sync::general_supported(binding, job),
|
|
||||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
|
||||||
);
|
|
||||||
let socket = socket_for(job, None, None)?;
|
|
||||||
rmm_privileged_helper::invoke_controlled(&socket, request, job.max_runtime_seconds, observe)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -251,149 +43,4 @@ mod tests {
|
|||||||
assert!(observation["data"].is_null());
|
assert!(observation["data"].is_null());
|
||||||
assert!(observation.get("received_at").is_none());
|
assert!(observation.get("received_at").is_none());
|
||||||
}
|
}
|
||||||
#[test]
|
|
||||||
fn typed_actions_require_their_own_fixture_readiness_or_accepted_recipe() {
|
|
||||||
let id = uuid::Uuid::new_v4();
|
|
||||||
let now = chrono::Utc::now();
|
|
||||||
let tx = serde_json::json!({"schema_version":1,"recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","platform":"ubuntu-24.04-amd64",
|
|
||||||
"resolver_config_version":"rmm-apt-local-v1","no_reboot":true,"status_fingerprint":"a".repeat(64),"baseline_sha256":"b".repeat(64),
|
|
||||||
"packages":[{"name":"rmm-mvp-test","architecture":"all","old_version":null,"new_version":"1.0","origin":"rmm-test",
|
|
||||||
"sha256":rmm_domain::apt_transaction::INSTALL_SHA,"size":20672,
|
|
||||||
"archive_path":format!("/var/lib/rmm-apt-transaction/archives/{}.deb",rmm_domain::apt_transaction::INSTALL_SHA)}]});
|
|
||||||
let bytes = serde_json::to_vec(&tx).unwrap();
|
|
||||||
let manifest = serde_json::json!({"type":"rmm.apt.helper-action","schema_version":2,"action":"apt-native-acceptance","execution_profile":"dev-test",
|
|
||||||
"transaction_sha256":rmm_domain::jobs::hash(&bytes),"resolved_apt_transaction":tx,"transaction_bytes":bytes,
|
|
||||||
"provider_sha256":"a".repeat(64),"hook_sha256":"a".repeat(64),"apt_config_sha256":"a".repeat(64),"runtime_sha256":"a".repeat(64),"test_result_id":"fixture-test"});
|
|
||||||
let mut job:JobPayload=serde_json::from_value(serde_json::json!({"schema_version":1,"tenant_id":id,"asset_id":id,"agent_id":id,
|
|
||||||
"enrollment_generation":1,"assignment_version":1,"job_id":id,"attempt_id":id,"execution_identity":"root",
|
|
||||||
"not_before":now,"start_before":now+chrono::Duration::minutes(1),"max_runtime_seconds":300,"max_output_bytes":4096,
|
|
||||||
"action":{"action":"apt_native_acceptance","recipe_id":provider::INSTALL_RECIPE,"recipe_version":"1","apt_manifest":manifest}})).unwrap();
|
|
||||||
assert!(job.action.validate());
|
|
||||||
let identity = readiness::Identity {
|
|
||||||
tenant_id: id,
|
|
||||||
asset_id: id,
|
|
||||||
agent_id: id,
|
|
||||||
enrollment_generation: 1,
|
|
||||||
assignment_version: 1,
|
|
||||||
signing_key_id: "a".repeat(64),
|
|
||||||
};
|
|
||||||
let mut response = readiness::Response {
|
|
||||||
schema_version: 1,
|
|
||||||
challenge: id,
|
|
||||||
identity,
|
|
||||||
profile: "apt_only".into(),
|
|
||||||
provider_stack_sha256: "a".repeat(64),
|
|
||||||
fixture_acceptance_ready: true,
|
|
||||||
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
|
|
||||||
accepted_recipes: vec![],
|
|
||||||
ledger_device: 1,
|
|
||||||
ledger_inode: 2,
|
|
||||||
lock_device: 1,
|
|
||||||
lock_inode: 3,
|
|
||||||
planning: None,
|
|
||||||
};
|
|
||||||
recipe_ready(&job, &response).unwrap();
|
|
||||||
let mut normal = manifest;
|
|
||||||
normal["action"] = serde_json::json!("apt-execute");
|
|
||||||
job.action=serde_json::from_value(serde_json::json!({"action":"ensure_package","provider":"apt","package":"rmm-mvp-test","version":"1.0",
|
|
||||||
"architecture":"all","recipe_version":"1","installation_context":"system","recipe_id":provider::INSTALL_RECIPE,"apt_manifest":normal})).unwrap();
|
|
||||||
assert!(job.action.validate());
|
|
||||||
assert!(recipe_ready(&job, &response).is_err());
|
|
||||||
response.accepted_recipes = vec![provider::UPDATE_RECIPE.into()];
|
|
||||||
assert!(recipe_ready(&job, &response).is_err());
|
|
||||||
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
|
|
||||||
recipe_ready(&job, &response).unwrap();
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn apt_route_cannot_fall_back_to_general_or_a_caller_path() {
|
|
||||||
assert!(select_socket(true, Some("/run/general.sock".into()), None).is_err());
|
|
||||||
assert!(
|
|
||||||
select_socket(
|
|
||||||
true,
|
|
||||||
Some("/run/general.sock".into()),
|
|
||||||
Some("/tmp/fake.sock".into())
|
|
||||||
)
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
select_socket(
|
|
||||||
true,
|
|
||||||
Some("/run/general.sock".into()),
|
|
||||||
Some(readiness::SOCKET.into())
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
Path::new(readiness::SOCKET)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn bootstrap_readiness_never_claims_package_acceptance() {
|
|
||||||
let id = readiness::Identity {
|
|
||||||
tenant_id: uuid::Uuid::new_v4(),
|
|
||||||
asset_id: uuid::Uuid::new_v4(),
|
|
||||||
agent_id: uuid::Uuid::new_v4(),
|
|
||||||
enrollment_generation: 1,
|
|
||||||
assignment_version: 1,
|
|
||||||
signing_key_id: "a".repeat(64),
|
|
||||||
};
|
|
||||||
let mut response = readiness::Response {
|
|
||||||
schema_version: 1,
|
|
||||||
challenge: uuid::Uuid::new_v4(),
|
|
||||||
identity: id,
|
|
||||||
profile: "apt_only".into(),
|
|
||||||
provider_stack_sha256: "a".repeat(64),
|
|
||||||
fixture_acceptance_ready: true,
|
|
||||||
bootstrap_recipes: vec![provider::INSTALL_RECIPE.into()],
|
|
||||||
accepted_recipes: vec![],
|
|
||||||
ledger_device: 1,
|
|
||||||
ledger_inode: 2,
|
|
||||||
lock_device: 1,
|
|
||||||
lock_inode: 3,
|
|
||||||
planning: None,
|
|
||||||
};
|
|
||||||
assert_eq!(capabilities_from(&response), vec!["apt_native_acceptance"]);
|
|
||||||
response.accepted_recipes = vec![provider::INSTALL_RECIPE.into()];
|
|
||||||
assert!(!capabilities_from(&response).contains(&"apply_updates".into()));
|
|
||||||
response
|
|
||||||
.accepted_recipes
|
|
||||||
.push(provider::UPDATE_RECIPE.into());
|
|
||||||
assert!(capabilities_from(&response).contains(&"apply_updates".into()));
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn generic_script_never_uses_apt_socket() {
|
|
||||||
let now = chrono::Utc::now();
|
|
||||||
let id = uuid::Uuid::new_v4();
|
|
||||||
let job = JobPayload {
|
|
||||||
schema_version: 1,
|
|
||||||
tenant_id: id,
|
|
||||||
asset_id: id,
|
|
||||||
agent_id: id,
|
|
||||||
enrollment_generation: 1,
|
|
||||||
assignment_version: 1,
|
|
||||||
job_id: id,
|
|
||||||
attempt_id: id,
|
|
||||||
action: rmm_domain::jobs::Action::RunScript {
|
|
||||||
interpreter: "posix_sh".into(),
|
|
||||||
script_utf8: "true".into(),
|
|
||||||
arguments: vec![],
|
|
||||||
expected_stdout: None,
|
|
||||||
windows_execution_profile: None,
|
|
||||||
privileged_script_profile: None,
|
|
||||||
},
|
|
||||||
execution_identity: "root".into(),
|
|
||||||
not_before: now,
|
|
||||||
start_before: now + chrono::Duration::minutes(1),
|
|
||||||
max_runtime_seconds: 300,
|
|
||||||
max_output_bytes: 4096,
|
|
||||||
};
|
|
||||||
assert!(socket_for(&job, None, Some(readiness::SOCKET.into())).is_err());
|
|
||||||
assert_eq!(
|
|
||||||
socket_for(
|
|
||||||
&job,
|
|
||||||
Some("/run/general.sock".into()),
|
|
||||||
Some(readiness::SOCKET.into())
|
|
||||||
)
|
|
||||||
.unwrap(),
|
|
||||||
Path::new("/run/general.sock")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,16 +41,12 @@ fn map(s: &root::Snapshot) -> reconcile::HelperSnapshot {
|
|||||||
.collect(),
|
.collect(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn general(binding: &Binding, full: bool) -> Result<control::Response> {
|
fn script_helper(binding: &Binding) -> Result<control::Response> {
|
||||||
let (socket_name, pin_name, profile) = if full {
|
let (socket_name, pin_name, profile) = (
|
||||||
(
|
|
||||||
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
"RMM_FULL_MAINTENANCE_HELPER_SOCKET",
|
||||||
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
"RMM_FULL_MAINTENANCE_POLICY_FILE",
|
||||||
"full_maintenance_v1",
|
"full_maintenance_v1",
|
||||||
)
|
);
|
||||||
} else {
|
|
||||||
("RMM_HELPER_SOCKET", "RMM_HELPER_POLICY_FILE", "general")
|
|
||||||
};
|
|
||||||
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
|
let socket = std::env::var_os(socket_name).context("NO_GENERAL_HELPER")?;
|
||||||
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
let path = std::env::var_os(pin_name).context("GENERAL_POLICY_PIN_REQUIRED")?;
|
||||||
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
let pin = control::GeneralPin::read(Path::new(&path), binding)?;
|
||||||
@@ -207,97 +203,72 @@ impl Helpers {
|
|||||||
Ok(applied.as_ref().map(map))
|
Ok(applied.as_ref().map(map))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn general_capabilities(binding: &Binding) -> Vec<String> {
|
pub fn script_capabilities(binding: &Binding) -> Vec<String> {
|
||||||
let mut caps = profile_capabilities(binding, false);
|
|
||||||
caps.extend(profile_capabilities(binding, true));
|
|
||||||
caps.sort();
|
|
||||||
caps.dedup();
|
|
||||||
caps
|
|
||||||
}
|
|
||||||
fn profile_capabilities(binding: &Binding, full: bool) -> Vec<String> {
|
|
||||||
(|| -> Result<Vec<String>> {
|
(|| -> Result<Vec<String>> {
|
||||||
let response = general(binding, full)?;
|
let response = script_helper(binding)?;
|
||||||
let policy = response.policy.context("NO_GENERAL_POLICY")?;
|
let binary = response
|
||||||
let mut caps = vec![
|
|
||||||
"helper.root.v1".into(),
|
|
||||||
format!("helper.policy.sha256:{}", response.policy_sha256),
|
|
||||||
];
|
|
||||||
if full {
|
|
||||||
ensure!(
|
|
||||||
policy.schema_version == 2
|
|
||||||
&& policy.profile == "full_maintenance_v1"
|
|
||||||
&& policy.allowed_script_profiles.as_deref()
|
|
||||||
== Some(&[rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1]),
|
|
||||||
"FULL_MAINTENANCE_POLICY_REQUIRED"
|
|
||||||
);
|
|
||||||
let binary = policy
|
|
||||||
.helper_binary_sha256
|
.helper_binary_sha256
|
||||||
.as_ref()
|
.context("SCRIPT_HELPER_BINARY_PROOF_REQUIRED")?;
|
||||||
.context("FULL_MAINTENANCE_BINARY_PIN_REQUIRED")?;
|
|
||||||
ensure!(
|
ensure!(
|
||||||
response.helper_binary_sha256.as_ref() == Some(binary),
|
rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||||
"FULL_MAINTENANCE_BINARY_PROOF_REQUIRED"
|
"SCRIPT_INTERPRETER_UNAVAILABLE"
|
||||||
);
|
);
|
||||||
caps.push(format!("helper.binary.sha256:{binary}"));
|
let mut caps = vec![
|
||||||
caps.push(rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into());
|
"run_script".into(),
|
||||||
}
|
"root:run_script".into(),
|
||||||
let mut actions = vec![];
|
"helper.root.v1".into(),
|
||||||
if policy.allow_root_scripts && rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
rmm_domain::jobs::FULL_MAINTENANCE_CAPABILITY.into(),
|
||||||
actions.push("run_script");
|
format!("helper.policy.sha256:{}", response.policy_sha256),
|
||||||
}
|
format!("helper.binary.sha256:{binary}"),
|
||||||
if !policy.allowed_services.is_empty() {
|
];
|
||||||
actions.extend(["set_service_state", "query_logs"]);
|
if let Some(release) = std::env::var("RMM_SCRIPT_HELPER_RELEASE")
|
||||||
}
|
.ok()
|
||||||
if policy.allow_reboot {
|
.and_then(|value| Uuid::parse_str(&value).ok())
|
||||||
actions.push("reboot");
|
.filter(|id| !id.is_nil())
|
||||||
}
|
{
|
||||||
for action in actions {
|
caps.push(format!("script.helper.release:{release}"));
|
||||||
caps.push(action.into());
|
|
||||||
caps.push(format!("root:{action}"));
|
|
||||||
}
|
}
|
||||||
Ok(caps)
|
Ok(caps)
|
||||||
})()
|
})()
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
}
|
}
|
||||||
pub fn general_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
|
|
||||||
(|| -> Result<bool> {
|
pub fn script_supported(binding: &Binding, job: &rmm_domain::jobs::JobPayload) -> bool {
|
||||||
let p = general(binding, job.action.full_maintenance())?
|
let rmm_domain::jobs::Action::RunScript { interpreter, .. } = &job.action else {
|
||||||
.policy
|
return false;
|
||||||
.context("NO_GENERAL_POLICY")?;
|
};
|
||||||
Ok(match &job.action {
|
job.execution_identity == "root"
|
||||||
rmm_domain::jobs::Action::RunScript { interpreter, .. } => {
|
&& job.action.full_maintenance()
|
||||||
p.allow_root_scripts
|
|
||||||
&& job.action.valid_execution_identity(&job.execution_identity)
|
&& job.action.valid_execution_identity(&job.execution_identity)
|
||||||
&& job
|
&& job
|
||||||
.action
|
.action
|
||||||
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
.valid_job_limits(job.max_runtime_seconds, job.max_output_bytes)
|
||||||
&& (!job.action.full_maintenance()
|
|
||||||
|| p.allowed_script_profiles.as_ref().is_some_and(|v| {
|
|
||||||
v.contains(
|
|
||||||
&rmm_domain::jobs::PrivilegedScriptProfile::FullMaintenanceV1,
|
|
||||||
)
|
|
||||||
}))
|
|
||||||
&& match interpreter.as_str() {
|
&& match interpreter.as_str() {
|
||||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
|
&& script_helper(binding).is_ok()
|
||||||
}
|
}
|
||||||
rmm_domain::jobs::Action::SetServiceState { unit, state } => {
|
|
||||||
p.allowed_services.contains(unit)
|
pub fn invoke_script(
|
||||||
&& matches!(state.as_str(), "running" | "stopped")
|
binding: &Binding,
|
||||||
&& job.max_runtime_seconds >= 180
|
job: &rmm_domain::jobs::JobPayload,
|
||||||
}
|
request: &rmm_privileged_helper::Request,
|
||||||
rmm_domain::jobs::Action::QueryLogs { unit, .. } => {
|
observe: impl FnMut() -> Result<()>,
|
||||||
p.allowed_services.contains(unit) && job.max_runtime_seconds >= 20
|
) -> Result<rmm_privileged_helper::Outcome> {
|
||||||
}
|
ensure!(
|
||||||
rmm_domain::jobs::Action::Reboot { .. } => {
|
script_supported(binding, job),
|
||||||
p.allow_reboot && job.max_runtime_seconds >= 60
|
"SCRIPT_HELPER_POLICY_REQUIRED"
|
||||||
}
|
);
|
||||||
_ => false,
|
let socket = std::env::var_os("RMM_FULL_MAINTENANCE_HELPER_SOCKET")
|
||||||
})
|
.context("SCRIPT_HELPER_SOCKET_REQUIRED")?;
|
||||||
})()
|
rmm_privileged_helper::invoke_controlled(
|
||||||
.unwrap_or(false)
|
Path::new(&socket),
|
||||||
|
request,
|
||||||
|
job.max_runtime_seconds,
|
||||||
|
observe,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Helpers {
|
impl Helpers {
|
||||||
|
|||||||
+35
-215
@@ -1,183 +1,46 @@
|
|||||||
use anyhow::{Result, ensure};
|
use anyhow::Result;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use prost::Message;
|
use prost::Message;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use rmm_domain::jobs::hash;
|
use rmm_domain::jobs::hash;
|
||||||
use rmm_domain::jobs::{Action, JobPayload};
|
use rmm_domain::jobs::{Action, JobPayload};
|
||||||
use rmm_privileged_helper::{Binding, Outcome};
|
use rmm_privileged_helper::Binding;
|
||||||
use rmm_protocol::*;
|
use rmm_protocol::*;
|
||||||
use rusqlite::Connection;
|
use rusqlite::Connection;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub fn supported(job: &JobPayload) -> bool {
|
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
|
||||||
if rmm_privileged_helper::apt::is_apt_action(job) {
|
let Action::RunScript { interpreter, .. } = &job.action else {
|
||||||
// A configured environment path alone is never a capability proof.
|
return false;
|
||||||
// Caller binding is independently provisioned, not taken from the job.
|
};
|
||||||
|
if unsafe { libc::geteuid() } == 0
|
||||||
|
|| !job.action.valid_execution_identity(&job.execution_identity)
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// The network process must never execute a script with accidental root.
|
match job.execution_identity.as_str() {
|
||||||
supported_as(
|
"root" => {
|
||||||
job,
|
job.action.full_maintenance()
|
||||||
unsafe { libc::geteuid() },
|
&& binding.is_some_and(|b| crate::helper_sync::script_supported(b, job))
|
||||||
std::env::var_os("RMM_HELPER_SOCKET").is_some(),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
pub fn supported_with_binding(job: &JobPayload, binding: Option<&Binding>) -> bool {
|
"agent_service" => match interpreter.as_str() {
|
||||||
if matches!(job.action, Action::UpdateAgent { .. }) {
|
|
||||||
return binding.is_some_and(|b| crate::agent_update_apply::supported(b, job));
|
|
||||||
}
|
|
||||||
if rmm_privileged_helper::apt::is_apt_action(job) {
|
|
||||||
// SAFETY: geteuid has no preconditions.
|
|
||||||
return unsafe { libc::geteuid() } != 0
|
|
||||||
&& binding.is_some_and(|b| crate::apt::supported(b, job));
|
|
||||||
}
|
|
||||||
if job.execution_identity == "root" {
|
|
||||||
return unsafe { libc::geteuid() } != 0
|
|
||||||
&& binding.is_some_and(|b| crate::helper_sync::general_supported(b, job));
|
|
||||||
}
|
|
||||||
supported(job)
|
|
||||||
}
|
|
||||||
fn supported_as(job: &JobPayload, uid: u32, helper_configured: bool) -> bool {
|
|
||||||
let unprivileged = uid != 0;
|
|
||||||
if job.execution_identity == "root" && unprivileged {
|
|
||||||
return helper_configured
|
|
||||||
&& matches!(
|
|
||||||
job.action,
|
|
||||||
Action::RunScript { .. } | Action::SetServiceState { .. } | Action::Reboot { .. }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
job.execution_identity == "agent_service"
|
|
||||||
&& unprivileged
|
|
||||||
&& match &job.action {
|
|
||||||
Action::RunScript { interpreter, .. } => match interpreter.as_str() {
|
|
||||||
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
"posix_sh" => rmm_agent_linux::actions::Interpreter::PosixSh.available(),
|
||||||
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
"bash" => rmm_agent_linux::actions::Interpreter::Bash.available(),
|
||||||
_ => false,
|
_ => false,
|
||||||
},
|
},
|
||||||
Action::RefreshInventory { scope } => scope == "linux.base",
|
|
||||||
Action::QueryLogs { .. } => log_request(job).is_ok(),
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub use rmm_agent_core::jobs::{
|
pub use rmm_agent_core::jobs::{
|
||||||
denied_request, ack, event, events, interrupted, interrupted_request, next, no_start, permit_request,
|
ack, denied_request, event, events, interrupted, interrupted_request, next, no_start,
|
||||||
recover_interrupted_outcome, requesting, reserve_request, result, transition,
|
permit_request, recover_interrupted_outcome, requesting, reserve_request, result, transition,
|
||||||
};
|
};
|
||||||
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
|
pub fn accept(db: &Connection, binding: &Binding, offer: &JobOffer) -> Result<bool> {
|
||||||
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
|
rmm_agent_core::jobs::accept(db, binding, offer, |job| {
|
||||||
supported_with_binding(job, Some(binding))
|
supported_with_binding(job, Some(binding))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
pub fn execute(job: &JobPayload) -> Outcome {
|
|
||||||
let result = match &job.action {
|
|
||||||
Action::RunScript { .. } => rmm_privileged_helper::script(job),
|
|
||||||
Action::RefreshInventory { .. } => rmm_agent_linux::collect().and_then(|i| {
|
|
||||||
let bytes = serde_json::to_vec(&i)?;
|
|
||||||
ensure!(bytes.len() <= job.max_output_bytes as usize, "INVENTORY_OUTPUT_LIMIT");
|
|
||||||
Ok(Outcome { state: "succeeded".into(), stdout: bytes, stderr: vec![], exit_code: None,
|
|
||||||
output_truncated: false, reboot_required: false,
|
|
||||||
evidence: serde_json::json!({"postconditions_passed":true,"source_id":"linux.base","observed_at":chrono::Utc::now(),"completeness":"partial"}), error_code: String::new() })
|
|
||||||
}),
|
|
||||||
Action::QueryLogs { .. } => query_logs(job),
|
|
||||||
_ => Err(anyhow::anyhow!("unsupported action")),
|
|
||||||
};
|
|
||||||
result.unwrap_or_else(|_| Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn allowed_log_units() -> Result<Vec<rmm_agent_linux::actions::ServiceUnit>> {
|
|
||||||
let path = std::env::var_os("RMM_LOG_UNITS_FILE")
|
|
||||||
.ok_or_else(|| anyhow::anyhow!("LOG_ALLOWLIST_NOT_CONFIGURED"))?;
|
|
||||||
let path = std::path::Path::new(&path);
|
|
||||||
rmm_privileged_helper::private_path(path, unsafe { libc::geteuid() }, false)?;
|
|
||||||
ensure!(
|
|
||||||
std::fs::metadata(path)?.len() <= 32768,
|
|
||||||
"LOG_ALLOWLIST_SIZE"
|
|
||||||
);
|
|
||||||
let units: Vec<String> = serde_json::from_slice(&std::fs::read(path)?)?;
|
|
||||||
ensure!(
|
|
||||||
!units.is_empty() && units.len() <= 128,
|
|
||||||
"LOG_ALLOWLIST_SIZE"
|
|
||||||
);
|
|
||||||
units
|
|
||||||
.iter()
|
|
||||||
.map(|u| rmm_agent_linux::actions::ServiceUnit::new(u))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
pub fn logs_available() -> bool {
|
|
||||||
allowed_log_units().is_ok()
|
|
||||||
&& rmm_agent_linux::inventory::capabilities()
|
|
||||||
.get("logs.journald")
|
|
||||||
.is_some_and(|o| o.data == Some(true))
|
|
||||||
}
|
|
||||||
fn log_request(job: &JobPayload) -> Result<rmm_agent_linux::inventory::JournalRequest> {
|
|
||||||
log_request_for(job, &allowed_log_units()?)
|
|
||||||
}
|
|
||||||
fn log_request_for(
|
|
||||||
job: &JobPayload,
|
|
||||||
allowed: &[rmm_agent_linux::actions::ServiceUnit],
|
|
||||||
) -> Result<rmm_agent_linux::inventory::JournalRequest> {
|
|
||||||
let Action::QueryLogs {
|
|
||||||
unit,
|
|
||||||
since,
|
|
||||||
until,
|
|
||||||
max_lines,
|
|
||||||
} = &job.action
|
|
||||||
else {
|
|
||||||
anyhow::bail!("NOT_LOG_QUERY")
|
|
||||||
};
|
|
||||||
ensure!(job.max_runtime_seconds >= 20, "LOG_RUNTIME_TOO_SHORT");
|
|
||||||
rmm_agent_linux::inventory::JournalRequest::new(
|
|
||||||
rmm_agent_linux::actions::ServiceUnit::new(unit)?,
|
|
||||||
allowed,
|
|
||||||
u64::try_from(since.timestamp())?,
|
|
||||||
u64::try_from(until.timestamp())?,
|
|
||||||
*max_lines as usize,
|
|
||||||
(job.max_output_bytes as usize).min(256 * 1024),
|
|
||||||
)?
|
|
||||||
.precise_window(*since, *until)
|
|
||||||
}
|
|
||||||
fn query_logs(job: &JobPayload) -> Result<Outcome> {
|
|
||||||
let observation = rmm_agent_linux::inventory::query_journal(&log_request(job)?);
|
|
||||||
let valid = observation.quality == rmm_agent_linux::inventory::Quality::Valid;
|
|
||||||
let error = observation.error_code.clone().unwrap_or_default();
|
|
||||||
let mut value = serde_json::to_value(&observation)?;
|
|
||||||
while serde_json::to_vec(&value)?.len() > job.max_output_bytes as usize {
|
|
||||||
let Some(lines) = value["data"]["json_lines"]
|
|
||||||
.as_array_mut()
|
|
||||||
.filter(|v| !v.is_empty())
|
|
||||||
else {
|
|
||||||
return Ok(Outcome {
|
|
||||||
state: "failed".into(),
|
|
||||||
..Outcome::unknown("LOG_RESULT_METADATA_EXCEEDS_OUTPUT_LIMIT")
|
|
||||||
});
|
|
||||||
};
|
|
||||||
lines.remove(0);
|
|
||||||
value["truncated"] = serde_json::json!(true);
|
|
||||||
value["completeness"] = serde_json::json!("partial");
|
|
||||||
value["error_code"] = serde_json::json!("LOG_SERIALIZED_OUTPUT_LIMIT");
|
|
||||||
}
|
|
||||||
Ok(Outcome {
|
|
||||||
state: if valid { "succeeded" } else { "failed" }.into(),
|
|
||||||
stdout: serde_json::to_vec(&value)?,
|
|
||||||
stderr: vec![],
|
|
||||||
exit_code: None,
|
|
||||||
output_truncated: value["truncated"] == true,
|
|
||||||
reboot_required: false,
|
|
||||||
evidence: serde_json::json!({"postconditions_passed":valid,"source_id":observation.source_id,
|
|
||||||
"observed_at":value["observed_at"],"quality":value["quality"],"completeness":value["completeness"],
|
|
||||||
"cursor_status":"not_advanced_no_ack_contract","provider_error_code":error}),
|
|
||||||
error_code: if valid {
|
|
||||||
String::new()
|
|
||||||
} else if error.is_empty() {
|
|
||||||
"LOG_PROVIDER_UNAVAILABLE".into()
|
|
||||||
} else {
|
|
||||||
error
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
/// With no backend SyncResponse contract, a reconnect/restart cannot prove an
|
|
||||||
/// earlier reservation never started. Telemetry and evidence replay continue;
|
|
||||||
/// all new effects stop. Do not paper over this with a new start request.
|
/// all new effects stop. Do not paper over this with a new start request.
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
pub fn begin_session(db: &Connection) -> Result<bool> {
|
pub fn begin_session(db: &Connection) -> Result<bool> {
|
||||||
@@ -228,8 +91,13 @@ mod tests {
|
|||||||
assignment_version: 2,
|
assignment_version: 2,
|
||||||
job_id: Uuid::new_v4(),
|
job_id: Uuid::new_v4(),
|
||||||
attempt_id: Uuid::new_v4(),
|
attempt_id: Uuid::new_v4(),
|
||||||
action: Action::RefreshInventory {
|
action: Action::RunScript {
|
||||||
scope: "linux.base".into(),
|
interpreter: "posix_sh".into(),
|
||||||
|
script_utf8: "true".into(),
|
||||||
|
arguments: vec![],
|
||||||
|
expected_stdout: None,
|
||||||
|
windows_execution_profile: None,
|
||||||
|
privileged_script_profile: None,
|
||||||
},
|
},
|
||||||
execution_identity: "agent_service".into(),
|
execution_identity: "agent_service".into(),
|
||||||
not_before: now,
|
not_before: now,
|
||||||
@@ -254,7 +122,7 @@ mod tests {
|
|||||||
let mut db = storage::open(&path).unwrap();
|
let mut db = storage::open(&path).unwrap();
|
||||||
let job = binding.job(&offer.payload_bytes).unwrap();
|
let job = binding.job(&offer.payload_bytes).unwrap();
|
||||||
if unsafe { libc::geteuid() } == 0 {
|
if unsafe { libc::geteuid() } == 0 {
|
||||||
assert!(!supported(&job));
|
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||||
assert!(accept(&db, &binding, &offer).is_err());
|
assert!(accept(&db, &binding, &offer).is_err());
|
||||||
} else {
|
} else {
|
||||||
assert!(accept(&db, &binding, &offer).unwrap());
|
assert!(accept(&db, &binding, &offer).unwrap());
|
||||||
@@ -326,20 +194,24 @@ mod tests {
|
|||||||
std::fs::remove_dir_all(path).unwrap();
|
std::fs::remove_dir_all(path).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn network_process_never_executes_as_accidental_root() {
|
fn legacy_actions_and_unbound_root_are_rejected_before_any_reservation() {
|
||||||
let (path, binding, offer) = fixture();
|
let (path, binding, offer) = fixture();
|
||||||
let mut job = binding.job(&offer.payload_bytes).unwrap();
|
let mut job = binding.job(&offer.payload_bytes).unwrap();
|
||||||
assert!(!supported_as(&job, 0, false));
|
|
||||||
assert!(!supported_as(&job, 0, true));
|
|
||||||
job.execution_identity = "root".into();
|
job.execution_identity = "root".into();
|
||||||
assert!(!supported_as(&job, 1000, false));
|
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||||
assert!(!supported_as(&job, 0, true));
|
for identity in ["agent_service", "root"] {
|
||||||
|
job.execution_identity = identity.into();
|
||||||
job.action = Action::Reboot {
|
job.action = Action::Reboot {
|
||||||
reason: "explicit root only".into(),
|
reason: "legacy fixture".into(),
|
||||||
reconnect_timeout_seconds: 60,
|
reconnect_timeout_seconds: 60,
|
||||||
dependency_group: "test".into(),
|
dependency_group: "test".into(),
|
||||||
};
|
};
|
||||||
assert!(supported_as(&job, 1000, true));
|
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||||
|
job.action = Action::RefreshInventory {
|
||||||
|
scope: "linux.base".into(),
|
||||||
|
};
|
||||||
|
assert!(!supported_with_binding(&job, Some(&binding)));
|
||||||
|
}
|
||||||
std::fs::remove_dir_all(path).unwrap();
|
std::fs::remove_dir_all(path).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
@@ -363,56 +235,4 @@ mod tests {
|
|||||||
drop(db);
|
drop(db);
|
||||||
std::fs::remove_dir_all(path).unwrap();
|
std::fs::remove_dir_all(path).unwrap();
|
||||||
}
|
}
|
||||||
#[test]
|
|
||||||
fn live_logs_enforce_actual_action_window_allowlist_limits_and_runtime() {
|
|
||||||
let (path, binding, offer) = fixture();
|
|
||||||
let mut job = binding.job(&offer.payload_bytes).unwrap();
|
|
||||||
let unit = rmm_agent_linux::actions::ServiceUnit::new("rmm-test.service").unwrap();
|
|
||||||
let now = chrono::Utc::now();
|
|
||||||
job.max_runtime_seconds = 20;
|
|
||||||
job.action = Action::QueryLogs {
|
|
||||||
unit: unit.as_str().into(),
|
|
||||||
since: now - chrono::Duration::minutes(1),
|
|
||||||
until: now,
|
|
||||||
max_lines: 10,
|
|
||||||
};
|
|
||||||
assert!(log_request_for(&job, &[]).is_err());
|
|
||||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_ok());
|
|
||||||
job.max_runtime_seconds = 10;
|
|
||||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
|
||||||
job.max_runtime_seconds = 20;
|
|
||||||
job.action = Action::QueryLogs {
|
|
||||||
unit: unit.as_str().into(),
|
|
||||||
since: now - chrono::Duration::hours(25),
|
|
||||||
until: now,
|
|
||||||
max_lines: 10,
|
|
||||||
};
|
|
||||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
|
||||||
job.action = Action::QueryLogs {
|
|
||||||
unit: unit.as_str().into(),
|
|
||||||
since: now - chrono::Duration::minutes(1),
|
|
||||||
until: now,
|
|
||||||
max_lines: 1001,
|
|
||||||
};
|
|
||||||
assert!(log_request_for(&job, std::slice::from_ref(&unit)).is_err());
|
|
||||||
std::fs::remove_dir_all(path).unwrap();
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn refresh_is_a_new_measurement_with_real_observation_time() {
|
|
||||||
let (path, binding, offer) = fixture();
|
|
||||||
let job = binding.job(&offer.payload_bytes).unwrap();
|
|
||||||
let before = chrono::Utc::now();
|
|
||||||
let outcome = execute(&job);
|
|
||||||
assert_eq!(outcome.state, "succeeded");
|
|
||||||
let observed =
|
|
||||||
chrono::DateTime::parse_from_rfc3339(outcome.evidence["observed_at"].as_str().unwrap())
|
|
||||||
.unwrap();
|
|
||||||
assert!(observed >= before);
|
|
||||||
assert!(
|
|
||||||
serde_json::from_slice::<rmm_domain::Inventory>(&outcome.stdout)
|
|
||||||
.unwrap()
|
|
||||||
.validate()
|
|
||||||
);
|
|
||||||
std::fs::remove_dir_all(path).unwrap();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -425,15 +425,8 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
|| binding.verify(&request, Utc::now()).is_err()
|
|| binding.verify(&request, Utc::now()).is_err()
|
||||||
{
|
{
|
||||||
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
|
jobs::no_start("failed", "START_WINDOW_OR_CLOCK_INVALID_BEFORE_EFFECT")
|
||||||
} else if matches!(job.action, rmm_domain::jobs::Action::UpdateAgent { .. }) {
|
|
||||||
match agent_update_apply::handoff(&binding, &request, grant.grant_id) {
|
|
||||||
// Full now owns this original. The stable updater may
|
|
||||||
// stop us. Reconciliation alone supplies its final result.
|
|
||||||
Ok(_) => return,
|
|
||||||
Err(_) => rmm_privileged_helper::Outcome::unknown("UPDATE_HANDOFF_UNCONFIRMED"),
|
|
||||||
}
|
|
||||||
} else if job.execution_identity == "root" {
|
} else if job.execution_identity == "root" {
|
||||||
apt::invoke_with_control(&binding, &job, &request, || {
|
helper_sync::invoke_script(&binding, &job, &request, || {
|
||||||
ensure!(
|
ensure!(
|
||||||
!cancellation.load(Ordering::SeqCst)
|
!cancellation.load(Ordering::SeqCst)
|
||||||
&& fence.running_generation.load(Ordering::SeqCst) == generation
|
&& fence.running_generation.load(Ordering::SeqCst) == generation
|
||||||
@@ -446,7 +439,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
|
rmm_privileged_helper::Outcome::unknown("HELPER_TRANSPORT_EFFECT_UNKNOWN")
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
jobs::execute(&job)
|
rmm_privileged_helper::script(&job).unwrap_or_else(|_| rmm_privileged_helper::Outcome::unknown("EXECUTOR_EFFECT_UNKNOWN"))
|
||||||
};
|
};
|
||||||
let _ = completed.blocking_send((offer, grant, outcome));
|
let _ = completed.blocking_send((offer, grant, outcome));
|
||||||
});
|
});
|
||||||
@@ -481,15 +474,7 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
||||||
capabilities.push("run_script".into());
|
capabilities.push("run_script".into());
|
||||||
}
|
}
|
||||||
capabilities.push("refresh_inventory".into());
|
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||||
if jobs::logs_available() {
|
|
||||||
capabilities.push("query_logs".into());
|
|
||||||
}
|
|
||||||
capabilities.extend(apt::capabilities(binding));
|
|
||||||
capabilities.extend(helper_sync::general_capabilities(binding));
|
|
||||||
if self.clock.trusted() {
|
|
||||||
capabilities.extend(self.update_observer.capabilities());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
capabilities.sort();
|
capabilities.sort();
|
||||||
capabilities.dedup();
|
capabilities.dedup();
|
||||||
@@ -670,8 +655,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
let mut first_heartbeat = true;
|
let mut first_heartbeat = true;
|
||||||
let mut health_task: Option<PendingUpdateHealth> = None;
|
let mut health_task: Option<PendingUpdateHealth> = None;
|
||||||
let mut health_inventory_prefix: Option<String> = None;
|
let mut health_inventory_prefix: Option<String> = None;
|
||||||
let mut update_prefetch: Option<(JobOffer, agent_update_apply::Prefetch)> = None;
|
|
||||||
let mut prefetched = std::collections::HashSet::new();
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
Some(result) = self.inventory_rx.recv() => {
|
Some(result) = self.inventory_rx.recv() => {
|
||||||
@@ -748,7 +731,6 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
// First preserve the original completion without unlocking.
|
// First preserve the original completion without unlocking.
|
||||||
// A startup can replay it if the journal transaction is lost.
|
// A startup can replay it if the journal transaction is lost.
|
||||||
let state = outcome.state.clone();
|
let state = outcome.state.clone();
|
||||||
let refresh_capabilities=state=="succeeded" && serde_json::from_slice::<rmm_domain::jobs::JobPayload>(&offer.payload_bytes)?.action.name()=="apt_native_acceptance";
|
|
||||||
rmm_privileged_helper::persist_outcome(&self.ledger,&grant,&outcome)?;
|
rmm_privileged_helper::persist_outcome(&self.ledger,&grant,&outcome)?;
|
||||||
let serialized = serde_json::to_vec(&outcome)?;
|
let serialized = serde_json::to_vec(&outcome)?;
|
||||||
self.record(generation, &offer, &grant.grant_id.to_string(), outcome)?;
|
self.record(generation, &offer, &grant.grant_id.to_string(), outcome)?;
|
||||||
@@ -756,17 +738,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
rmm_privileged_helper::finish(&self.ledger, &grant, &outcome)?;
|
rmm_privileged_helper::finish(&self.ledger, &grant, &outcome)?;
|
||||||
if state == "unknown" { eprintln!("job effect unknown: device execution lock retained"); }
|
if state == "unknown" { eprintln!("job effect unknown: device execution lock retained"); }
|
||||||
needs_sync=true;self.replay(&ws, generation).await?;
|
needs_sync=true;self.replay(&ws, generation).await?;
|
||||||
if refresh_capabilities {return Ok(());}
|
|
||||||
}
|
}
|
||||||
_ = tick.tick() => {
|
_ = tick.tick() => {
|
||||||
self.replay(&ws, generation).await?;
|
self.replay(&ws, generation).await?;
|
||||||
if update_prefetch.as_ref().is_some_and(|(_,task)|task.0.is_finished()) {
|
|
||||||
let (offer, mut task)=update_prefetch.take().context("UPDATE_PREFETCH_REQUIRED")?;
|
|
||||||
match (&mut task.0).await {
|
|
||||||
Ok(Ok(())) => {prefetched.insert((offer.job_id.clone(),offer.attempt_id.clone()));},
|
|
||||||
_ => {self.record(generation,&offer,"",jobs::no_start("failed","UPDATE_ARTIFACT_PREFETCH_FAILED"))?;needs_sync=true;}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let busy:bool=self.db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get(0))?;
|
let busy:bool=self.db.query_row("SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN ('requesting','running','verifying'))",[],|r|r.get(0))?;
|
||||||
let update=self.update_proof()?;
|
let update=self.update_proof()?;
|
||||||
let pending_update=self.binding.as_ref().map(|binding|rmm_agent_core::jobs::needs_update_control(&self.db,&self.ledger,binding)).transpose()?.unwrap_or(false);
|
let pending_update=self.binding.as_ref().map(|binding|rmm_agent_core::jobs::needs_update_control(&self.db,&self.ledger,binding)).transpose()?.unwrap_or(false);
|
||||||
@@ -802,18 +776,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
|||||||
let job = self.binding.as_ref().context("binding")?.job(&offer.payload_bytes)?;
|
let job = self.binding.as_ref().context("binding")?.job(&offer.payload_bytes)?;
|
||||||
if Utc::now() >= job.start_before {
|
if Utc::now() >= job.start_before {
|
||||||
self.record(generation, &offer, "", jobs::no_start("expired", "START_DEADLINE_EXPIRED"))?;
|
self.record(generation, &offer, "", jobs::no_start("expired", "START_DEADLINE_EXPIRED"))?;
|
||||||
|
} else if !matches!(job.action,rmm_domain::jobs::Action::RunScript{..}) {
|
||||||
|
self.record(generation, &offer, "", jobs::no_start("failed","LEGACY_ACTION_RETIRED"))?;
|
||||||
} else if !self.ready(generation,job.execution_identity=="root") {
|
} else if !self.ready(generation,job.execution_identity=="root") {
|
||||||
needs_sync=true;
|
needs_sync=true;
|
||||||
} else if Utc::now() >= job.not_before {
|
} else if Utc::now() >= job.not_before {
|
||||||
if matches!(job.action,rmm_domain::jobs::Action::UpdateAgent{..}) && !prefetched.contains(&(offer.job_id.clone(),offer.attempt_id.clone())) {
|
|
||||||
if update_prefetch.is_none() {
|
|
||||||
let identity=self.certificates.current(Utc::now().timestamp())?;
|
|
||||||
let client=https_channel::mtls_client(self.address,&self.ca,&identity.certificate_pem,&identity.private_key_pem)?;
|
|
||||||
let base=format!("https://{}:{}",https_channel::server_name()?,self.address.port());
|
|
||||||
update_prefetch=Some((offer.clone(),agent_update_apply::Prefetch(tokio::spawn(agent_update_apply::prefetch(client,base,job)))));
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Reserve before send. A lost response must never cause
|
// Reserve before send. A lost response must never cause
|
||||||
// a second permit request for this attempt.
|
// a second permit request for this attempt.
|
||||||
// The root updater holds this lock exclusively while it checks
|
// The root updater holds this lock exclusively while it checks
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# Usage: sudo sh linux.sh https://bootstrap.example
|
# Usage: sudo sh linux.sh https://bootstrap.example [--enable-admin-scripts]
|
||||||
set -eu
|
set -eu
|
||||||
umask 077
|
umask 077
|
||||||
file=$(mktemp)
|
file=$(mktemp)
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
"""Bootstrap a Linux systemd client and maintain its signed release pair."""
|
"""Bootstrap a Linux systemd client and maintain its signed release pair."""
|
||||||
import argparse
|
import argparse
|
||||||
|
import contextlib
|
||||||
import datetime
|
import datetime
|
||||||
import fcntl
|
import fcntl
|
||||||
import getpass
|
import getpass
|
||||||
import hashlib
|
import hashlib
|
||||||
|
import io
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -14,6 +16,7 @@ import shutil
|
|||||||
import socket
|
import socket
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import ssl
|
import ssl
|
||||||
|
import stat
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -26,6 +29,9 @@ ROOT = Path('/opt/rust-discovery-client')
|
|||||||
STATE = Path('/var/lib/rmm-discovery')
|
STATE = Path('/var/lib/rmm-discovery')
|
||||||
SERVICE = 'rmm-discovery-agent.service'
|
SERVICE = 'rmm-discovery-agent.service'
|
||||||
TIMER = 'rmm-discovery-update.timer'
|
TIMER = 'rmm-discovery-update.timer'
|
||||||
|
HELPER = 'rmm-discovery-managed-script-helper.service'
|
||||||
|
HELPER_SOCKET = Path('/run/rmm-discovery-script-helper/control.sock')
|
||||||
|
OLD_HELPER_CONFIG = Path('/etc/rmm-discovery-managed-scripts')
|
||||||
PLATFORM = 'x86_64-unknown-linux-gnu'
|
PLATFORM = 'x86_64-unknown-linux-gnu'
|
||||||
MAX_BINARY = 256 * 1024 * 1024
|
MAX_BINARY = 256 * 1024 * 1024
|
||||||
UNIT_DIR = Path('/etc/systemd/system')
|
UNIT_DIR = Path('/etc/systemd/system')
|
||||||
@@ -177,7 +183,7 @@ def installed():
|
|||||||
return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout)
|
return json.loads(as_device('fetch', '/agent/v1/releases/installed', stdout=subprocess.PIPE).stdout)
|
||||||
|
|
||||||
|
|
||||||
def healthy(version, baseline, duration=90):
|
def healthy(version, baseline, duration=90, pin=None):
|
||||||
until = time.monotonic() + duration
|
until = time.monotonic() + duration
|
||||||
started = time.time()
|
started = time.time()
|
||||||
while time.monotonic() < until:
|
while time.monotonic() < until:
|
||||||
@@ -188,6 +194,8 @@ def healthy(version, baseline, duration=90):
|
|||||||
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
|
recent = datetime.datetime.fromisoformat(contact.replace('Z', '+00:00')).timestamp()
|
||||||
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
|
if (started - 1 <= recent <= time.time() + 10 and record['agent_version'] == version
|
||||||
and record['connection_generation'] > baseline
|
and record['connection_generation'] > baseline
|
||||||
|
and (pin is None or {'root:run_script', 'helper.policy.sha256:' + pin['policy_sha256'],
|
||||||
|
'helper.binary.sha256:' + pin['helper_binary_sha256']}.issubset(record['capabilities']))
|
||||||
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
|
and subprocess.run(['systemctl', 'is-active', '--quiet', SERVICE], timeout=10).returncode == 0):
|
||||||
return True
|
return True
|
||||||
except (subprocess.SubprocessError, ValueError, OSError):
|
except (subprocess.SubprocessError, ValueError, OSError):
|
||||||
@@ -200,6 +208,212 @@ def service(*args):
|
|||||||
subprocess.run(['systemctl', *args], check=True, timeout=60)
|
subprocess.run(['systemctl', *args], check=True, timeout=60)
|
||||||
|
|
||||||
|
|
||||||
|
def active_folder():
|
||||||
|
release = canonical_id(read(ROOT / 'current/manifest.json')['release_id'])
|
||||||
|
folder = ROOT / 'releases' / release
|
||||||
|
require((ROOT / 'current').resolve(strict=True) == folder and folder.resolve() == folder,
|
||||||
|
'unexpected active generation path')
|
||||||
|
return folder
|
||||||
|
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def account_file(path, uid):
|
||||||
|
# Open only a checked inode a second time for TLS. No privileged open of a
|
||||||
|
# device or FIFO, and no path re-resolution after validation.
|
||||||
|
fd = os.open(path, os.O_PATH | os.O_NOFOLLOW)
|
||||||
|
try:
|
||||||
|
info = os.fstat(fd)
|
||||||
|
require(stat.S_ISREG(info.st_mode) and info.st_uid == uid and info.st_nlink == 1
|
||||||
|
and info.st_mode & 0o077 == 0 and 0 < info.st_size <= 65536,
|
||||||
|
'device credential metadata differs')
|
||||||
|
yield Path('/proc/self/fd') / str(fd)
|
||||||
|
finally:
|
||||||
|
os.close(fd)
|
||||||
|
|
||||||
|
|
||||||
|
def script_binding(account):
|
||||||
|
# The root helper trusts only the signing key from the original HTTPS
|
||||||
|
# bootstrap and the binding returned by the authenticated device gateway.
|
||||||
|
boot = read(ROOT / 'bootstrap.json')
|
||||||
|
certs = STATE / 'certificates'
|
||||||
|
with account_file(certs / 'current.json', account.pw_uid) as selector:
|
||||||
|
version = canonical_id(read(selector)['version'])
|
||||||
|
creds = certs / 'versions' / version
|
||||||
|
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
context.load_verify_locations(cafile=str(ROOT / 'gateway-ca.pem'))
|
||||||
|
with (account_file(creds / 'device.pem', account.pw_uid) as cert,
|
||||||
|
account_file(creds / 'device.key', account.pw_uid) as key):
|
||||||
|
context.load_cert_chain(str(cert), str(key))
|
||||||
|
response = io.BytesIO()
|
||||||
|
conf = read(ROOT / 'config.json')
|
||||||
|
retrieve(conf['gateway'], '/agent/v1/releases/installed', response, context=context)
|
||||||
|
own = json.loads(response.getvalue())
|
||||||
|
public_key = boot.get('job_signing_public_key_hex')
|
||||||
|
if public_key is None:
|
||||||
|
trust = io.BytesIO()
|
||||||
|
retrieve(conf['gateway'], '/agent/v1/releases/device-trust', trust, context=context)
|
||||||
|
public_key = json.loads(trust.getvalue())['job_signing_public_key_hex']
|
||||||
|
require(re.fullmatch('[0-9a-f]{64}', public_key), 'invalid job signing key')
|
||||||
|
require(own['tenant_id'] == conf['tenant'] == boot['tenant_id'], 'device binding tenant mismatch')
|
||||||
|
binding = {field: canonical_id(own[field]) for field in ('tenant_id', 'asset_id', 'agent_id')}
|
||||||
|
for field in ('enrollment_generation', 'assignment_version'):
|
||||||
|
require(type(own[field]) is int and own[field] > 0, 'invalid device generation')
|
||||||
|
binding[field] = own[field]
|
||||||
|
binding['public_key_hex'] = public_key
|
||||||
|
return binding
|
||||||
|
|
||||||
|
|
||||||
|
def script_settings(binding, account, digest):
|
||||||
|
return dict(profile='full_maintenance_v1', binding=binding, agent_uid=account.pw_uid,
|
||||||
|
socket_gid=account.pw_gid, socket=str(HELPER_SOCKET), state='/var/lib/rmm-discovery-helper',
|
||||||
|
allowed_services=[], allow_reboot=False, allow_root_scripts=True,
|
||||||
|
allowed_script_profiles=['full_maintenance_v1'], helper_binary_sha256=digest)
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_script_helper(folder, binding, account):
|
||||||
|
manifest = json.loads(subprocess.check_output([
|
||||||
|
ROOT / 'updater', '--verify-bootstrap', ROOT / 'keyring.json', folder / 'envelope.json',
|
||||||
|
folder / 'agent', folder / 'helper'], timeout=120))
|
||||||
|
require(manifest == read(folder / 'manifest.json') and manifest['release_id'] == folder.name,
|
||||||
|
'helper generation differs from signed release')
|
||||||
|
digest = next(a['sha256'] for a in manifest['artifacts'] if a['role'] == 'helper')
|
||||||
|
settings = script_settings(binding, account, digest)
|
||||||
|
config = folder / 'script-helper.json'
|
||||||
|
if config.exists():
|
||||||
|
require(read(config) == settings, 'installed helper binding changed')
|
||||||
|
else:
|
||||||
|
save(config, settings, 0o600)
|
||||||
|
raw = subprocess.check_output([folder / 'helper', '--inspect-full-maintenance-profile'],
|
||||||
|
env={'PATH': '/usr/bin:/bin', 'RMM_HELPER_CONFIG': str(config)}, timeout=30)
|
||||||
|
pin = json.loads(raw)
|
||||||
|
require(pin['helper_binary_sha256'] == digest and re.fullmatch('[0-9a-f]{64}', pin['policy_sha256']),
|
||||||
|
'helper pin differs from signed release')
|
||||||
|
save(folder / 'script-pin.json', raw)
|
||||||
|
return pin
|
||||||
|
|
||||||
|
|
||||||
|
def helper_unit(executable, config=None):
|
||||||
|
command = f'Environment=RMM_HELPER_CONFIG={config}\n' if config else ''
|
||||||
|
return f"""[Unit]
|
||||||
|
Description=Rust Discovery helper for approved root scripts
|
||||||
|
After=time-sync.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=root
|
||||||
|
Group=rmm-discovery
|
||||||
|
StateDirectory=rmm-discovery-helper
|
||||||
|
StateDirectoryMode=0700
|
||||||
|
RuntimeDirectory=rmm-discovery-script-helper
|
||||||
|
RuntimeDirectoryMode=0750
|
||||||
|
UMask=0077
|
||||||
|
{command}ExecStart={executable}
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
""".encode()
|
||||||
|
|
||||||
|
|
||||||
|
def helper_unit_files(binding, account):
|
||||||
|
unit = UNIT_DIR / HELPER
|
||||||
|
dropdir = UNIT_DIR / (SERVICE + '.d')
|
||||||
|
dropdir.mkdir(mode=0o755, exist_ok=True)
|
||||||
|
require(not dropdir.is_symlink() and not dropdir.stat().st_mode & 0o022, 'unsafe service drop-in directory')
|
||||||
|
drop = dropdir / '50-managed-scripts.conf'
|
||||||
|
order = f'[Unit]\nAfter={HELPER}\n'.encode()
|
||||||
|
old_order = (f'[Unit]\nWants={HELPER}\nAfter={HELPER}\n'
|
||||||
|
f'\n[Service]\nEnvironment=RMM_FULL_MAINTENANCE_HELPER_SOCKET={HELPER_SOCKET}\n'
|
||||||
|
f'Environment=RMM_FULL_MAINTENANCE_POLICY_FILE={OLD_HELPER_CONFIG}/agent-pin.json\n').encode()
|
||||||
|
changed = []
|
||||||
|
for path, desired in (
|
||||||
|
(unit, helper_unit(f'/usr/bin/python3 -I {ROOT}/lifecycle.py run-helper')),
|
||||||
|
(drop, order),
|
||||||
|
):
|
||||||
|
if path.is_symlink():
|
||||||
|
raise ValueError('unexpected systemd symlink: ' + str(path))
|
||||||
|
if path.exists():
|
||||||
|
current = path.read_bytes()
|
||||||
|
if current == desired:
|
||||||
|
continue
|
||||||
|
old = old_order
|
||||||
|
if path == unit:
|
||||||
|
exe = re.search(rb'^ExecStart=(.+)$', current, re.M)
|
||||||
|
require(exe is not None, 'unrecognized helper service')
|
||||||
|
candidate = Path(os.fsdecode(exe[1]))
|
||||||
|
require(candidate == ROOT / 'releases' / canonical_id(candidate.parent.name) / 'helper',
|
||||||
|
'unexpected legacy helper image')
|
||||||
|
private = OLD_HELPER_CONFIG / 'helper.json'
|
||||||
|
old = helper_unit(candidate, private)
|
||||||
|
settings = read(private)
|
||||||
|
require(settings == script_settings(binding, account, settings['helper_binary_sha256']),
|
||||||
|
'existing helper belongs to a different binding or profile')
|
||||||
|
require(current == old, 'unrecognized managed service file: ' + str(path))
|
||||||
|
changed.append((path, desired))
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def start_pair():
|
||||||
|
service('start', HELPER)
|
||||||
|
until = time.monotonic() + 15
|
||||||
|
while not HELPER_SOCKET.is_socket():
|
||||||
|
require(time.monotonic() < until, 'script helper socket unavailable')
|
||||||
|
time.sleep(.2)
|
||||||
|
service('start', SERVICE)
|
||||||
|
|
||||||
|
|
||||||
|
def helper_state():
|
||||||
|
probe = subprocess.run(['systemctl', 'is-enabled', HELPER], stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.DEVNULL, text=True, timeout=10)
|
||||||
|
return probe.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def provision_scripts(enable_admin_scripts):
|
||||||
|
with (ROOT / 'release.lock').open('rb') as lock:
|
||||||
|
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||||
|
pending = ROOT / 'pending.json'
|
||||||
|
if pending.exists():
|
||||||
|
revert(read(pending))
|
||||||
|
folder = active_folder()
|
||||||
|
intent = ROOT / 'script-helper-installing.json'
|
||||||
|
state = helper_state()
|
||||||
|
known = (UNIT_DIR / HELPER).exists() or OLD_HELPER_CONFIG.exists() or (folder / 'script-helper.json').exists()
|
||||||
|
if state != 'enabled':
|
||||||
|
new = enable_admin_scripts and not known and state in ('', 'not-found')
|
||||||
|
resume = (enable_admin_scripts and intent.is_file() and read(intent) == folder.name
|
||||||
|
and state in ('', 'not-found', 'disabled'))
|
||||||
|
if not (new or resume):
|
||||||
|
print('Keeping the local script helper activation policy: ' + (state or 'not installed'), file=sys.stderr)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
require((UNIT_DIR / HELPER).is_file(), 'refusing to replace an externally managed helper unit')
|
||||||
|
require(as_device('idle', stdout=subprocess.PIPE).stdout.strip() == b'idle', 'active job prevents helper switch')
|
||||||
|
account = pwd.getpwnam('rmm-discovery')
|
||||||
|
require(account.pw_uid > 0 and account.pw_gid > 0, 'dedicated service account required')
|
||||||
|
binding = script_binding(account)
|
||||||
|
changed = helper_unit_files(binding, account)
|
||||||
|
if state != 'enabled':
|
||||||
|
save(intent, folder.name)
|
||||||
|
pin = prepare_script_helper(folder, binding, account)
|
||||||
|
observed = installed()
|
||||||
|
if (not changed and 'root:run_script' in observed['capabilities']
|
||||||
|
and 'helper.binary.sha256:' + pin['helper_binary_sha256'] in observed['capabilities']
|
||||||
|
and 'helper.policy.sha256:' + pin['policy_sha256'] in observed['capabilities']):
|
||||||
|
intent.unlink(missing_ok=True)
|
||||||
|
return
|
||||||
|
service('stop', SERVICE)
|
||||||
|
if (UNIT_DIR / HELPER).exists():
|
||||||
|
service('stop', HELPER)
|
||||||
|
for path, raw in changed:
|
||||||
|
save(path, raw)
|
||||||
|
service('daemon-reload')
|
||||||
|
service('enable', HELPER)
|
||||||
|
start_pair()
|
||||||
|
require(healthy(read(folder / 'manifest.json')['version'], observed['connection_generation'], pin=pin),
|
||||||
|
'device has not confirmed the script helper')
|
||||||
|
intent.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
def units():
|
def units():
|
||||||
program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py')
|
program = '/usr/bin/python3 -I ' + str(ROOT / 'lifecycle.py')
|
||||||
return {
|
return {
|
||||||
@@ -266,7 +480,7 @@ def save_token(base, token, gid):
|
|||||||
os.chown(path, 0, gid)
|
os.chown(path, 0, gid)
|
||||||
|
|
||||||
|
|
||||||
def install(base, token_file):
|
def install(base, token_file, enable_admin_scripts=False):
|
||||||
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
|
require(platform.machine() == 'x86_64', 'Linux x86-64 required')
|
||||||
base = origin(base)
|
base = origin(base)
|
||||||
if ROOT.exists():
|
if ROOT.exists():
|
||||||
@@ -288,8 +502,12 @@ def install(base, token_file):
|
|||||||
current = Path(__file__).read_bytes()
|
current = Path(__file__).read_bytes()
|
||||||
if harness.read_bytes() != current:
|
if harness.read_bytes() != current:
|
||||||
save(harness, current)
|
save(harness, current)
|
||||||
|
pending = ROOT / 'pending.json'
|
||||||
|
if pending.exists():
|
||||||
|
revert(read(pending), report_failure=False)
|
||||||
enable()
|
enable()
|
||||||
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
|
require(healthy(read(ROOT / 'current/manifest.json')['version'], 0), 'awaiting authenticated device heartbeat')
|
||||||
|
provision_scripts(enable_admin_scripts)
|
||||||
service('enable', '--now', TIMER)
|
service('enable', '--now', TIMER)
|
||||||
(ROOT / 'first.token').unlink(missing_ok=True)
|
(ROOT / 'first.token').unlink(missing_ok=True)
|
||||||
return
|
return
|
||||||
@@ -330,6 +548,7 @@ def install(base, token_file):
|
|||||||
os.rename(staging, ROOT)
|
os.rename(staging, ROOT)
|
||||||
enable()
|
enable()
|
||||||
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
|
require(healthy(manifest['version'], 0), 'installed, awaiting authenticated device heartbeat')
|
||||||
|
provision_scripts(enable_admin_scripts)
|
||||||
# OnBootSec may already be in the past on a running machine. The first
|
# OnBootSec may already be in the past on a running machine. The first
|
||||||
# timer check can run immediately once the device has reported its platform.
|
# timer check can run immediately once the device has reported its platform.
|
||||||
service('enable', '--now', TIMER)
|
service('enable', '--now', TIMER)
|
||||||
@@ -349,16 +568,31 @@ def run_agent():
|
|||||||
RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1',
|
RMM_ENROLLMENT_TENANT=conf['tenant'], RMM_JOB_SIGNING_KEY_BOOTSTRAP='1',
|
||||||
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
|
RMM_RELEASE_LOCK=str(ROOT / 'release.lock'),
|
||||||
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
|
RMM_INSTALLED_RELEASE_VERSION=read(ROOT / 'current/manifest.json')['version'])
|
||||||
exe = str(ROOT / 'current/agent')
|
folder = active_folder()
|
||||||
|
if (folder / 'script-pin.json').is_file() and helper_state() in ('enabled', 'enabled-runtime'):
|
||||||
|
os.environ.update(RMM_FULL_MAINTENANCE_HELPER_SOCKET=str(HELPER_SOCKET),
|
||||||
|
RMM_FULL_MAINTENANCE_POLICY_FILE=str(folder / 'script-pin.json'),
|
||||||
|
RMM_SCRIPT_HELPER_RELEASE=folder.name)
|
||||||
|
exe = str(folder / 'agent')
|
||||||
os.execv(exe, [exe])
|
os.execv(exe, [exe])
|
||||||
|
|
||||||
|
|
||||||
def revert(intent):
|
def revert(intent, report_failure=True):
|
||||||
# Persist failed sequence before restoring. An interruption re-enters recovery.
|
# Persist failed sequence before restoring. An interruption re-enters recovery.
|
||||||
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
|
save(ROOT / 'failed.json', {'release_sequence': intent['sequence'], 'reason': 'activation_unconfirmed'})
|
||||||
|
enabled = intent.get('script_helper') and helper_state() in ('enabled', 'enabled-runtime')
|
||||||
|
if intent.get('script_helper'):
|
||||||
|
service('stop', SERVICE, HELPER)
|
||||||
link(ROOT, intent['previous'])
|
link(ROOT, intent['previous'])
|
||||||
|
if enabled:
|
||||||
|
start_pair()
|
||||||
|
previous = active_folder()
|
||||||
|
require(healthy(read(previous / 'manifest.json')['version'], 0, pin=read(previous / 'script-pin.json')),
|
||||||
|
'predecessor has not yet confirmed the previous script helper')
|
||||||
|
else:
|
||||||
service('restart', SERVICE)
|
service('restart', SERVICE)
|
||||||
(ROOT / 'pending.json').unlink()
|
(ROOT / 'pending.json').unlink()
|
||||||
|
if report_failure:
|
||||||
raise RuntimeError('release activation unconfirmed; predecessor selected')
|
raise RuntimeError('release activation unconfirmed; predecessor selected')
|
||||||
|
|
||||||
|
|
||||||
@@ -401,10 +635,28 @@ def update():
|
|||||||
(staging / 'current.json').unlink()
|
(staging / 'current.json').unlink()
|
||||||
os.rename(staging, dest)
|
os.rename(staging, dest)
|
||||||
intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']}
|
intent = {'previous': active['release_id'], 'sequence': manifest['release_sequence']}
|
||||||
|
active_config = active_folder() / 'script-helper.json'
|
||||||
|
pin = None
|
||||||
|
if active_config.exists() and helper_state() in ('enabled', 'enabled-runtime'):
|
||||||
|
settings = read(active_config)
|
||||||
|
account = pwd.getpwnam('rmm-discovery')
|
||||||
|
active_hash = next(a['sha256'] for a in active['artifacts'] if a['role'] == 'helper')
|
||||||
|
require(settings == script_settings(settings['binding'], account, active_hash),
|
||||||
|
'existing script helper policy changed')
|
||||||
|
pin = prepare_script_helper(dest, settings['binding'], account)
|
||||||
|
intent['script_helper'] = True
|
||||||
save(pending, intent)
|
save(pending, intent)
|
||||||
|
try:
|
||||||
|
if pin:
|
||||||
|
service('stop', SERVICE, HELPER)
|
||||||
link(ROOT, release)
|
link(ROOT, release)
|
||||||
|
if pin:
|
||||||
|
start_pair()
|
||||||
|
else:
|
||||||
service('restart', SERVICE)
|
service('restart', SERVICE)
|
||||||
if not healthy(manifest['version'], previous_health['connection_generation']):
|
except (OSError, ValueError, subprocess.SubprocessError):
|
||||||
|
revert(intent)
|
||||||
|
if not healthy(manifest['version'], previous_health['connection_generation'], pin=pin):
|
||||||
revert(intent)
|
revert(intent)
|
||||||
pending.unlink()
|
pending.unlink()
|
||||||
(ROOT / 'first.token').unlink(missing_ok=True)
|
(ROOT / 'first.token').unlink(missing_ok=True)
|
||||||
@@ -412,18 +664,25 @@ def update():
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'fetch', 'idle'))
|
parser.add_argument('action', choices=('install', 'update', 'run-agent', 'run-helper', 'fetch', 'idle'))
|
||||||
parser.add_argument('values', nargs='*')
|
parser.add_argument('values', nargs='*')
|
||||||
parser.add_argument('--token-file')
|
parser.add_argument('--token-file')
|
||||||
|
parser.add_argument('--enable-admin-scripts', action='store_true',
|
||||||
|
help='enable this enrolled device to run individually approved root scripts')
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if args.action in ('install', 'update'):
|
if args.action in ('install', 'update'):
|
||||||
require(os.geteuid() == 0, 'administrative installation required')
|
require(os.geteuid() == 0, 'administrative installation required')
|
||||||
os.umask(0o022)
|
os.umask(0o022)
|
||||||
if args.action == 'install':
|
if args.action == 'install':
|
||||||
require(len(args.values) == 1, 'one HTTPS bootstrap origin required')
|
require(len(args.values) == 1, 'one HTTPS bootstrap origin required')
|
||||||
install(args.values[0], args.token_file)
|
install(args.values[0], args.token_file, args.enable_admin_scripts)
|
||||||
elif args.action == 'update':
|
elif args.action == 'update':
|
||||||
update()
|
update()
|
||||||
|
elif args.action == 'run-helper':
|
||||||
|
require(os.geteuid() == 0, 'privileged script helper service required')
|
||||||
|
folder = active_folder()
|
||||||
|
os.environ['RMM_HELPER_CONFIG'] = str(folder / 'script-helper.json')
|
||||||
|
os.execv(folder / 'helper', [str(folder / 'helper')])
|
||||||
elif args.action == 'run-agent':
|
elif args.action == 'run-agent':
|
||||||
run_agent()
|
run_agent()
|
||||||
elif args.action == 'fetch':
|
elif args.action == 'fetch':
|
||||||
|
|||||||
+5
-3
@@ -73,13 +73,15 @@ Im Releasekatalog der WebUI unter **Neues Gerät aufnehmen** einen Einmalcode er
|
|||||||
|
|
||||||
Im aktuellen Windows-Entwicklungsmandanten den angebotenen Aufruf mit `-Platform x86_64-pc-windows-gnu` aus der WebUI übernehmen. Windows verwendet den LocalService-Agenten und den separaten Dienst `RmmDiscoveryReleasePull` für die periodische Prüfung.
|
Im aktuellen Windows-Entwicklungsmandanten den angebotenen Aufruf mit `-Platform x86_64-pc-windows-gnu` aus der WebUI übernehmen. Windows verwendet den LocalService-Agenten und den separaten Dienst `RmmDiscoveryReleasePull` für die periodische Prüfung.
|
||||||
|
|
||||||
Auf Linux startet `rmm-discovery-agent.service` als Systemkonto `rmm-discovery` mit eigenem Zustand in `/var/lib/rmm-discovery`. `rmm-discovery-update.timer` prüft nach dem Booten und anschließend alle fünf Minuten den Releasebestand. Die aktive Generation und ein bei fehlgeschlagener Aktivierung gespeicherter Fehler liegen unter `/opt/rust-discovery-client`. Der Lauf berücksichtigt belegte Jobs, verifiziert den signierten Inhalt, schaltet die Generation um und prüft die neue Geräteverbindung. Das Systemjournal von `rmm-discovery-update.service` enthält die Fehlermeldung. Der Linux-Produktinstaller startet den unprivilegierten Agenten. Die Freigabe und gerätespezifische Provisionierung des privilegierten Wartungshelpers bleibt eine eigene Verwaltungshandlung.
|
Auf Linux startet `rmm-discovery-agent.service` als Systemkonto `rmm-discovery` mit eigenem Zustand in `/var/lib/rmm-discovery`. `rmm-discovery-update.timer` prüft nach dem Booten und anschließend alle fünf Minuten den Releasebestand. Die aktive Generation und ein bei fehlgeschlagener Aktivierung gespeicherter Fehler liegen unter `/opt/rust-discovery-client`. Der Lauf berücksichtigt belegte Jobs, verifiziert den signierten Inhalt, schaltet die Generation um und prüft die neue Geräteverbindung. Das Systemjournal von `rmm-discovery-update.service` enthält die Fehlermeldung. Der Linux-Produktinstaller startet den unprivilegierten Agenten. Für Root-Skripte aktiviert ein lokaler Administrator einmalig den an dieses Gerät gebundenen Helferdienst. Dazu den aus der WebUI geladenen Installer mit `sudo sh linux.sh https://discovery.ease-technologies.de:8443 --enable-admin-scripts` ausführen. Bei einem abweichenden Bootstrap-Origin die von der WebUI angezeigte HTTPS-Adresse einsetzen. Der Schalter funktioniert auch nach der Aufnahme mit der vorhandenen Geräteidentität. Ohne diesen Schalter bleibt ein bisheriges Dienstkonto-Gerät beim Dienstkonto. Die WebUI-Genehmigung des konkreten Skripts und die Berechtigungen auf dem Server gelten bei jedem Auftrag.
|
||||||
|
|
||||||
|
Der Helferdienst `rmm-discovery-managed-script-helper.service` verwendet den Helper aus demselben signierten Release wie der Agent. Der Installer übernimmt einen bereits ausdrücklich eingerichteten, dauerhaft aktivierten Skripthelfer nur mit übereinstimmender Gerätebindung und Skriptrichtlinie. Für diese Migration den aktuellen HTTPS-Installer auf dem eingeschriebenen Gerät erneut ausführen. Die nächste periodische Aktualisierung schaltet Agent, Helper und die zugehörigen Prüfdaten gemeinsam um. Bei fehlgeschlagener Aktivierung prüft der Updater die Rückkehr des vorherigen Paares. Eine bestehende lokale Deaktivierung, Maskierung oder abweichende Richtlinie bleibt wirksam.
|
||||||
|
|
||||||
Ein geänderter stabiler Bootstrap-Updater wird ausdrücklich je Mandant rotiert. Dazu beim Veröffentlichen des geprüften neuen Builds `--rotate-bootstrap-from <bisheriger SHA-256>` ergänzen. Für den Windows-GNU-Worker mit Skript-/Updatesperre verlangt der signierte Release zusätzlich `--minimum-updater-version 2`. Der Befehl lädt den neuen Worker zunächst über die Katalog-API hoch, vergleicht das gespeicherte Objekt und den bisherigen Mandantenpin und schaltet anschließend auf den neuen Hash um. Bereits ausgestellte Installer können den vorher erhaltenen Hash noch 15 Minuten lang abrufen. Weitere Releases desselben Workerstands verwenden nur `--minimum-updater-version 2`. Bestehende Geräte mit älterer stabiler Prüferdatei verwerfen ein Release, dessen signierte Mindestversion ihre eigene Prüferfähigkeit übersteigt.
|
Ein geänderter stabiler Bootstrap-Updater wird ausdrücklich je Mandant rotiert. Dazu beim Veröffentlichen des geprüften neuen Builds `--rotate-bootstrap-from <bisheriger SHA-256>` ergänzen. Für den Windows-GNU-Worker mit Skript-/Updatesperre verlangt der signierte Release zusätzlich `--minimum-updater-version 2`. Der Befehl lädt den neuen Worker zunächst über die Katalog-API hoch, vergleicht das gespeicherte Objekt und den bisherigen Mandantenpin und schaltet anschließend auf den neuen Hash um. Bereits ausgestellte Installer können den vorher erhaltenen Hash noch 15 Minuten lang abrufen. Weitere Releases desselben Workerstands verwenden nur `--minimum-updater-version 2`. Bestehende Geräte mit älterer stabiler Prüferdatei verwerfen ein Release, dessen signierte Mindestversion ihre eigene Prüferfähigkeit übersteigt.
|
||||||
|
|
||||||
## Bestehenden verwalteten Linux-Helper auf eine neue Releaseversion umstellen
|
## Historischer manueller Linux-Helperwechsel
|
||||||
|
|
||||||
Auf der Entwicklungs-VM verweist die Unit `rmm-discovery-managed-script-helper.service` auf den absoluten Pfad der bisherigen signierten Releaseversion. Für den gemeinsamen Versionswechsel vor der Katalogveröffentlichung den aktiven Release aus `/opt/rust-discovery-client/current` erfassen, `rmm-discovery-update.timer` mit systemd stoppen und den Abschluss eines laufenden Update-Dienstes abwarten. Das neue Paar veröffentlichen, den regulären `rmm-discovery-update.service` einmal starten und seine erfolgreich aktivierte Release-ID prüfen.
|
Für Systeme vor der Migration auf den aktuellen HTTPS-Installer gilt das frühere Verfahren. Auf der Entwicklungs-VM verwies die Unit `rmm-discovery-managed-script-helper.service` auf den absoluten Pfad der bisherigen signierten Releaseversion. Für den gemeinsamen Versionswechsel vor der Katalogveröffentlichung den aktiven Release aus `/opt/rust-discovery-client/current` erfassen, `rmm-discovery-update.timer` mit systemd stoppen und den Abschluss eines laufenden Update-Dienstes abwarten. Das neue Paar veröffentlichen, den regulären `rmm-discovery-update.service` einmal starten und seine erfolgreich aktivierte Release-ID prüfen.
|
||||||
|
|
||||||
Vom Entwicklungsrechner den [Helperwechsel](../tools/dev_linux_helper_rollover.py) zuerst mit `check` und dann mit `switch` aufrufen. Beide Aufrufe erwarten `--tenant UUID --asset UUID --agent UUID --previous ALTE_RELEASE_UUID --current NEUE_RELEASE_UUID`. Der Befehl prüft beide signierten Paare, den vorhandenen Systemdienst, die lokale Gerätebindung und genau einen passenden bestehenden Serverscope. Unter der lokalen Auftrags- und Releasesperre aktualisiert er Helperprofil, Agentpin und Unit-Ziel. Ein neuer authentisierter Kontakt muss beide erwarteten Helperhashes und einen bereiten Abgleich melden. Erst dann ersetzt der Operator im vorhandenen Serverscope die beiden Hashwerte. Principals, erlaubte Aktionen, übrige Geräte und Kunden bleiben erhalten.
|
Vom Entwicklungsrechner den [Helperwechsel](../tools/dev_linux_helper_rollover.py) zuerst mit `check` und dann mit `switch` aufrufen. Beide Aufrufe erwarten `--tenant UUID --asset UUID --agent UUID --previous ALTE_RELEASE_UUID --current NEUE_RELEASE_UUID`. Der Befehl prüft beide signierten Paare, den vorhandenen Systemdienst, die lokale Gerätebindung und genau einen passenden bestehenden Serverscope. Unter der lokalen Auftrags- und Releasesperre aktualisiert er Helperprofil, Agentpin und Unit-Ziel. Ein neuer authentisierter Kontakt muss beide erwarteten Helperhashes und einen bereiten Abgleich melden. Erst dann ersetzt der Operator im vorhandenen Serverscope die beiden Hashwerte. Principals, erlaubte Aktionen, übrige Geräte und Kunden bleiben erhalten.
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import json
|
|||||||
import sqlite3
|
import sqlite3
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import tempfile
|
import tempfile
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import subprocess
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
@@ -33,6 +35,7 @@ class EnrollmentRetry(unittest.TestCase):
|
|||||||
for field, value in [('ROOT',root),('STATE',self.state)]:
|
for field, value in [('ROOT',root),('STATE',self.state)]:
|
||||||
self.stack.enter_context(patch.object(lifecycle,field,value))
|
self.stack.enter_context(patch.object(lifecycle,field,value))
|
||||||
self.enable = self.stack.enter_context(patch.object(lifecycle,'enable'))
|
self.enable = self.stack.enter_context(patch.object(lifecycle,'enable'))
|
||||||
|
self.provision = self.stack.enter_context(patch.object(lifecycle,'provision_scripts'))
|
||||||
self.service = self.stack.enter_context(patch.object(lifecycle,'service'))
|
self.service = self.stack.enter_context(patch.object(lifecycle,'service'))
|
||||||
self.healthy = self.stack.enter_context(patch.object(lifecycle,'healthy',return_value=True))
|
self.healthy = self.stack.enter_context(patch.object(lifecycle,'healthy',return_value=True))
|
||||||
self.save = self.stack.enter_context(patch.object(lifecycle,'save_token'))
|
self.save = self.stack.enter_context(patch.object(lifecycle,'save_token'))
|
||||||
@@ -69,6 +72,7 @@ class EnrollmentRetry(unittest.TestCase):
|
|||||||
remote.assert_not_called()
|
remote.assert_not_called()
|
||||||
self.save.assert_not_called()
|
self.save.assert_not_called()
|
||||||
self.enable.assert_called_once()
|
self.enable.assert_called_once()
|
||||||
|
self.provision.assert_called_once_with(False)
|
||||||
|
|
||||||
def test_expired_initial_token_can_be_replaced_in_same_tenant(self):
|
def test_expired_initial_token_can_be_replaced_in_same_tenant(self):
|
||||||
self.bootstrap_tenant(self.tenant)
|
self.bootstrap_tenant(self.tenant)
|
||||||
@@ -83,8 +87,10 @@ class EnrollmentRetry(unittest.TestCase):
|
|||||||
lifecycle.install(self.base,self.token)
|
lifecycle.install(self.base,self.token)
|
||||||
self.enable.assert_called_once()
|
self.enable.assert_called_once()
|
||||||
self.service.assert_not_called()
|
self.service.assert_not_called()
|
||||||
|
self.provision.assert_not_called()
|
||||||
self.healthy.return_value = True
|
self.healthy.return_value = True
|
||||||
lifecycle.install(self.base,self.token)
|
lifecycle.install(self.base,self.token,enable_admin_scripts=True)
|
||||||
|
self.provision.assert_called_once_with(True)
|
||||||
self.service.assert_called_once_with('enable','--now',lifecycle.TIMER)
|
self.service.assert_called_once_with('enable','--now',lifecycle.TIMER)
|
||||||
|
|
||||||
def test_token_for_another_tenant_cannot_replace_initial_token(self):
|
def test_token_for_another_tenant_cannot_replace_initial_token(self):
|
||||||
@@ -96,5 +102,97 @@ class EnrollmentRetry(unittest.TestCase):
|
|||||||
self.assertEqual((lifecycle.ROOT / 'lifecycle.py').read_bytes(), b'previous installer')
|
self.assertEqual((lifecycle.ROOT / 'lifecycle.py').read_bytes(), b'previous installer')
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptHelperInstallation(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.stack = ExitStack()
|
||||||
|
self.addCleanup(self.stack.close)
|
||||||
|
base = Path(self.stack.enter_context(tempfile.TemporaryDirectory()))
|
||||||
|
self.root = base / 'client'
|
||||||
|
self.units = base / 'units'
|
||||||
|
self.old = base / 'old-config'
|
||||||
|
self.units.mkdir()
|
||||||
|
self.uid = SimpleNamespace(pw_uid=990,pw_gid=990)
|
||||||
|
self.release = '11111111-1111-4111-8111-111111111111'
|
||||||
|
self.previous = '22222222-2222-4222-8222-222222222222'
|
||||||
|
self.folder = self.root / 'releases' / self.release
|
||||||
|
self.folder.mkdir(parents=True)
|
||||||
|
self.manifest = {'release_id': self.release, 'version': 'v2', 'artifacts':[{'role':'helper','sha256':'a'*64}]}
|
||||||
|
self.binding = {'tenant_id':self.previous, 'agent_id':self.release, 'public_key_hex':'f'*64}
|
||||||
|
self.pin = {'helper_binary_sha256':'a'*64,'policy_sha256':'b'*64}
|
||||||
|
lifecycle.save(self.folder / 'manifest.json', self.manifest)
|
||||||
|
(self.root / 'release.lock').touch()
|
||||||
|
for field, value in [('ROOT',self.root),('UNIT_DIR',self.units),('OLD_HELPER_CONFIG',self.old)]:
|
||||||
|
self.stack.enter_context(patch.object(lifecycle,field,value))
|
||||||
|
lifecycle.link(self.root, self.release)
|
||||||
|
self.unit = self.units / lifecycle.HELPER
|
||||||
|
self.service = self.stack.enter_context(patch.object(lifecycle,'service'))
|
||||||
|
self.state = self.stack.enter_context(patch.object(lifecycle,'helper_state',return_value='not-found'))
|
||||||
|
|
||||||
|
def legacy(self, enabled=True):
|
||||||
|
self.old.mkdir()
|
||||||
|
settings = lifecycle.script_settings(self.binding,self.uid,'c'*64)
|
||||||
|
settings['allow_root_scripts'] = enabled
|
||||||
|
lifecycle.save(self.old / 'helper.json',settings)
|
||||||
|
legacy_image = self.root / 'releases' / self.previous / 'helper'
|
||||||
|
self.unit.write_bytes(lifecycle.helper_unit(legacy_image,self.old / 'helper.json'))
|
||||||
|
|
||||||
|
def test_no_unit_or_explicitly_disabled_local_policy_stays_service_only(self):
|
||||||
|
for state, opt_in in [('not-found',False), ('masked',True), ('disabled',True)]:
|
||||||
|
with self.subTest(state=state):
|
||||||
|
self.state.return_value = state
|
||||||
|
lifecycle.provision_scripts(opt_in)
|
||||||
|
self.service.assert_not_called()
|
||||||
|
self.assertFalse((self.folder / 'script-helper.json').exists())
|
||||||
|
|
||||||
|
def test_legacy_predecessor_migrates_only_for_exact_authorized_profile(self):
|
||||||
|
self.legacy(enabled=False)
|
||||||
|
with self.assertRaisesRegex(ValueError,'different binding or profile'):
|
||||||
|
lifecycle.helper_unit_files(self.binding,self.uid)
|
||||||
|
settings = lifecycle.read(self.old / 'helper.json')
|
||||||
|
settings['allow_root_scripts'] = True
|
||||||
|
lifecycle.save(self.old / 'helper.json',settings)
|
||||||
|
with self.assertRaisesRegex(ValueError,'different binding or profile'):
|
||||||
|
lifecycle.helper_unit_files(dict(self.binding, public_key_hex='0'*64),self.uid)
|
||||||
|
files = dict(lifecycle.helper_unit_files(self.binding,self.uid))
|
||||||
|
self.assertIn(b'lifecycle.py run-helper',files[self.unit])
|
||||||
|
self.assertIn(str(self.previous).encode(),self.unit.read_bytes())
|
||||||
|
|
||||||
|
def test_rejected_pair_does_not_run_candidate_and_altered_policy_stays_intact(self):
|
||||||
|
with patch.object(lifecycle.subprocess,'check_output',side_effect=subprocess.CalledProcessError(1,'verify')) as run:
|
||||||
|
with self.assertRaises(subprocess.CalledProcessError):
|
||||||
|
lifecycle.prepare_script_helper(self.folder,self.binding,self.uid)
|
||||||
|
self.assertEqual(run.call_count,1)
|
||||||
|
config = self.folder / 'script-helper.json'
|
||||||
|
self.assertFalse(config.exists())
|
||||||
|
with patch.object(lifecycle.subprocess,'check_output',side_effect=[json.dumps(self.manifest),json.dumps(self.pin).encode()]):
|
||||||
|
self.assertEqual(lifecycle.prepare_script_helper(self.folder,self.binding,self.uid),self.pin)
|
||||||
|
settings = lifecycle.read(config)
|
||||||
|
settings['allow_root_scripts'] = False
|
||||||
|
lifecycle.save(config,settings)
|
||||||
|
with patch.object(lifecycle.subprocess,'check_output',return_value=json.dumps(self.manifest)) as run:
|
||||||
|
with self.assertRaisesRegex(ValueError,'binding changed'):
|
||||||
|
lifecycle.prepare_script_helper(self.folder,self.binding,self.uid)
|
||||||
|
self.assertEqual(run.call_count,1)
|
||||||
|
self.assertEqual(lifecycle.read(config),settings)
|
||||||
|
|
||||||
|
def test_rollback_selects_previous_pair_and_keeps_pending_until_confirmed(self):
|
||||||
|
self.state.return_value = 'enabled'
|
||||||
|
previous = self.root / 'releases' / self.previous
|
||||||
|
previous.mkdir()
|
||||||
|
lifecycle.save(previous / 'manifest.json',dict(self.manifest,release_id=self.previous,version='v1'))
|
||||||
|
lifecycle.save(previous / 'script-pin.json',self.pin)
|
||||||
|
pending = self.root / 'pending.json'
|
||||||
|
intent = {'previous':self.previous,'sequence':2,'script_helper':True}
|
||||||
|
lifecycle.save(pending,intent)
|
||||||
|
with patch.object(lifecycle,'start_pair') as start, patch.object(lifecycle,'healthy',side_effect=[False,True]):
|
||||||
|
with self.assertRaisesRegex(ValueError,'has not yet confirmed'):
|
||||||
|
lifecycle.revert(intent)
|
||||||
|
self.assertEqual(lifecycle.active_folder(),previous)
|
||||||
|
self.assertTrue(pending.exists())
|
||||||
|
lifecycle.revert(intent,report_failure=False)
|
||||||
|
self.assertFalse(pending.exists())
|
||||||
|
self.assertEqual(start.call_count,2)
|
||||||
|
self.assertEqual(lifecycle.read(self.root / 'failed.json')['release_sequence'],2)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
Reference in New Issue
Block a user