Complete customer transfers on first authenticated inventory
Rust development slice / linux (push) Failing after 8s

This commit is contained in:
2026-11-18 22:57:05 +01:00
parent 65d84a19c0
commit 480e3749a6
13 changed files with 234 additions and 76 deletions
+11 -1
View File
@@ -105,7 +105,7 @@ pub async fn ingest(
);
let mut tx = rmm_persistence::tenant_tx(&state.pool, tenant).await?;
control_lock(&mut tx, tenant, agent).await?;
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
let row=sqlx::query("SELECT revoked_at,connection_generation,transport,connection_boot_id,last_sequence,capabilities,customer_transfer_pending FROM agent_installations WHERE agent_id=$1 FOR UPDATE").bind(agent).fetch_one(&mut *tx).await?;
let active = row.get::<Option<DateTime<Utc>>, _>("revoked_at").is_none()
&& row.get::<i64, _>("connection_generation") == i64::try_from(e.connection_generation)?
&& row.get::<String, _>("transport") == transport;
@@ -196,6 +196,16 @@ pub async fn ingest(
}
_ => anyhow::bail!("unsupported capability"),
}
if row.get::<bool, _>("customer_transfer_pending")
&& (matches!(&e.payload, Some(Payload::Heartbeat(_)))
|| matches!(&e.payload, Some(Payload::InventorySnapshot(s)) if s.scope != "agent.update"))
{
sqlx::query("SELECT finish_device_customer_transfer($1,$2)")
.bind(tenant)
.bind(agent)
.execute(&mut *tx)
.await?;
}
tx.commit().await?;
Ok(reply(
e,
+11 -27
View File
@@ -158,11 +158,13 @@ async fn status(
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 hostname = if t.completed_at.is_some() {
target_hostname(&mut tx, &t).await?
} else {
None
};
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 {
@@ -186,7 +188,7 @@ async fn lock_source(
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",
WHERE i.asset_id=$1 AND i.agent_id=$2 AND NOT i.customer_transfer_pending FOR UPDATE OF i",
)
.bind(asset)
.bind(agent)
@@ -320,34 +322,16 @@ async fn complete(
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?;
verify_pairing(&mut tx, 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() {
// Older WebUI bundles may still request completion after the atomic cutover.
if t.completed_at.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"})))
}
@@ -443,8 +427,8 @@ async fn device_certificate(
.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)",
"INSERT INTO agent_installations(tenant_id,asset_id,agent_id,certificate_sha256,certificate_pem,connection_generation,customer_transfer_pending)
VALUES($1,$2,$3,$4,$5,$6,true)",
).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?;
+2
View File
@@ -25,6 +25,8 @@ WITH classified AS (
JOIN assets asset USING (tenant_id,asset_id)
JOIN tenants t USING(tenant_id)
WHERE a.tenant_id=$1 AND a.created_at<=$2 AND a.agent_id>$3
AND NOT a.customer_transfer_pending
AND (a.customer_transfer_activated_at IS NULL OR a.customer_transfer_activated_at<=$2)
AND ($4::uuid IS NULL OR a.asset_id=$4)
AND ($5::uuid IS NULL OR a.agent_id=$5)
)
+26 -2
View File
@@ -128,6 +128,7 @@ pub async fn list(
"device-fleet:{}",
rmm_domain::jobs::hash(binding.to_string().as_bytes())
);
let first_page = q.cursor.is_none();
let mut page = Cursor::parse(
s,
&p,
@@ -143,10 +144,15 @@ pub async fn list(
let mut last = None;
let mut truncated = false;
let mut authorized = false;
let mut principals = Vec::new();
for customer in tenants {
if page.last_tenant.is_some_and(|after| customer < after) {
continue;
}
if customer == p.tenant {
principals.push(p.clone());
continue;
}
let mut headers = h.clone();
headers.insert(
"x-rmm-tenant",
@@ -155,7 +161,25 @@ pub async fn list(
);
let current = crate::jobs::principal(s, &headers, false).await?;
crate::jobs::scope(&current, customer, false)?;
let mut tx = rmm_persistence::tenant_tx(&s.pool, customer).await?;
principals.push(current);
}
// Read all customers from the same snapshot so a transfer cannot appear
// under both customers if its cutover commits while listing the fleet.
let mut tx = s.pool.begin().await?;
sqlx::query("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
.execute(&mut *tx)
.await?;
if first_page {
page.as_of = sqlx::query_scalar("SELECT clock_timestamp()")
.fetch_one(&mut *tx)
.await?;
}
for current in principals {
let customer = current.tenant;
sqlx::query("SELECT set_config('app.tenant_id',$1,true)")
.bind(customer.to_string())
.execute(&mut *tx)
.await?;
match crate::permissions::require_principal(&mut tx, &current, "inventory:read").await {
Err(Error(StatusCode::FORBIDDEN, _)) if tenant.is_none() => continue,
other => other?,
@@ -179,7 +203,6 @@ pub async fn list(
.rows(&mut tx)
.await?;
let hosts = assigned_hosts(&mut tx, customer, page.as_of, &rows).await?;
tx.commit().await?;
for row in rows {
if items.len() == capacity {
truncated = true;
@@ -192,6 +215,7 @@ pub async fn list(
break;
}
}
tx.commit().await?;
if !authorized {
return Err(Error(StatusCode::FORBIDDEN, "FORBIDDEN"));
}
+2
View File
@@ -4,6 +4,8 @@ JOIN LATERAL (
SELECT a.agent_id, a.revoked_at
FROM agent_installations a
WHERE a.tenant_id=asset.tenant_id AND a.asset_id=asset.asset_id AND a.created_at<=$2
AND NOT a.customer_transfer_pending
AND (a.customer_transfer_activated_at IS NULL OR a.customer_transfer_activated_at<=$2)
AND a.last_authenticated_at IS NOT NULL AND a.last_contact_at IS NOT NULL
ORDER BY a.enrollment_generation DESC, a.created_at DESC, a.agent_id
LIMIT 1
+2 -2
View File
@@ -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 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?;
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 customer_transfer_pending 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 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"))?;
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 customer_transfer_pending 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
{