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:
@@ -20,6 +20,7 @@ rmm-domain = { path = "../domain" }
|
||||
rmm-protocol = { path = "../protocol" }
|
||||
rmm-updater-handoff = { path = "../updater-handoff" }
|
||||
rusqlite.workspace = true
|
||||
reqwest.workspace = true
|
||||
ed25519-dalek = "=2.2.0"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -92,6 +92,11 @@ fn rotation_file_id(path: &Path) -> Result<[u32; 3]> {
|
||||
])
|
||||
}
|
||||
impl Config {
|
||||
fn supports_customer_transfer(&self) -> bool {
|
||||
cfg!(feature = "system-helper") && self.enable_jobs
|
||||
&& self.localservice_time_policy.is_some() && self.job_binding_file.is_none()
|
||||
&& !self.windows_echo_probe_only && !self.windows_update_helper
|
||||
}
|
||||
fn allows_script_action(&self, action: &Action, identity: &str) -> bool {
|
||||
let Action::RunScript { interpreter, windows_execution_profile, .. } = action else {
|
||||
return false;
|
||||
@@ -183,6 +188,16 @@ fn protected_read(path: &Path, max: usize) -> Result<Vec<u8>> {
|
||||
);
|
||||
Ok(fs::read(path)?)
|
||||
}
|
||||
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
|
||||
let key = match previous {
|
||||
Some(raw) => KeyPair::from_pem(std::str::from_utf8(raw)?)?,
|
||||
None => KeyPair::generate()?,
|
||||
};
|
||||
let mut parameters = CertificateParams::default();
|
||||
parameters.distinguished_name.push(DnType::CommonName, "customer-transfer");
|
||||
let csr = parameters.serialize_request(&key)?.pem()?;
|
||||
Ok((key.serialize_pem().into_bytes(), csr))
|
||||
}
|
||||
async fn enrollment(config: &Config, ca: &[u8]) -> Result<EnrollmentResponse> {
|
||||
let state = &config.state_directory;
|
||||
let identity = state.join("identity.json");
|
||||
@@ -625,6 +640,7 @@ struct Agent {
|
||||
config: Config,
|
||||
reported_version: String,
|
||||
release_job_guard: Option<fs::File>,
|
||||
transfer_gate: Option<fs::File>,
|
||||
identity: EnrollmentResponse,
|
||||
ca: Vec<u8>,
|
||||
journal: Journal,
|
||||
@@ -1561,12 +1577,54 @@ impl Agent {
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
async fn stage_customer_transfer(&mut self) -> Result<bool> {
|
||||
if !self.config.supports_customer_transfer() || self.running.is_some()
|
||||
|| self.prepared || self.deferred_sync.is_some() || self.deferred_permit.is_some()
|
||||
|| self.release_job_guard.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let (Some(binding), Some(ledger)) = (&self.binding, &self.ledger) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !rmm_agent_core::customer_transfer::idle(self.journal.connection(), ledger)? {
|
||||
return Ok(false);
|
||||
}
|
||||
#[cfg(feature = "system-helper")]
|
||||
if self.helper_control_busy_for_sync() || self.update_health.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
// Keep the release service from replacing the program during the handoff.
|
||||
let binding = binding.clone();
|
||||
if !self.reserve_release_gate()? {
|
||||
return Ok(false);
|
||||
}
|
||||
let result = async {
|
||||
let identity = self.certificates.current(
|
||||
self.journal.connection(), &self.key_files, Utc::now().timestamp(),
|
||||
)?;
|
||||
let client = crate::https_channel::mtls_client(
|
||||
self.config.connect_address, &self.ca, &identity.certificate_pem, &identity.private_key_pem,
|
||||
)?;
|
||||
let base = format!("https://{}:{}", self.config.server_name, self.config.connect_address.port());
|
||||
rmm_agent_core::customer_transfer::stage(
|
||||
&client, &base, &self.config.state_directory, &binding, transfer_csr,
|
||||
).await
|
||||
}.await;
|
||||
let gate = self.release_job_guard.take();
|
||||
if matches!(&result, Ok(true)) {
|
||||
self.transfer_gate = gate;
|
||||
}
|
||||
result
|
||||
}
|
||||
fn capabilities(&self) -> Vec<String> {
|
||||
let mut caps: Vec<String> = CAPABILITIES.iter().map(|c| c.to_string()).collect();
|
||||
#[cfg(target_env = "gnu")]
|
||||
caps.push("agent.release.windows.gnu/1".into());
|
||||
// queue_update_observation emits the passive update status in every profile.
|
||||
caps.push("agent.update/1".into());
|
||||
if self.config.supports_customer_transfer() {
|
||||
caps.push(rmm_domain::customer_transfer::CAPABILITY.into());
|
||||
}
|
||||
if self.config.windows_echo_probe_only {
|
||||
caps.push("windows.echo-probe/1".into());
|
||||
}
|
||||
@@ -2746,6 +2804,11 @@ impl Agent {
|
||||
if rotation_at.elapsed() >= rotation_after {
|
||||
rotation_at = Instant::now();
|
||||
rotation_after = Duration::from_secs(30);
|
||||
match self.stage_customer_transfer().await {
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) => (),
|
||||
Err(_) => eprintln!("CUSTOMER_TRANSFER_PENDING"),
|
||||
}
|
||||
let now = Utc::now().timestamp();
|
||||
if self
|
||||
.certificates
|
||||
@@ -2905,7 +2968,23 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
);
|
||||
let path = Path::new(&arguments[2]);
|
||||
ensure!(path.is_absolute(), "ABSOLUTE_CONFIG_REQUIRED");
|
||||
let config = Config::read(path)?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.worker_threads(2)
|
||||
.build()?;
|
||||
runtime.block_on(async {
|
||||
let mut gate = None;
|
||||
loop {
|
||||
match run_service_binding(path, stop, gate.take()).await? {
|
||||
Some(held) => gate = Some(held),
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async fn run_service_binding(path: &Path, stop: &'static AtomicBool, release_guard: Option<fs::File>) -> Result<Option<fs::File>> {
|
||||
let mut config = Config::read(path)?;
|
||||
native::require_local_service()?;
|
||||
ensure!(
|
||||
config.state_directory.is_absolute(),
|
||||
@@ -2921,21 +3000,50 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
let child = child?;
|
||||
native::private_path(&child.path(), child.file_type()?.is_dir())?;
|
||||
}
|
||||
let journal = Journal::open(&config.state_directory)?;
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.worker_threads(2)
|
||||
.build()?;
|
||||
runtime.block_on(async move {
|
||||
let identity = enrollment(&config, &ca).await?;
|
||||
let mut journal=journal;
|
||||
if rmm_agent_core::customer_transfer::pending(&config.state_directory)? {
|
||||
#[cfg(feature = "system-helper")]
|
||||
{
|
||||
ensure!(config.supports_customer_transfer(), "TRANSFER_CONFIG");
|
||||
let policy = config.localservice_time_policy.as_deref().context("TRANSFER_POLICY")?;
|
||||
let signer = rmm_agent_windows::signed_clock::enrolled_transfer_signer(policy)?;
|
||||
loop {
|
||||
if stop.load(Ordering::SeqCst) {
|
||||
return Ok(None);
|
||||
}
|
||||
match rmm_agent_core::customer_transfer::activate(&config.state_directory, &signer) {
|
||||
Ok(()) => break,
|
||||
Err(error) if error.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| matches!(e.raw_os_error(), Some(32 | 33))) => {
|
||||
// Another service can briefly hold a read-only handle.
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "system-helper"))]
|
||||
anyhow::bail!("TRANSFER_CONFIG");
|
||||
}
|
||||
drop(release_guard);
|
||||
let mut journal = Journal::open(&config.state_directory)?;
|
||||
let identity = enrollment(&config, &ca).await?;
|
||||
journal.pin_identity(&identity.agent_id)?;
|
||||
let (boot, booted_at) = native::boot_identity().await?;
|
||||
let binding=config.job_binding_file.as_deref().map(readonly_binding).transpose()?;
|
||||
#[cfg(feature = "system-helper")]
|
||||
let binding = if let Some(policy) = &config.localservice_time_policy {
|
||||
Some(rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?)
|
||||
} else { binding };
|
||||
let (binding, installed_tenant) = if let Some(policy) = &config.localservice_time_policy {
|
||||
let mut enrolled = rmm_agent_windows::signed_clock::enrolled_binding(policy, &identity)?;
|
||||
let installed = enrolled.tenant_id;
|
||||
if config.supports_customer_transfer()
|
||||
&& let Some(target) = rmm_agent_core::customer_transfer::assigned_tenant(
|
||||
&config.state_directory, &identity, &enrolled.public_key_hex,
|
||||
)? {
|
||||
enrolled.tenant_id = target;
|
||||
// Elevated helpers are bound to the original installation.
|
||||
config.managed_script_helper = false;
|
||||
}
|
||||
(Some(enrolled), Some(installed))
|
||||
} else { (binding, None) };
|
||||
if let Some(binding)=&binding {
|
||||
ensure!(binding.agent_id.to_string()==identity.agent_id && binding.asset_id.to_string()==identity.asset_id,"ENROLLMENT_JOB_BINDING_MISMATCH");
|
||||
native::private_path(&config.state_directory.join("jobs"),true)?;
|
||||
@@ -2952,7 +3060,9 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
#[cfg(feature = "system-helper")]
|
||||
let clock = if let Some(policy) = &config.localservice_time_policy {
|
||||
let binding = binding.clone().context("JOB_BINDING_REQUIRED")?;
|
||||
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(binding,policy.clone()).for_generation(0) }
|
||||
JobClock { enabled: true, native: rmm_agent_windows::signed_clock::RuntimeClock::enrolled_local_service(
|
||||
binding, policy.clone(), installed_tenant.context("INSTALLED_TENANT_REQUIRED")?
|
||||
).for_generation(0) }
|
||||
} else { clock };
|
||||
let mut config=config;
|
||||
if config.enable_jobs {
|
||||
@@ -2974,6 +3084,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
config,
|
||||
reported_version: installed_version()?,
|
||||
release_job_guard: None,
|
||||
transfer_gate: None,
|
||||
identity,
|
||||
ca,
|
||||
journal,
|
||||
@@ -3038,6 +3149,12 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
if let Err(error) = agent.session(stop).await {
|
||||
record_session_error(&agent.config.state_directory, &error);
|
||||
}
|
||||
if let Some(guard) = agent.transfer_gate.take() {
|
||||
if let Some(worker) = agent.readiness_worker.take() {
|
||||
let _ = worker.await;
|
||||
}
|
||||
return Ok(Some(guard));
|
||||
}
|
||||
if start.elapsed() > Duration::from_secs(60) {
|
||||
backoff = 1;
|
||||
}
|
||||
@@ -3056,8 +3173,7 @@ fn service_run(stop: &'static AtomicBool) -> Result<()> {
|
||||
tokio::time::sleep(Duration::from_millis(250)).await;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
Ok(None)
|
||||
}
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
|
||||
@@ -802,10 +802,7 @@ mod installed {
|
||||
tenant_id: Uuid,
|
||||
job_signing_public_key_hex: String,
|
||||
}
|
||||
pub fn enrolled_binding(
|
||||
policy: &Path,
|
||||
registration: &rmm_protocol::EnrollmentResponse,
|
||||
) -> Result<rmm_agent_core::auth::Binding> {
|
||||
fn installed_policy(policy: &Path) -> Result<LocalPolicy> {
|
||||
crate::job_binding::check_admin_readonly(policy)?;
|
||||
ensure!(
|
||||
std::fs::metadata(policy)?.len() <= MAX_CONFIG_BYTES as u64,
|
||||
@@ -816,6 +813,16 @@ mod installed {
|
||||
p.schema_version == 1 && !p.tenant_id.is_nil() && digest(&p.job_signing_public_key_hex),
|
||||
"INSTALLED_JOB_TRUST"
|
||||
);
|
||||
Ok(p)
|
||||
}
|
||||
pub fn enrolled_transfer_signer(policy: &Path) -> Result<String> {
|
||||
Ok(installed_policy(policy)?.job_signing_public_key_hex)
|
||||
}
|
||||
pub fn enrolled_binding(
|
||||
policy: &Path,
|
||||
registration: &rmm_protocol::EnrollmentResponse,
|
||||
) -> Result<rmm_agent_core::auth::Binding> {
|
||||
let p = installed_policy(policy)?;
|
||||
let binding = rmm_agent_core::auth::Binding {
|
||||
tenant_id: p.tenant_id,
|
||||
agent_id: Uuid::parse_str(®istration.agent_id)?,
|
||||
@@ -963,6 +970,7 @@ mod installed {
|
||||
generation: u64,
|
||||
binding: &rmm_agent_core::auth::Binding,
|
||||
policy_file: &Path,
|
||||
installed_tenant: Uuid,
|
||||
helper: Option<&ipc::PeerPin>,
|
||||
) -> Result<Self> {
|
||||
let mut failure_fence = ConstructorFailureFence { armed: true };
|
||||
@@ -1002,7 +1010,7 @@ mod installed {
|
||||
.map(|(id, key)| Ok((id, independent_time_key(&key, &binding.public_key_hex)?)))
|
||||
.collect::<Result<BTreeMap<_, _>>>()?;
|
||||
ensure!(
|
||||
p.tenant_id == binding.tenant_id
|
||||
p.tenant_id == installed_tenant
|
||||
&& p.job_signing_public_key_hex == binding.public_key_hex,
|
||||
"TIME_POLICY_BINDING"
|
||||
);
|
||||
@@ -1394,7 +1402,7 @@ mod installed {
|
||||
pub struct RuntimeClock {
|
||||
role: Role,
|
||||
enrolled_helper: Option<ipc::PeerPin>,
|
||||
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf)>,
|
||||
local_policy: Option<(rmm_agent_core::auth::Binding, std::path::PathBuf, Uuid)>,
|
||||
state: Arc<Mutex<Option<(u64, SignedClock)>>>,
|
||||
}
|
||||
#[derive(Clone)]
|
||||
@@ -1414,14 +1422,16 @@ mod installed {
|
||||
pub fn enrolled_local_service(
|
||||
binding: rmm_agent_core::auth::Binding,
|
||||
policy: std::path::PathBuf,
|
||||
installed_tenant: Uuid,
|
||||
) -> Self {
|
||||
let mut value = Self::new(Role::Agent);
|
||||
value.local_policy = Some((binding, policy));
|
||||
value.local_policy = Some((binding, policy, installed_tenant));
|
||||
value
|
||||
}
|
||||
pub fn enrolled_windows_update_helper(binding: rmm_agent_core::auth::Binding, helper: ipc::PeerPin) -> Self {
|
||||
let mut value = Self::new(Role::SystemHelper);
|
||||
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json")));
|
||||
let installed_tenant = binding.tenant_id;
|
||||
value.local_policy = Some((binding, std::path::PathBuf::from(r"C:\ProgramData\RustDiscovery\job-time.json"), installed_tenant));
|
||||
value.enrolled_helper = Some(helper);
|
||||
value
|
||||
}
|
||||
@@ -1440,8 +1450,8 @@ mod installed {
|
||||
ensure!(generation > 0, "TIME_RUNTIME_GENERATION");
|
||||
self.close()?;
|
||||
let clock = match &self.local_policy {
|
||||
Some((binding, policy)) => {
|
||||
SignedClock::open_local_service(generation, binding, policy, self.enrolled_helper.as_ref()).await?
|
||||
Some((binding, policy, installed_tenant)) => {
|
||||
SignedClock::open_local_service(generation, binding, policy, *installed_tenant, self.enrolled_helper.as_ref()).await?
|
||||
}
|
||||
None => SignedClock::open(self.role, generation).await?,
|
||||
};
|
||||
@@ -1561,7 +1571,7 @@ mod installed {
|
||||
#[cfg(all(windows, feature = "system-helper"))]
|
||||
pub use installed::{
|
||||
BoundClock, CONFIG_PATH, Comparison, RuntimeClock, SignedClock, UPDATER_CONFIG_PATH,
|
||||
enrolled_binding,
|
||||
enrolled_binding, enrolled_transfer_signer,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -64,6 +64,8 @@ struct Agent<C: reconcile::SyncClock = reconcile::NativeClock> {
|
||||
rotation_policy: certificate_rotation::RotationPolicy,
|
||||
catalog: agent_update_catalog::Checker,
|
||||
update_observer: agent_update_apply::Observer,
|
||||
transfer_state: Option<PathBuf>,
|
||||
transfer_gate: Option<fs::File>,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct EffectFence {
|
||||
@@ -465,6 +467,9 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
"heartbeat/1".into(),
|
||||
"agent.update/1".into(),
|
||||
];
|
||||
if self.transfer_state.is_some() {
|
||||
capabilities.push(rmm_domain::customer_transfer::CAPABILITY.into());
|
||||
}
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
capabilities.push(rmm_domain::agent_update::LINUX_ARM64_RELEASE_CAPABILITY.into());
|
||||
if self.binding.is_some() {
|
||||
@@ -476,12 +481,39 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
if rmm_agent_linux::actions::Interpreter::PosixSh.available() {
|
||||
capabilities.push("run_script".into());
|
||||
}
|
||||
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||
if self.helpers.is_some() {
|
||||
capabilities.extend(helper_sync::script_capabilities(binding));
|
||||
}
|
||||
}
|
||||
capabilities.sort();
|
||||
capabilities.dedup();
|
||||
capabilities
|
||||
}
|
||||
async fn stage_customer_transfer(&mut self) -> Result<bool> {
|
||||
let (Some(dir), Some(binding)) = (&self.transfer_state, &self.binding) else {
|
||||
return Ok(false);
|
||||
};
|
||||
if !self.running_cancels.is_empty() || self.prepared.is_some()
|
||||
|| !rmm_agent_core::customer_transfer::idle(&self.db, &self.ledger)? {
|
||||
return Ok(false);
|
||||
}
|
||||
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());
|
||||
let guard = fs::File::open(env::var_os("RMM_RELEASE_LOCK").context("RELEASE_LOCK_REQUIRED")?)?;
|
||||
match fs2::FileExt::try_lock_shared(&guard) {
|
||||
Ok(()) => (),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => return Ok(false),
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
if rmm_agent_core::customer_transfer::stage(&client, &base, dir, binding, transfer_csr).await? {
|
||||
self.transfer_gate = Some(guard);
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
fn queue_inventory(&mut self) -> bool {
|
||||
if self.inventory_inflight || !storage::passive_collection_ready(&self.db).unwrap_or(false)
|
||||
{
|
||||
@@ -849,6 +881,11 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
if rotation_at.elapsed() >= Duration::from_secs(30) {
|
||||
rotation_at = Instant::now();
|
||||
match self.stage_customer_transfer().await {
|
||||
Ok(true) => return Ok(()),
|
||||
Ok(false) => (),
|
||||
Err(_) => eprintln!("customer transfer waiting for a valid handoff"),
|
||||
}
|
||||
if self
|
||||
.certificates
|
||||
.due(self.rotation_policy, Utc::now().timestamp())?
|
||||
@@ -873,6 +910,27 @@ impl<C: reconcile::SyncClock> Agent<C> {
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer_csr(previous: Option<&[u8]>) -> Result<(Vec<u8>, String)> {
|
||||
let key = match previous {
|
||||
Some(raw) => PKey::private_key_from_pem(raw)?,
|
||||
None => {
|
||||
let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1)?;
|
||||
PKey::from_ec_key(EcKey::generate(&group)?)?
|
||||
}
|
||||
};
|
||||
let mut csr = X509Req::builder()?;
|
||||
let mut name = X509NameBuilder::new()?;
|
||||
name.append_entry_by_text("CN", "customer-transfer")?;
|
||||
csr.set_subject_name(&name.build())?;
|
||||
csr.set_pubkey(&key)?;
|
||||
csr.sign(&key, MessageDigest::sha256())?;
|
||||
Ok((key.private_key_to_pem_pkcs8()?, String::from_utf8(csr.build().to_pem()?)?))
|
||||
}
|
||||
|
||||
fn customer_transfer_signer(dir: &Path) -> Result<rmm_privileged_helper::SigningKey> {
|
||||
rmm_privileged_helper::SigningKey::read(&dir.join("job-signing-key.json"), unsafe { libc::geteuid() })
|
||||
}
|
||||
|
||||
async fn enrollment(dir: &Path, address: std::net::SocketAddr, ca: &[u8]) -> Result<String> {
|
||||
let identity = dir.join("identity.json");
|
||||
if identity.exists() {
|
||||
@@ -950,6 +1008,18 @@ async fn main() -> Result<()> {
|
||||
PathBuf::from(env::var("RMM_AGENT_STATE").unwrap_or_else(|_| "devstate/agent".into()));
|
||||
storage::prepare_dir(&dir)?;
|
||||
let _lock = storage::lock(&dir)?;
|
||||
let mut release_guard = None;
|
||||
loop {
|
||||
if rmm_agent_core::customer_transfer::pending(&dir)? {
|
||||
let signer = customer_transfer_signer(&dir)?;
|
||||
rmm_agent_core::customer_transfer::activate(&dir, &signer.public_key_hex)?;
|
||||
}
|
||||
drop(release_guard.take());
|
||||
release_guard = Some(run_agent(&dir).await?);
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_agent(dir: &Path) -> Result<fs::File> {
|
||||
let address = env::var("RMM_CONNECT_ADDR")
|
||||
.unwrap_or_else(|_| "127.0.0.1:18443".into())
|
||||
.parse()?;
|
||||
@@ -978,6 +1048,20 @@ async fn main() -> Result<()> {
|
||||
enrollment_generation: 1, assignment_version: 1, public_key_hex: String::new(),
|
||||
});
|
||||
}
|
||||
let transfer_state = (env::var_os("RMM_JOB_BINDING_FILE").is_none()
|
||||
&& env::var_os("RMM_ENROLLMENT_TENANT").is_some()
|
||||
&& env::var("RMM_JOB_SIGNING_KEY_BOOTSTRAP").as_deref() == Ok("1")
|
||||
&& env::var_os("RMM_RELEASE_LOCK").is_some()).then(|| dir.to_owned());
|
||||
let mut moved = false;
|
||||
if transfer_state.is_some() && let Some(binding) = binding.as_mut()
|
||||
&& dir.join("job-signing-key.json").try_exists()? {
|
||||
let identity: EnrollmentResponse = serde_json::from_slice(&fs::read(dir.join("identity.json"))?)?;
|
||||
let signer = customer_transfer_signer(dir)?;
|
||||
if let Some(tenant) = rmm_agent_core::customer_transfer::assigned_tenant(dir, &identity, &signer.public_key_hex)? {
|
||||
binding.tenant_id = tenant;
|
||||
moved = true;
|
||||
}
|
||||
}
|
||||
let certificate_dir = dir.join("certificates");
|
||||
let certificates = certificate_rotation::RotationStore::open(
|
||||
&certificate_dir,
|
||||
@@ -1009,10 +1093,9 @@ async fn main() -> Result<()> {
|
||||
let sync = binding
|
||||
.as_ref()
|
||||
.map(|b| reconcile::ClientSync::new(b.clone()));
|
||||
let helpers = binding
|
||||
.as_ref()
|
||||
.map(helper_sync::Helpers::configured)
|
||||
.transpose()?;
|
||||
let helpers = if moved { None } else {
|
||||
binding.as_ref().map(helper_sync::Helpers::configured).transpose()?
|
||||
};
|
||||
let mut rotation_policy = certificate_rotation::RotationPolicy::default();
|
||||
if let Ok(after) = env::var("RMM_ROTATION_TEST_AFTER_SECONDS") {
|
||||
ensure!(
|
||||
@@ -1054,6 +1137,8 @@ async fn main() -> Result<()> {
|
||||
rotation_policy,
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state,
|
||||
transfer_gate: None,
|
||||
};
|
||||
agent.recover_interrupted()?;
|
||||
let mut backoff = 1_u64;
|
||||
@@ -1063,6 +1148,9 @@ async fn main() -> Result<()> {
|
||||
report_closed_gate(&error);
|
||||
}
|
||||
agent.close_gate();
|
||||
if let Some(guard) = agent.transfer_gate.take() {
|
||||
return Ok(guard);
|
||||
}
|
||||
eprintln!("channel unavailable; retrying with jitter (no jobs can execute)");
|
||||
if started.elapsed() > Duration::from_secs(60) {
|
||||
backoff = 1;
|
||||
|
||||
@@ -152,6 +152,8 @@ fn new_process_persists_interruption_before_helper_io_without_unlock_or_repeat()
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state: None,
|
||||
transfer_gate: None,
|
||||
};
|
||||
// A forged local consumption/start cannot become a purported grant result.
|
||||
agent
|
||||
@@ -541,6 +543,8 @@ async fn run(mode: wire_channel::Mode, trusted: bool, forged: bool, rounds: u64)
|
||||
rotation_policy: certificate_rotation::RotationPolicy::default(),
|
||||
catalog: agent_update_catalog::Checker::default(),
|
||||
update_observer: agent_update_apply::Observer::default(),
|
||||
transfer_state: None,
|
||||
transfer_gate: None,
|
||||
};
|
||||
for _ in 0..rounds {
|
||||
assert!(
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const CAPABILITY: &str = "device.customer_transfer/1";
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Offer {
|
||||
pub transfer_id: Uuid,
|
||||
pub source_tenant_id: Uuid,
|
||||
pub source_agent_id: Uuid,
|
||||
pub target_tenant_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Binding {
|
||||
pub offer: Offer,
|
||||
pub asset_id: Uuid,
|
||||
pub agent_id: Uuid,
|
||||
pub certificate_sha256: String,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
pub fn signing_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
|
||||
let mut bytes = b"rust-discovery:customer-transfer:1\0".to_vec();
|
||||
bytes.extend(serde_json::to_vec(self)?);
|
||||
Ok(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Receipt {
|
||||
pub binding: Binding,
|
||||
pub signature_hex: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CertificateRequest {
|
||||
pub csr_pem: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CertificateResponse {
|
||||
pub certificate_pem: String,
|
||||
pub receipt: Receipt,
|
||||
}
|
||||
@@ -3,6 +3,7 @@ pub mod agent_update;
|
||||
pub mod agent_update_provisioning;
|
||||
pub mod apt_transaction;
|
||||
pub mod checkpoint_repair;
|
||||
pub mod customer_transfer;
|
||||
pub mod inventory_document;
|
||||
pub mod jobs;
|
||||
pub mod reconciliation;
|
||||
|
||||
@@ -265,6 +265,12 @@ fn verify_envelope_with_keyring(
|
||||
}
|
||||
Ok(decoded.manifest)
|
||||
}
|
||||
pub(crate) async fn ensure_customer_starters(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
bootstrap::publish_starters(tx, tenant).await
|
||||
}
|
||||
pub fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route(
|
||||
@@ -602,7 +608,7 @@ async fn list(
|
||||
pub struct Current {
|
||||
platform: Platform,
|
||||
}
|
||||
async fn device(
|
||||
pub(crate) async fn device(
|
||||
s: &crate::State,
|
||||
peer: crate::Peer,
|
||||
headers: &HeaderMap,
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
use super::*;
|
||||
mod starter;
|
||||
|
||||
pub(super) use starter::publish_missing as publish_starters;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Config {
|
||||
|
||||
@@ -10,7 +10,7 @@ struct Starter {
|
||||
worker: Pin,
|
||||
}
|
||||
|
||||
pub(super) async fn publish_missing(
|
||||
pub(in crate::agent_updates) async fn publish_missing(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
use crate::{auth::Principal, jobs::Error};
|
||||
use axum::{
|
||||
Extension, Json, Router,
|
||||
extract::{Path, Query, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::{IntoResponse, Response},
|
||||
routing::{get, post},
|
||||
};
|
||||
use chrono::{DateTime, Utc};
|
||||
use rmm_domain::{customer_transfer as wire, jobs::hash};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::{Postgres, Row, Transaction};
|
||||
use uuid::Uuid;
|
||||
|
||||
const NOT_FOUND: Error = Error(StatusCode::NOT_FOUND, "NOT_FOUND");
|
||||
|
||||
fn private_json(body: Value) -> Response {
|
||||
([("cache-control", "private, no-store")], Json(body)).into_response()
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route("/agent/v1/customer-transfer", get(device_offer))
|
||||
.route(
|
||||
"/agent/v1/customer-transfer/{transfer}/certificate",
|
||||
post(device_certificate),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn routes(router: Router<crate::State>) -> Router<crate::State> {
|
||||
router
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer",
|
||||
get(status).post(begin),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/complete",
|
||||
post(complete),
|
||||
)
|
||||
.route(
|
||||
"/api/v1/tenants/{tenant}/devices/{asset}/customer-transfer/{transfer}/cancel",
|
||||
post(cancel),
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Pairing {
|
||||
agent_id: Uuid,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Destination {
|
||||
target_tenant_id: Uuid,
|
||||
}
|
||||
|
||||
struct Transfer {
|
||||
transfer_id: Uuid,
|
||||
target_tenant_id: Uuid,
|
||||
target_asset_id: Option<Uuid>,
|
||||
target_agent_id: Option<Uuid>,
|
||||
csr_sha256: Option<String>,
|
||||
requested_by: String,
|
||||
completed_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
async fn source<'a>(
|
||||
s: &'a crate::State,
|
||||
headers: &HeaderMap,
|
||||
tenant: Uuid,
|
||||
write: bool,
|
||||
) -> Result<(Principal, Transaction<'a, Postgres>), Error> {
|
||||
let p = crate::jobs::principal(s, headers, write).await?;
|
||||
crate::jobs::scope(&p, tenant, write)?;
|
||||
if p.session_hash.is_none() {
|
||||
return Err(Error(StatusCode::FORBIDDEN, "INTERACTIVE_AUTH_REQUIRED"));
|
||||
}
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "inventory:read").await?;
|
||||
crate::permissions::require_principal(&mut tx, &p, "devices:revoke").await?;
|
||||
Ok((p, tx))
|
||||
}
|
||||
|
||||
async fn select_tenant(tx: &mut Transaction<'_, Postgres>, tenant: Uuid) -> Result<(), Error> {
|
||||
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
|
||||
.bind(tenant.to_string())
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn destination(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
target: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
if target == p.tenant || !p.tenants.contains(&target) {
|
||||
return Err(NOT_FOUND);
|
||||
}
|
||||
select_tenant(tx, target).await?;
|
||||
crate::permissions::require_principal(tx, p, "inventory:read").await?;
|
||||
crate::permissions::require_principal(tx, p, "devices:enroll").await
|
||||
}
|
||||
|
||||
async fn transfer(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
agent: Uuid,
|
||||
) -> Result<Option<Transfer>, Error> {
|
||||
let row = sqlx::query(
|
||||
"SELECT transfer_id,target_tenant_id,target_asset_id,target_agent_id,csr_sha256,requested_by,completed_at
|
||||
FROM device_customer_transfers WHERE source_agent_id=$1 AND cancelled_at IS NULL",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
Ok(row.map(|row| Transfer {
|
||||
transfer_id: row.get("transfer_id"),
|
||||
target_tenant_id: row.get("target_tenant_id"),
|
||||
target_asset_id: row.get("target_asset_id"),
|
||||
target_agent_id: row.get("target_agent_id"),
|
||||
csr_sha256: row.get("csr_sha256"),
|
||||
requested_by: row.get("requested_by"),
|
||||
completed_at: row.get("completed_at"),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn target_hostname(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
t: &Transfer,
|
||||
) -> Result<Option<String>, Error> {
|
||||
let (Some(asset), Some(agent)) = (t.target_asset_id, t.target_agent_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(sqlx::query_scalar(
|
||||
"SELECT o.data->>'hostname' FROM agent_installations a
|
||||
JOIN LATERAL (
|
||||
SELECT data FROM observations WHERE tenant_id=a.tenant_id AND agent_id=a.agent_id AND source_id IN ('linux.base','windows.base')
|
||||
ORDER BY observed_at DESC, received_at DESC, sequence DESC LIMIT 1
|
||||
) o ON true
|
||||
WHERE a.asset_id=$1 AND a.agent_id=$2 AND a.revoked_at IS NULL
|
||||
AND a.last_authenticated_at IS NOT NULL AND length(o.data->>'hostname')>0",
|
||||
)
|
||||
.bind(asset).bind(agent)
|
||||
.fetch_optional(&mut **tx).await?)
|
||||
}
|
||||
|
||||
async fn status(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, false).await?;
|
||||
verify_pairing(&mut tx, asset, pair.agent_id).await?;
|
||||
let Some(t) = transfer(&mut tx, pair.agent_id).await? else {
|
||||
return Ok(private_json(json!({"transfer":null})));
|
||||
};
|
||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||
let hostname = target_hostname(&mut tx, &t).await?;
|
||||
let state = if t.completed_at.is_some() {
|
||||
"completed"
|
||||
} else if hostname.is_some() {
|
||||
"ready"
|
||||
} else if t.target_agent_id.is_some() {
|
||||
"enrolled"
|
||||
} else {
|
||||
"pending"
|
||||
};
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"transfer":{
|
||||
"transfer_id":t.transfer_id, "state":state,
|
||||
"target_tenant_id":t.target_tenant_id, "target_asset_id":t.target_asset_id,
|
||||
"target_agent_id":t.target_agent_id, "target_hostname":hostname
|
||||
}})))
|
||||
}
|
||||
|
||||
async fn lock_source(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
tenant: Uuid,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
) -> Result<bool, Error> {
|
||||
crate::agent_service::control_lock(tx, tenant, agent).await?;
|
||||
sqlx::query_scalar(
|
||||
"SELECT i.revoked_at IS NULL AND i.last_authenticated_at IS NOT NULL AND a.archived_at IS NULL
|
||||
FROM agent_installations i JOIN assets a USING (tenant_id,asset_id)
|
||||
WHERE i.asset_id=$1 AND i.agent_id=$2 FOR UPDATE OF i",
|
||||
)
|
||||
.bind(asset)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn ensure_idle(tx: &mut Transaction<'_, Postgres>, agent: Uuid) -> Result<(), Error> {
|
||||
let busy: bool = sqlx::query_scalar(
|
||||
"SELECT EXISTS(SELECT FROM jobs WHERE agent_id=$1
|
||||
AND state NOT IN ('succeeded','failed','cancelled','expired','closed_unknown'))
|
||||
OR EXISTS(SELECT FROM approval_requests r JOIN operation_plans p USING(tenant_id,plan_id)
|
||||
WHERE r.approval_state='pending_approval' AND p.expires_at>now()
|
||||
AND convert_from(p.payload,'UTF8')::jsonb->'jobs'
|
||||
@> jsonb_build_array(jsonb_build_object('payload',jsonb_build_object('agent_id',$1::uuid))))",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_one(&mut **tx)
|
||||
.await?;
|
||||
if busy {
|
||||
return Err(Error(StatusCode::CONFLICT, "DEVICE_HAS_OPEN_WORK"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn audit(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
p: &Principal,
|
||||
event: &str,
|
||||
details: Value,
|
||||
) -> Result<(), Error> {
|
||||
sqlx::query("INSERT INTO audit_events VALUES($1,$2,$3,$4,$5,now())")
|
||||
.bind(p.tenant).bind(Uuid::new_v4()).bind(&p.name).bind(event)
|
||||
.bind(json!({"decision":details,"session_hash":p.session_hash,"approval_origin":p.approval_origin(),"testsimulation":p.testsimulation}))
|
||||
.execute(&mut **tx).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn begin(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset)): Path<(Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
Json(input): Json<Destination>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||
destination(&mut tx, &p, input.target_tenant_id).await?;
|
||||
crate::agent_updates::ensure_customer_starters(&mut tx, input.target_tenant_id).await?;
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
if !lock_source(&mut tx, tenant, asset, pair.agent_id).await? {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_SOURCE_INACTIVE"));
|
||||
}
|
||||
ensure_idle(&mut tx, pair.agent_id).await?;
|
||||
let supported: bool =
|
||||
sqlx::query_scalar("SELECT capabilities ? $2 FROM agent_installations WHERE agent_id=$1")
|
||||
.bind(pair.agent_id)
|
||||
.bind(wire::CAPABILITY)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !supported {
|
||||
return Err(Error(
|
||||
StatusCode::CONFLICT,
|
||||
"TRANSFER_AGENT_UPDATE_REQUIRED",
|
||||
));
|
||||
}
|
||||
if transfer(&mut tx, pair.agent_id).await?.is_some() {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_PENDING"));
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
sqlx::query(
|
||||
"INSERT INTO device_customer_transfers(transfer_id,source_tenant_id,source_asset_id,source_agent_id,target_tenant_id,requested_by)
|
||||
VALUES($1,$2,$3,$4,$5,$6)",
|
||||
).bind(id).bind(tenant).bind(asset).bind(pair.agent_id).bind(input.target_tenant_id).bind(&p.name)
|
||||
.execute(&mut *tx).await?;
|
||||
audit(&mut tx, &p, "device_customer_transfer_prepared", json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":input.target_tenant_id
|
||||
})).await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"transfer_id":id,"state":"pending"})))
|
||||
}
|
||||
|
||||
async fn verify_pairing(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
asset: Uuid,
|
||||
agent: Uuid,
|
||||
) -> Result<(), Error> {
|
||||
sqlx::query_scalar::<_, Uuid>(
|
||||
"SELECT agent_id FROM agent_installations WHERE asset_id=$1 AND agent_id=$2",
|
||||
)
|
||||
.bind(asset)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cancel(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<StatusCode, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
|
||||
let changed = sqlx::query(
|
||||
"UPDATE device_customer_transfers SET cancelled_at=now()
|
||||
WHERE transfer_id=$1 AND source_agent_id=$2 AND target_agent_id IS NULL AND cancelled_at IS NULL",
|
||||
).bind(id).bind(pair.agent_id).execute(&mut *tx).await?.rows_affected();
|
||||
if changed == 0 {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_ALREADY_STARTED"));
|
||||
}
|
||||
audit(
|
||||
&mut tx,
|
||||
&p,
|
||||
"device_customer_transfer_cancelled",
|
||||
json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn complete(
|
||||
State(s): State<crate::State>,
|
||||
headers: HeaderMap,
|
||||
Path((tenant, asset, id)): Path<(Uuid, Uuid, Uuid)>,
|
||||
Query(pair): Query<Pairing>,
|
||||
) -> Result<Response, Error> {
|
||||
let (p, mut tx) = source(&s, &headers, tenant, true).await?;
|
||||
lock_source(&mut tx, tenant, asset, pair.agent_id).await?;
|
||||
let t = transfer(&mut tx, pair.agent_id)
|
||||
.await?
|
||||
.filter(|t| t.transfer_id == id)
|
||||
.ok_or(NOT_FOUND)?;
|
||||
destination(&mut tx, &p, t.target_tenant_id).await?;
|
||||
if t.completed_at.is_some() {
|
||||
return Ok(private_json(json!({"state":"completed"})));
|
||||
}
|
||||
if target_hostname(&mut tx, &t).await?.is_none() {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_TARGET_NOT_READY"));
|
||||
}
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
ensure_idle(&mut tx, pair.agent_id).await?;
|
||||
sqlx::query(
|
||||
"UPDATE agent_installations SET revoked_at=now(), connection_generation=connection_generation+1,
|
||||
previous_certificate_sha256=NULL,previous_certificate_until=NULL
|
||||
WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
|
||||
)
|
||||
.bind(asset).bind(pair.agent_id).execute(&mut *tx).await?;
|
||||
sqlx::query("UPDATE device_customer_transfers SET completed_at=now() WHERE transfer_id=$1")
|
||||
.bind(id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
audit(&mut tx, &p, "device_customer_transfer_completed", json!({
|
||||
"transfer_id":id,"asset_id":asset,"agent_id":pair.agent_id,"target_tenant_id":t.target_tenant_id,
|
||||
"target_asset_id":t.target_asset_id,"target_agent_id":t.target_agent_id
|
||||
})).await?;
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"state":"completed"})))
|
||||
}
|
||||
|
||||
async fn device_offer(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
let offer = transfer(&mut tx, agent)
|
||||
.await?
|
||||
.filter(|t| t.completed_at.is_none())
|
||||
.map(|t| offer(tenant, agent, &t));
|
||||
tx.commit().await?;
|
||||
Ok(private_json(json!({"offer":offer})))
|
||||
}
|
||||
|
||||
fn offer(tenant: Uuid, agent: Uuid, t: &Transfer) -> wire::Offer {
|
||||
wire::Offer {
|
||||
transfer_id: t.transfer_id,
|
||||
source_tenant_id: tenant,
|
||||
source_agent_id: agent,
|
||||
target_tenant_id: t.target_tenant_id,
|
||||
}
|
||||
}
|
||||
|
||||
async fn device_certificate(
|
||||
State(s): State<crate::State>,
|
||||
Extension(peer): Extension<crate::Peer>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(input): Json<wire::CertificateRequest>,
|
||||
) -> Result<Response, Error> {
|
||||
let (tenant, agent) = crate::agent_updates::device(&s, peer, &headers).await?;
|
||||
let invalid = || Error(StatusCode::BAD_REQUEST, "INVALID_CSR");
|
||||
if input.csr_pem.len() > 8192 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let csr = openssl::x509::X509Req::from_pem(input.csr_pem.as_bytes()).map_err(|_| invalid())?;
|
||||
let public = csr.public_key().map_err(|_| invalid())?;
|
||||
if !csr.verify(&public).map_err(|_| invalid())? {
|
||||
return Err(invalid());
|
||||
}
|
||||
let digest = hash(&public.public_key_to_der().map_err(|_| invalid())?);
|
||||
let mut tx = rmm_persistence::tenant_tx(&s.pool, tenant).await?;
|
||||
crate::agent_service::control_lock(&mut tx, tenant, agent).await?;
|
||||
let (asset, generation): (Uuid, i64) = sqlx::query_as(
|
||||
"SELECT asset_id,connection_generation FROM agent_installations
|
||||
WHERE agent_id=$1 AND revoked_at IS NULL FOR UPDATE",
|
||||
)
|
||||
.bind(agent)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or(NOT_FOUND)?;
|
||||
let t = transfer(&mut tx, agent)
|
||||
.await?
|
||||
.filter(|t| t.transfer_id == id && t.completed_at.is_none())
|
||||
.ok_or(NOT_FOUND)?;
|
||||
ensure_idle(&mut tx, agent).await?;
|
||||
if t.target_agent_id.is_none() {
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "devices:revoke").await?;
|
||||
}
|
||||
select_tenant(&mut tx, t.target_tenant_id).await?;
|
||||
let (new_asset, new_agent, certificate_pem) = if let (Some(target_asset), Some(target_agent)) =
|
||||
(t.target_asset_id, t.target_agent_id)
|
||||
{
|
||||
if t.csr_sha256.as_deref() != Some(&digest) {
|
||||
return Err(Error(StatusCode::CONFLICT, "TRANSFER_KEY_MISMATCH"));
|
||||
}
|
||||
let pem: String = sqlx::query_scalar(
|
||||
"SELECT certificate_pem FROM agent_installations WHERE asset_id=$1 AND agent_id=$2 AND revoked_at IS NULL",
|
||||
).bind(target_asset).bind(target_agent).fetch_optional(&mut *tx).await?.ok_or(NOT_FOUND)?;
|
||||
sqlx::query(
|
||||
"UPDATE agent_installations SET connection_generation=GREATEST(connection_generation,$2)
|
||||
WHERE agent_id=$1 AND last_authenticated_at IS NULL",
|
||||
).bind(target_agent).bind(generation).execute(&mut *tx).await?;
|
||||
(target_asset, target_agent, pem)
|
||||
} else {
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "inventory:read").await?;
|
||||
crate::permissions::require(&mut tx, &t.requested_by, "devices:enroll").await?;
|
||||
let new_asset = Uuid::new_v4();
|
||||
let new_agent = Uuid::new_v4();
|
||||
let certificate =
|
||||
crate::tls::issue(&s, &input.csr_pem, new_agent).map_err(|_| invalid())?;
|
||||
let pem = String::from_utf8(certificate.to_pem().map_err(anyhow::Error::from)?)
|
||||
.map_err(anyhow::Error::from)?;
|
||||
sqlx::query("INSERT INTO assets(tenant_id,asset_id) VALUES($1,$2)")
|
||||
.bind(t.target_tenant_id)
|
||||
.bind(new_asset)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation)
|
||||
VALUES($1,$2,$3,$4,$5,$6)",
|
||||
).bind(t.target_tenant_id).bind(new_asset).bind(new_agent)
|
||||
.bind(hash(&certificate.to_der().map_err(anyhow::Error::from)?)).bind(&pem).bind(generation)
|
||||
.execute(&mut *tx).await?;
|
||||
select_tenant(&mut tx, tenant).await?;
|
||||
sqlx::query(
|
||||
"UPDATE device_customer_transfers SET target_asset_id=$2,target_agent_id=$3,csr_sha256=$4
|
||||
WHERE transfer_id=$1 AND source_asset_id=$5",
|
||||
).bind(id).bind(new_asset).bind(new_agent).bind(digest).bind(asset).execute(&mut *tx).await?;
|
||||
(new_asset, new_agent, pem)
|
||||
};
|
||||
let binding = wire::Binding {
|
||||
offer: offer(tenant, agent, &t),
|
||||
asset_id: new_asset,
|
||||
agent_id: new_agent,
|
||||
certificate_sha256: hash(certificate_pem.as_bytes()),
|
||||
};
|
||||
let signature_hex = hex::encode(s.job_signer.sign(&binding.signing_bytes()?)?);
|
||||
tx.commit().await?;
|
||||
Ok((
|
||||
[("cache-control", "private, no-store")],
|
||||
Json(wire::CertificateResponse {
|
||||
certificate_pem,
|
||||
receipt: wire::Receipt {
|
||||
binding,
|
||||
signature_hex,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.into_response())
|
||||
}
|
||||
@@ -427,7 +427,7 @@ pub(crate) async fn plan_resolved(
|
||||
let artifacts = crate::catalog::resolve_artifacts(&mut tx, tenant, &input.artifact_ids).await?;
|
||||
let mut jobs = Vec::new();
|
||||
for asset in ids {
|
||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||
let rows=sqlx::query("SELECT agent_id,enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE asset_id=$1 AND revoked_at IS NULL AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) ORDER BY agent_id FOR SHARE").bind(asset).fetch_all(&mut *tx).await?;
|
||||
if rows.len() != 1 {
|
||||
return Err(fail(if rows.is_empty() {
|
||||
"NOT_FOUND"
|
||||
@@ -683,7 +683,7 @@ async fn recheck_for(
|
||||
if job.payload.start_before <= Utc::now() {
|
||||
return Err(fail("PLAN_EXPIRED"));
|
||||
}
|
||||
let r=sqlx::query("SELECT enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL FOR SHARE").bind(job.payload.agent_id).bind(job.payload.asset_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AUTHORIZATION_REVOKED"))?;
|
||||
let r=sqlx::query("SELECT enrollment_generation,assignment_version,capabilities FROM agent_installations WHERE agent_id=$1 AND asset_id=$2 AND revoked_at IS NULL AND NOT EXISTS (SELECT FROM device_customer_transfers t WHERE t.source_agent_id=agent_installations.agent_id AND t.completed_at IS NULL AND t.cancelled_at IS NULL) FOR SHARE").bind(job.payload.agent_id).bind(job.payload.asset_id).fetch_optional(&mut **tx).await?.ok_or_else(||fail("AUTHORIZATION_REVOKED"))?;
|
||||
if r.get::<i64, _>("assignment_version") as u64 != job.payload.assignment_version
|
||||
|| r.get::<i64, _>("enrollment_generation") as u64 != job.payload.enrollment_generation
|
||||
{
|
||||
|
||||
@@ -13,6 +13,7 @@ mod auth;
|
||||
mod local_auth;
|
||||
mod mcp_tokens;
|
||||
mod customers;
|
||||
mod customer_transfer;
|
||||
mod catalog;
|
||||
mod checkpoint_repair;
|
||||
mod controls;
|
||||
@@ -174,7 +175,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
let mut routes = Router::new().route("/healthz", get(|| async { "ok" }));
|
||||
if role.gateway() {
|
||||
routes = agent_updates::gateway_routes(routes);
|
||||
routes = customer_transfer::gateway_routes(agent_updates::gateway_routes(routes));
|
||||
routes = agent_update_health::gateway_routes(routes);
|
||||
routes = agent_time::gateway_routes(routes);
|
||||
routes = routes
|
||||
@@ -221,7 +222,7 @@ async fn main() -> Result<()> {
|
||||
routes = routes.route("/auth/local/login", post(auth::local_login));
|
||||
routes = jobs::routes(routes);
|
||||
routes = script_library::routes(routes);
|
||||
routes = controls::routes(routes);
|
||||
routes = customer_transfer::routes(controls::routes(routes));
|
||||
routes = catalog::routes(routes);
|
||||
routes = agent_updates::routes(routes);
|
||||
routes = routes
|
||||
|
||||
Reference in New Issue
Block a user