Support interactive customer transfers for enrolled devices
Rust development slice / linux (push) Failing after 8s
Rust development slice / linux (push) Failing after 8s
This commit is contained in:
@@ -0,0 +1,391 @@
|
||||
//! A handoff changes the installation, not the old journal or its trust.
|
||||
use anyhow::{Context, Result, ensure};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use reqwest::Client;
|
||||
use rmm_domain::customer_transfer::{CertificateRequest, CertificateResponse, Offer};
|
||||
use rmm_protocol::EnrollmentResponse;
|
||||
use serde::{Deserialize, de::DeserializeOwned};
|
||||
use std::{
|
||||
fs::{self, File, OpenOptions},
|
||||
io::{Read, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::Duration,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
const PREFIX: &str = "customer-move-";
|
||||
const INTENT: &str = "customer-move-intent.json";
|
||||
const MAX_RECORD: usize = 32768;
|
||||
|
||||
pub fn idle(journal: &rusqlite::Connection, ledger: &rusqlite::Connection) -> Result<bool> {
|
||||
let busy: bool = journal.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM job_attempts WHERE state IN (
|
||||
'accepted','requesting','running','verifying','unknown','awaiting_reboot'))",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
let consumed: bool = ledger.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM consumed WHERE result IS NULL)",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
// The new customer executes under the same service account. Retire
|
||||
// local history only after the old installation has delivered its work.
|
||||
if busy || consumed {
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(crate::jobs::events(journal)?.iter().all(|event| {
|
||||
matches!(
|
||||
event.payload,
|
||||
Some(rmm_protocol::Payload::InventorySnapshot(_))
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<Vec<u8>> {
|
||||
let info = fs::symlink_metadata(path)?;
|
||||
ensure!(
|
||||
info.is_file() && !info.file_type().is_symlink() && info.len() <= MAX_RECORD as u64,
|
||||
"TRANSFER_RECORD"
|
||||
);
|
||||
let mut data = Vec::new();
|
||||
File::open(path)?
|
||||
.take(MAX_RECORD as u64 + 1)
|
||||
.read_to_end(&mut data)?;
|
||||
ensure!(data.len() <= MAX_RECORD, "TRANSFER_RECORD");
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
fn sync_dir(path: &Path) -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
File::open(path)?.sync_all()?;
|
||||
#[cfg(not(unix))]
|
||||
let _ = path;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn publish(path: &Path, bytes: &[u8]) -> Result<()> {
|
||||
if path.try_exists()? {
|
||||
ensure!(read(path)? == bytes, "TRANSFER_RECORD_CONFLICT");
|
||||
return Ok(());
|
||||
}
|
||||
let dir = path.parent().context("TRANSFER_RECORD_PARENT")?;
|
||||
let temporary = dir.join(format!("{PREFIX}tmp-{}", Uuid::new_v4()));
|
||||
let result = (|| {
|
||||
let mut options = OpenOptions::new();
|
||||
options.write(true).create_new(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
options.mode(0o600);
|
||||
}
|
||||
let mut file = options.open(&temporary)?;
|
||||
file.write_all(bytes)?;
|
||||
file.sync_all()?;
|
||||
drop(file);
|
||||
fs::rename(&temporary, path)?;
|
||||
sync_dir(dir)
|
||||
})();
|
||||
if result.is_err() {
|
||||
let _ = fs::remove_file(temporary);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn file(dir: &Path, id: Uuid, role: &str) -> PathBuf {
|
||||
dir.join(format!("{PREFIX}{id}-{role}"))
|
||||
}
|
||||
|
||||
fn verify(response: &CertificateResponse, signer: &str) -> Result<()> {
|
||||
let binding = &response.receipt.binding;
|
||||
let signature = Signature::from_slice(&hex::decode(&response.receipt.signature_hex)?)?;
|
||||
let public: [u8; 32] = hex::decode(signer)?
|
||||
.try_into()
|
||||
.map_err(|_| anyhow::anyhow!("TRANSFER_SIGNER"))?;
|
||||
VerifyingKey::from_bytes(&public)?.verify_strict(&binding.signing_bytes()?, &signature)?;
|
||||
ensure!(
|
||||
binding.offer.source_tenant_id != binding.offer.target_tenant_id
|
||||
&& binding.agent_id != binding.offer.source_agent_id
|
||||
&& !binding.agent_id.is_nil()
|
||||
&& !binding.asset_id.is_nil()
|
||||
&& binding.certificate_sha256
|
||||
== rmm_domain::jobs::hash(response.certificate_pem.as_bytes()),
|
||||
"TRANSFER_BINDING"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn json<T: DeserializeOwned>(mut response: reqwest::Response) -> Result<T> {
|
||||
ensure!(response.status().is_success(), "TRANSFER_HTTP");
|
||||
let mut bytes = Vec::new();
|
||||
while let Some(chunk) = response.chunk().await? {
|
||||
ensure!(
|
||||
bytes.len() + chunk.len() <= MAX_RECORD,
|
||||
"TRANSFER_RESPONSE_SIZE"
|
||||
);
|
||||
bytes.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(serde_json::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
pub async fn stage(
|
||||
client: &Client,
|
||||
origin: &str,
|
||||
dir: &Path,
|
||||
current: &crate::auth::Binding,
|
||||
key_and_csr: impl FnOnce(Option<&[u8]>) -> Result<(Vec<u8>, String)>,
|
||||
) -> Result<bool> {
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
offer: Option<Offer>,
|
||||
}
|
||||
let route = format!("{origin}/agent/v1/customer-transfer");
|
||||
let response = client
|
||||
.get(&route)
|
||||
.timeout(Duration::from_secs(4))
|
||||
.send()
|
||||
.await?;
|
||||
if response.status() == reqwest::StatusCode::NOT_FOUND {
|
||||
return Ok(false); // agent updates can precede the server upgrade
|
||||
}
|
||||
let Some(offer) = json::<Response>(response).await?.offer else {
|
||||
return Ok(false);
|
||||
};
|
||||
ensure!(
|
||||
offer.source_agent_id == current.agent_id
|
||||
&& offer.source_tenant_id == current.tenant_id
|
||||
&& offer.target_tenant_id != current.tenant_id
|
||||
&& !offer.transfer_id.is_nil(),
|
||||
"TRANSFER_SOURCE"
|
||||
);
|
||||
let id = offer.transfer_id;
|
||||
let key_path = file(dir, id, "key.pem");
|
||||
let previous = key_path
|
||||
.try_exists()?
|
||||
.then(|| read(&key_path))
|
||||
.transpose()?;
|
||||
let (key, csr_pem) = key_and_csr(previous.as_deref())?;
|
||||
publish(&key_path, &key)?;
|
||||
let response = json::<CertificateResponse>(
|
||||
client
|
||||
.post(format!("{route}/{id}/certificate"))
|
||||
.timeout(Duration::from_secs(10))
|
||||
.json(&CertificateRequest { csr_pem })
|
||||
.send()
|
||||
.await?,
|
||||
)
|
||||
.await?;
|
||||
verify(&response, ¤t.public_key_hex)?;
|
||||
ensure!(
|
||||
response.receipt.binding.offer == offer,
|
||||
"TRANSFER_OFFER_CHANGED"
|
||||
);
|
||||
publish(
|
||||
&file(dir, id, "response.json"),
|
||||
&serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn archive(dir: &Path, id: Uuid) -> Result<()> {
|
||||
for item in fs::read_dir(dir)? {
|
||||
let item = item?;
|
||||
let name = item.file_name();
|
||||
if name.to_string_lossy().starts_with(PREFIX)
|
||||
|| ["agent.lock", "job-signing-key.json"]
|
||||
.iter()
|
||||
.any(|kept| name == *kept)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if name == "jobs" && item.file_type()?.is_dir() {
|
||||
// Keep the installer-owned directory and its Windows ACL.
|
||||
archive(&item.path(), id)?;
|
||||
continue;
|
||||
}
|
||||
let mut backup = std::ffi::OsString::from(format!("{PREFIX}{id}-prior-"));
|
||||
backup.push(name);
|
||||
let target = dir.join(backup);
|
||||
ensure!(!target.try_exists()?, "TRANSFER_ARCHIVE_EXISTS");
|
||||
fs::rename(item.path(), target)?;
|
||||
}
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
fn retire_prior_state(dir: &Path, id: Uuid) -> Result<()> {
|
||||
let prefix = format!("{PREFIX}{id}-prior-");
|
||||
for item in fs::read_dir(dir)? {
|
||||
let item = item?;
|
||||
let name = item.file_name();
|
||||
if name == "jobs" && item.file_type()?.is_dir() {
|
||||
retire_prior_state(&item.path(), id)?;
|
||||
} else if name.to_string_lossy().starts_with(&prefix) {
|
||||
if item.file_type()?.is_dir() {
|
||||
fs::remove_dir_all(item.path())?;
|
||||
} else {
|
||||
fs::remove_file(item.path())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
sync_dir(dir)
|
||||
}
|
||||
|
||||
pub fn pending(dir: &Path) -> Result<bool> {
|
||||
Ok(dir.join(INTENT).try_exists()?)
|
||||
}
|
||||
|
||||
pub fn activate(dir: &Path, signer: &str) -> Result<()> {
|
||||
let intent = dir.join(INTENT);
|
||||
if !intent.try_exists()? {
|
||||
return Ok(());
|
||||
}
|
||||
let id: Uuid = serde_json::from_slice(&read(&intent)?)?;
|
||||
let response_file = file(dir, id, "response.json");
|
||||
let data = read(&response_file)?;
|
||||
let response: CertificateResponse = serde_json::from_slice(&data)?;
|
||||
let binding = &response.receipt.binding;
|
||||
verify(&response, signer)?;
|
||||
ensure!(binding.offer.transfer_id == id, "TRANSFER_INTENT");
|
||||
let relocated = file(dir, id, "relocated");
|
||||
if !relocated.try_exists()? {
|
||||
let current: EnrollmentResponse =
|
||||
serde_json::from_slice(&read(&dir.join("identity.json")).or_else(|error| {
|
||||
let backup = file(dir, id, "prior-identity.json");
|
||||
if backup.exists() {
|
||||
read(&backup)
|
||||
} else {
|
||||
Err(error)
|
||||
}
|
||||
})?)?;
|
||||
ensure!(
|
||||
current.agent_id == binding.offer.source_agent_id.to_string(),
|
||||
"TRANSFER_SOURCE"
|
||||
);
|
||||
archive(dir, id)?;
|
||||
publish(&relocated, b"ok")?;
|
||||
}
|
||||
let key_file = file(dir, id, "key.pem");
|
||||
let identity = EnrollmentResponse {
|
||||
agent_id: binding.agent_id.to_string(),
|
||||
asset_id: binding.asset_id.to_string(),
|
||||
certificate_pem: response.certificate_pem,
|
||||
};
|
||||
publish(&dir.join("device.key"), &read(&key_file)?)?;
|
||||
publish(&dir.join("device.pem"), identity.certificate_pem.as_bytes())?;
|
||||
publish(&dir.join("identity.json"), &serde_json::to_vec(&identity)?)?;
|
||||
publish(&file(dir, binding.agent_id, "active.json"), &data)?;
|
||||
// Do not expose old-tenant credentials or job outputs to scripts running
|
||||
// under this same local service account in the new tenant.
|
||||
retire_prior_state(dir, id)?;
|
||||
fs::remove_file(intent)?;
|
||||
sync_dir(dir)?;
|
||||
// The live private key is durable. This copy only existed for upload retry.
|
||||
let _ = fs::remove_file(key_file);
|
||||
let _ = fs::remove_file(response_file);
|
||||
let _ = fs::remove_file(relocated);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn assigned_tenant(
|
||||
dir: &Path,
|
||||
identity: &EnrollmentResponse,
|
||||
signer: &str,
|
||||
) -> Result<Option<Uuid>> {
|
||||
let path = file(dir, Uuid::parse_str(&identity.agent_id)?, "active.json");
|
||||
if !path.try_exists()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let response: CertificateResponse = serde_json::from_slice(&read(&path)?)?;
|
||||
verify(&response, signer)?;
|
||||
let binding = response.receipt.binding;
|
||||
ensure!(
|
||||
response.certificate_pem == identity.certificate_pem
|
||||
&& binding.agent_id.to_string() == identity.agent_id
|
||||
&& binding.asset_id.to_string() == identity.asset_id,
|
||||
"TRANSFER_ACTIVE_IDENTITY"
|
||||
);
|
||||
Ok(Some(binding.offer.target_tenant_id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
use rmm_domain::customer_transfer::{Binding, Receipt};
|
||||
|
||||
#[test]
|
||||
fn authenticated_handoff_recovers_partial_archive_and_isolates_local_state() -> Result<()> {
|
||||
let dir = std::env::temp_dir().join(format!("rmm-transfer-{}", Uuid::new_v4()));
|
||||
fs::create_dir(&dir)?;
|
||||
let result = (|| {
|
||||
let id = Uuid::new_v4();
|
||||
let source = Uuid::new_v4();
|
||||
let target = Uuid::new_v4();
|
||||
let previous = EnrollmentResponse {
|
||||
agent_id: source.to_string(),
|
||||
asset_id: Uuid::new_v4().to_string(),
|
||||
certificate_pem: "old certificate fixture".into(),
|
||||
};
|
||||
publish(&dir.join("identity.json"), &serde_json::to_vec(&previous)?)?;
|
||||
publish(&dir.join("device.key"), b"old key")?;
|
||||
publish(&dir.join("journal.sqlite"), b"old journal")?;
|
||||
let signer = SigningKey::from_bytes(&[7; 32]);
|
||||
let public = hex::encode(signer.verifying_key().as_bytes());
|
||||
let certificate_pem = "new certificate fixture".to_string();
|
||||
let binding = Binding {
|
||||
offer: Offer {
|
||||
transfer_id: id,
|
||||
source_agent_id: source,
|
||||
source_tenant_id: Uuid::new_v4(),
|
||||
target_tenant_id: Uuid::new_v4(),
|
||||
},
|
||||
asset_id: Uuid::new_v4(),
|
||||
agent_id: target,
|
||||
certificate_sha256: rmm_domain::jobs::hash(certificate_pem.as_bytes()),
|
||||
};
|
||||
let tenant = binding.offer.target_tenant_id;
|
||||
let mut response = CertificateResponse {
|
||||
certificate_pem,
|
||||
receipt: Receipt {
|
||||
signature_hex: hex::encode(signer.sign(&binding.signing_bytes()?).to_bytes()),
|
||||
binding,
|
||||
},
|
||||
};
|
||||
publish(&file(&dir, id, "key.pem"), b"new key")?;
|
||||
publish(&dir.join(INTENT), &serde_json::to_vec(&id)?)?;
|
||||
response.receipt.binding.offer.target_tenant_id = Uuid::new_v4();
|
||||
fs::write(
|
||||
file(&dir, id, "response.json"),
|
||||
serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
assert!(activate(&dir, &public).is_err());
|
||||
assert_eq!(fs::read(dir.join("device.key"))?, b"old key");
|
||||
response.receipt.binding.offer.target_tenant_id = tenant;
|
||||
fs::write(
|
||||
file(&dir, id, "response.json"),
|
||||
serde_json::to_vec(&response)?,
|
||||
)?;
|
||||
|
||||
// Simulate a stop immediately after relocating the first original file.
|
||||
fs::rename(
|
||||
dir.join("identity.json"),
|
||||
file(&dir, id, "prior-identity.json"),
|
||||
)?;
|
||||
activate(&dir, &public)?;
|
||||
activate(&dir, &public)?;
|
||||
assert!(!pending(&dir)?);
|
||||
assert!(!file(&dir, id, "prior-identity.json").exists());
|
||||
assert!(!file(&dir, id, "prior-device.key").exists());
|
||||
assert!(!file(&dir, id, "prior-journal.sqlite").exists());
|
||||
assert_eq!(fs::read(dir.join("device.key"))?, b"new key");
|
||||
let active: EnrollmentResponse =
|
||||
serde_json::from_slice(&read(&dir.join("identity.json"))?)?;
|
||||
assert_eq!(active.agent_id, target.to_string());
|
||||
assert_eq!(assigned_tenant(&dir, &active, &public)?, Some(tenant));
|
||||
Ok(())
|
||||
})();
|
||||
fs::remove_dir_all(dir)?;
|
||||
result
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Callers must authenticate their transport, protect/lock their own journals and
|
||||
//! supply a qualified clock. A successful signature is never UI approval itself.
|
||||
pub mod auth;
|
||||
pub mod customer_transfer;
|
||||
pub mod crypto;
|
||||
pub mod helper_reconcile;
|
||||
pub mod jobs;
|
||||
|
||||
Reference in New Issue
Block a user